diff --git a/datafusion/common/src/config.rs b/datafusion/common/src/config.rs index cbb4ef87b48fc..bf4a1314203d6 100644 --- a/datafusion/common/src/config.rs +++ b/datafusion/common/src/config.rs @@ -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 } } @@ -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, diff --git a/datafusion/physical-expr/src/expressions/dynamic_filters/mod.rs b/datafusion/physical-expr/src/expressions/dynamic_filters/mod.rs index eb3d457de82ad..24d935aa6e0bd 100644 --- a/datafusion/physical-expr/src/expressions/dynamic_filters/mod.rs +++ b/datafusion/physical-expr/src/expressions/dynamic_filters/mod.rs @@ -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(()) } @@ -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, }); } @@ -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; @@ -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); + + // 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) + .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) + .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, + )); + 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 diff --git a/datafusion/physical-plan/Cargo.toml b/datafusion/physical-plan/Cargo.toml index 89573f3323548..4bc72b940660c 100644 --- a/datafusion/physical-plan/Cargo.toml +++ b/datafusion/physical-plan/Cargo.toml @@ -103,6 +103,7 @@ tokio = { workspace = true, features = [ "rt-multi-thread", "fs", "parking_lot", + "test-util", ] } [[bench]] diff --git a/datafusion/physical-plan/src/joins/hash_join/adaptive.rs b/datafusion/physical-plan/src/joins/hash_join/adaptive.rs new file mode 100644 index 0000000000000..cdc3e3f4f6c49 --- /dev/null +++ b/datafusion/physical-plan/src/joins/hash_join/adaptive.rs @@ -0,0 +1,1331 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +//! Runtime adaptive build-side selection for partitioned [`super::HashJoinExec`]. +//! +//! Coordinates all partitions of a partitioned hash join through a bounded +//! sampling phase before committing to either building the planned left side +//! (`KeepLeft`) or swapping build and probe roles in-stream (`SwapRight`). + +use std::collections::VecDeque; +use std::pin::Pin; +use std::sync::{Arc, Weak}; +use std::task::{Context, Poll}; +use std::time::Duration; + +use arrow::datatypes::SchemaRef; +use arrow::record_batch::RecordBatch; +use datafusion_common::config::ConfigOptions; +use datafusion_common::instant::Instant; +use datafusion_common::utils::memory::RecordBatchMemoryCounter; +use datafusion_common::{DataFusionError, JoinSide, Result}; +use datafusion_execution::memory_pool::MemoryReservation; +use datafusion_physical_expr::PhysicalExprRef; +use futures::future::BoxFuture; +use futures::{Stream, StreamExt}; +use parking_lot::Mutex; +use tokio::sync::watch; + +use crate::joins::hash_join::shared_bounds::SharedBuildAccumulator; +use crate::metrics::{ + Count, ExecutionPlanMetricsSet, MetricBuilder, MetricCategory, MetricValue, Time, +}; +use crate::stream::EmptyRecordBatchStream; +use crate::{RecordBatchStream, SendableRecordBatchStream}; + +/// Coordinator lifecycle phase shared across all partitions of a build generation. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum Phase { + /// Sampling the planned left (build) side up to the join-wide threshold. + SampleLeft, + /// Planned left exceeded the threshold; one partition is discharging the + /// dynamic-filter accumulator before transitioning to `SampleRight`. + /// Peers park instead of polling or buffering additional left batches. + ReleasingFilter, + /// Planned left exceeded the threshold; sampling the planned right (probe) side. + SampleRight, + /// Terminal build-side decision has been reached. + Decided(Decision), +} + +/// Terminal build-side decision for a build generation. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum Decision { + /// Keep the planned left side as the build side. + KeepLeft(Reason), + /// Swap roles in-stream so the planned right side becomes the build side. + SwapRight, +} + +/// Reason why the coordinator kept the planned left side. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum Reason { + LeftSmall, + RightCrossed, + RightError, + Abandoned, + Duplicate, +} + +/// Result of claiming a partition slot on [`AdaptiveBuildCoordinator`]. +pub(super) enum Claim { + /// Partition owns an exclusive adaptive sampling ticket for this generation. + Adaptive(Ticket), + /// Partition should execute the stock path using this generation's accumulator. + Stock, + /// Partition should execute the stock path without attaching to the accumulator + /// because the generation has already released and finalized its dynamic filter. + StockDetached, +} + +/// Join-wide decision-reason counters (incremented at most once per generation). +struct DecisionReasonMetrics { + swap_right: Count, + left_small: Count, + right_crossed: Count, + right_error: Count, + abandoned: Count, + duplicate: Count, +} + +impl DecisionReasonMetrics { + fn new(metrics: &ExecutionPlanMetricsSet) -> Self { + let c = |name| MetricBuilder::new(metrics).global_counter(name); + Self { + swap_right: c("adaptive_decision_reason_swap_right"), + left_small: c("adaptive_decision_reason_left_small"), + right_crossed: c("adaptive_decision_reason_right_crossed"), + right_error: c("adaptive_decision_reason_right_error"), + abandoned: c("adaptive_decision_reason_abandoned"), + duplicate: c("adaptive_decision_reason_duplicate"), + } + } + + fn record(&self, decision: Decision) { + match decision { + Decision::SwapRight => self.swap_right.add(1), + Decision::KeepLeft(Reason::LeftSmall) => self.left_small.add(1), + Decision::KeepLeft(Reason::RightCrossed) => self.right_crossed.add(1), + Decision::KeepLeft(Reason::RightError) => self.right_error.add(1), + Decision::KeepLeft(Reason::Abandoned) => self.abandoned.add(1), + Decision::KeepLeft(Reason::Duplicate) => self.duplicate.add(1), + } + } +} + +/// Per-partition metrics for adaptive build-side selection. +pub(super) struct AdaptiveMetrics { + pub(super) build_swapped: Count, + pub(super) right_sampled: Count, + pub(super) sampled_left_bytes: Count, + pub(super) sampled_right_bytes: Count, + /// Per-partition elapsed time spent inside `poll_adaptive_sample` + /// (excluding parked time between polls; not OS thread CPU time). + pub(super) sample_poll_time: Time, +} + +impl AdaptiveMetrics { + pub(super) fn new(partition: usize, metrics: &ExecutionPlanMetricsSet) -> Self { + Self { + build_swapped: MetricBuilder::new(metrics) + .counter("adaptive_build_swapped", partition), + right_sampled: MetricBuilder::new(metrics) + .counter("adaptive_right_sampled", partition), + sampled_left_bytes: MetricBuilder::new(metrics) + .with_category(MetricCategory::Bytes) + .counter("adaptive_sampled_left_bytes", partition), + sampled_right_bytes: MetricBuilder::new(metrics) + .with_category(MetricCategory::Bytes) + .counter("adaptive_sampled_right_bytes", partition), + sample_poll_time: MetricBuilder::new(metrics) + .subset_time("adaptive_sample_poll_time", partition), + } + } +} + +#[derive(Debug, Default)] +struct Side { + bytes: usize, + rows: usize, + batches: usize, + done: usize, +} + +impl Side { + fn add(&mut self, bytes: usize, rows: usize) { + self.bytes = self.bytes.saturating_add(bytes); + self.rows = self.rows.saturating_add(rows); + self.batches = self.batches.saturating_add(1); + } +} + +struct Inner { + phase: Phase, + /// Monotonic flag set to `true` by the single partition that triggers the + /// transition from `SampleLeft` to `SampleRight` and owns calling + /// `SharedBuildAccumulator::cancel_all_partitions_and_wait()`. Never set + /// after `phase` reaches `Phase::Decided`. + filter_released: bool, + /// Wall-clock timestamp recorded on the first `claim()` for this generation. + first_claim_at: Option, + l: Side, + r: Side, + claimed: Vec, +} + +/// Coordinates runtime adaptive build-side selection across all partitions +/// belonging to one build generation. +pub(super) struct AdaptiveBuildCoordinator { + p: usize, + cap: usize, + max_batches: usize, + max_rows: usize, + accumulator: Weak, + inner: Mutex, + tx: watch::Sender, + reason_metrics: DecisionReasonMetrics, + decision_wall_time: Time, + #[cfg(test)] + before_filter_release_hook: Mutex>>, + #[cfg(test)] + before_watch_build_hook: Mutex>>, +} + +impl AdaptiveBuildCoordinator { + pub(super) fn new( + p: usize, + cap: usize, + batch_size: usize, + accumulator: &Arc, + metrics: &ExecutionPlanMetricsSet, + ) -> Arc { + let max_batches = 64usize.saturating_mul(p); + let max_rows = max_batches.saturating_mul(batch_size.max(1)); + let (tx, _rx) = watch::channel(Phase::SampleLeft); + let decision_wall_time = Time::new(); + MetricBuilder::new(metrics) + .with_category(MetricCategory::Timing) + .build(MetricValue::Time { + name: "adaptive_decision_wall_time".into(), + time: decision_wall_time.clone(), + }); + Arc::new(Self { + p, + cap, + max_batches, + max_rows, + accumulator: Arc::downgrade(accumulator), + inner: Mutex::new(Inner { + phase: Phase::SampleLeft, + filter_released: false, + first_claim_at: None, + l: Side::default(), + r: Side::default(), + claimed: vec![false; p], + }), + tx, + reason_metrics: DecisionReasonMetrics::new(metrics), + decision_wall_time, + #[cfg(test)] + before_filter_release_hook: Mutex::new(None), + #[cfg(test)] + before_watch_build_hook: Mutex::new(None), + }) + } + + #[cfg(test)] + pub(super) fn set_before_filter_release_hook( + &self, + hook: Option>, + ) { + *self.before_filter_release_hook.lock() = hook; + } + + #[cfg(test)] + pub(super) fn set_before_watch_build_hook( + &self, + hook: Option>, + ) { + *self.before_watch_build_hook.lock() = hook; + } + + #[cfg(test)] + pub(super) fn run_before_watch_build_hook(&self) { + let hook = self.before_watch_build_hook.lock().take(); + if let Some(hook) = hook { + hook(); + } + } + + #[cfg(test)] + pub(super) fn accumulator_completed_partitions_for_test(&self) -> usize { + let acc = self + .accumulator + .upgrade() + .expect("accumulator should still be alive"); + crate::joins::hash_join::shared_bounds::completed_partitions_for_test(&acc) + } + + fn over(&self, side: &Side) -> bool { + side.bytes > self.cap + || side.batches > self.max_batches + || side.rows > self.max_rows + } + + fn transition_to_decided_locked( + &self, + inner: &mut Inner, + decision: Decision, + ) -> Decision { + if let Phase::Decided(existing) = inner.phase { + return existing; + } + inner.phase = Phase::Decided(decision); + self.reason_metrics.record(decision); + if let Some(started_at) = inner.first_claim_at { + // Saturate to `usize::MAX` nanoseconds so 32-bit targets saturate + // instead of wrapping inside `Time::add_duration`. + let nanos = started_at.elapsed().as_nanos().min(usize::MAX as u128); + let dur = Duration::from_nanos(u64::try_from(nanos).unwrap_or(u64::MAX)); + self.decision_wall_time.add_duration(dur); + } + self.tx.send_replace(inner.phase); + decision + } + + /// Returns whether dynamic-filter release (`SampleLeft` -> `ReleasingFilter` + /// -> `SampleRight`) has started or completed for this generation. + pub(super) fn is_filter_released(&self) -> bool { + self.inner.lock().filter_released + } + + /// Synchronously claims an exclusive adaptive ticket for `partition`. + /// Must be called before opening child streams. + pub(super) fn claim(self: &Arc, partition: usize) -> Claim { + let mut inner = self.inner.lock(); + inner.first_claim_at.get_or_insert_with(Instant::now); + if matches!( + inner.phase, + Phase::SampleLeft | Phase::ReleasingFilter | Phase::SampleRight + ) { + match inner.claimed.get_mut(partition) { + Some(slot) if !*slot => { + *slot = true; + return Claim::Adaptive(Ticket { + coordinator: Arc::clone(self), + }); + } + _ => { + self.transition_to_decided_locked( + &mut inner, + Decision::KeepLeft(Reason::Duplicate), + ); + } + } + } + + if inner.filter_released { + Claim::StockDetached + } else { + Claim::Stock + } + } + + /// Returns the last published phase from the watch channel. + pub(super) fn phase(&self) -> Phase { + *self.tx.borrow() + } + + /// Subscribes to phase updates published by this coordinator. + pub(super) fn subscribe(&self) -> watch::Receiver { + self.tx.subscribe() + } + + fn record_batch_locked( + &self, + inner: &mut Inner, + side: JoinSide, + bytes: usize, + rows: usize, + ) -> bool { + match side { + JoinSide::Left => { + inner.l.add(bytes, rows); + if inner.phase == Phase::SampleLeft + && !inner.filter_released + && self.over(&inner.l) + { + inner.filter_released = true; + inner.phase = Phase::ReleasingFilter; + self.tx.send_replace(Phase::ReleasingFilter); + true + } else { + false + } + } + JoinSide::Right => { + inner.r.add(bytes, rows); + if inner.phase == Phase::SampleRight && self.over(&inner.r) { + self.transition_to_decided_locked( + inner, + Decision::KeepLeft(Reason::RightCrossed), + ); + } + false + } + JoinSide::None => false, + } + } + + fn release_filter_and_enter_sample_right(&self) { + #[cfg(test)] + { + let hook = self.before_filter_release_hook.lock().clone(); + if let Some(hook) = hook { + hook(); + } + } + if let Some(acc) = self.accumulator.upgrade() { + acc.cancel_all_partitions_and_wait(); + } + let mut inner = self.inner.lock(); + if inner.phase == Phase::ReleasingFilter { + inner.phase = Phase::SampleRight; + self.tx.send_replace(Phase::SampleRight); + } + } + + /// Admits a batch returned by an in-flight child poll, serialized with + /// coordinator phase transitions under `self.inner`. + /// + /// While the coordinator is still in `side`'s sampling phase, this reserves + /// memory in `buf`, records the batch on the coordinator, and returns + /// `Ok(Some(bytes))`. If another partition already transitioned the + /// coordinator out of `side`'s sampling phase (for example, `SampleLeft` -> + /// `ReleasingFilter`) before the poll returned, the batch is stashed + /// unreserved in `buf` for exact-order replay without touching `buf.res` + /// and this returns `Ok(None)`. + /// + /// When the planned left side first exceeds the sampling limit in + /// `SampleLeft`, the winning partition transitions the coordinator to + /// `ReleasingFilter` under the lock (parking peers so they stop polling + /// and buffering `Left`), discharges all `P` accumulator slots and waits + /// for actual filter completion (`lit(true)`) outside the lock, and only + /// then publishes `SampleRight` to peers (unless a terminal decision was + /// reached concurrently during the release window). + pub(super) fn admit_batch( + &self, + side: JoinSide, + buf: &mut SideBuf, + batch: RecordBatch, + ) -> Result> { + let expected_phase = match side { + JoinSide::Left => Phase::SampleLeft, + JoinSide::Right => Phase::SampleRight, + JoinSide::None => return Ok(None), + }; + let rows = batch.num_rows(); + let (bytes, should_release_filter) = { + let mut inner = self.inner.lock(); + if inner.phase != expected_phase { + buf.push_unreserved(batch); + return Ok(None); + } + let bytes = buf.push_batch(batch)?; + let should_release_filter = + self.record_batch_locked(&mut inner, side, bytes, rows); + (bytes, should_release_filter) + }; + + if should_release_filter { + self.release_filter_and_enter_sample_right(); + } + + Ok(Some(bytes)) + } + + /// Records a sampled batch directly (used by coordinator unit tests). + #[cfg(test)] + pub(super) fn on_batch(&self, side: JoinSide, bytes: usize, rows: usize) { + let should_release_filter = { + let mut inner = self.inner.lock(); + self.record_batch_locked(&mut inner, side, bytes, rows) + }; + + if should_release_filter { + self.release_filter_and_enter_sample_right(); + } + } + + /// Records EOF for one partition on `side`. + /// + /// When the final partition hits `Right` EOF in `SampleRight`, the dynamic + /// filter has already been discharged upon entering `SampleRight`, so this + /// publishes `Decided(SwapRight)` directly. + pub(super) fn on_eof(&self, side: JoinSide) { + let mut inner = self.inner.lock(); + match side { + JoinSide::Left => { + inner.l.done += 1; + if inner.phase == Phase::SampleLeft + && !inner.filter_released + && inner.l.done == self.p + { + self.transition_to_decided_locked( + &mut inner, + Decision::KeepLeft(Reason::LeftSmall), + ); + } + } + JoinSide::Right => { + inner.r.done += 1; + if inner.phase == Phase::SampleRight && inner.r.done == self.p { + debug_assert!(inner.filter_released); + self.transition_to_decided_locked(&mut inner, Decision::SwapRight); + } + } + JoinSide::None => {} + } + } + + /// Transitions to `Decided(KeepLeft(reason))` if not already decided, + /// returning the terminal decision. Idempotent. + pub(super) fn abandon(&self, reason: Reason) -> Decision { + let mut inner = self.inner.lock(); + self.transition_to_decided_locked(&mut inner, Decision::KeepLeft(reason)) + } +} + +/// Exclusive per-partition RAII ticket into an [`AdaptiveBuildCoordinator`]. +/// +/// Dropping a ticket before a terminal decision abandons adaptive sampling +/// so sibling partitions never strand. +pub(super) struct Ticket { + coordinator: Arc, +} + +impl Ticket { + pub(super) fn phase(&self) -> Phase { + self.coordinator.phase() + } + + pub(super) fn subscribe(&self) -> watch::Receiver { + self.coordinator.subscribe() + } + + pub(super) fn is_filter_released(&self) -> bool { + self.coordinator.is_filter_released() + } + + pub(super) fn admit_batch( + &self, + side: JoinSide, + buf: &mut SideBuf, + batch: RecordBatch, + ) -> Result> { + self.coordinator.admit_batch(side, buf, batch) + } + + #[cfg(test)] + pub(super) fn on_batch(&self, side: JoinSide, bytes: usize, rows: usize) { + self.coordinator.on_batch(side, bytes, rows); + } + + pub(super) fn on_eof(&self, side: JoinSide) { + self.coordinator.on_eof(side); + } + + pub(super) fn abandon(&self, reason: Reason) -> Decision { + self.coordinator.abandon(reason) + } + + #[cfg(test)] + pub(super) fn run_before_watch_build_hook(&self) { + self.coordinator.run_before_watch_build_hook(); + } +} + +impl Drop for Ticket { + fn drop(&mut self) { + self.coordinator.abandon(Reason::Abandoned); + } +} + +/// Pre-sampled batches, deduplicating memory counter, and already-grown +/// reservation handed into `collect_left_input`. +pub(super) struct BuildPrefix { + pub(super) batches: Vec, + pub(super) counter: RecordBatchMemoryCounter, + pub(super) reservation: MemoryReservation, +} + +impl BuildPrefix { + pub(super) fn empty(reservation: MemoryReservation) -> Self { + Self { + batches: Vec::new(), + counter: RecordBatchMemoryCounter::new(), + reservation, + } + } +} + +/// Per-side sample buffer holding sampled batches and their reserved memory. +pub(super) struct SideBuf { + pub(super) batches: VecDeque, + /// Trailing batch(es) returned by an in-flight child poll after the + /// coordinator already moved past this side's sampling phase. Preserved in + /// exact order without growing `self.res`. + pub(super) unreserved: VecDeque, + pub(super) counter: RecordBatchMemoryCounter, + pub(super) res: MemoryReservation, + pub(super) eof: bool, + pub(super) err: Option, +} + +impl SideBuf { + pub(super) fn new(res: MemoryReservation) -> Self { + Self { + batches: VecDeque::new(), + unreserved: VecDeque::new(), + counter: RecordBatchMemoryCounter::new(), + res, + eof: false, + err: None, + } + } + + /// Counts incremental memory for `batch`, grows the reservation, and buffers + /// the batch. Returns the incremental byte count on success. + pub(super) fn push_batch(&mut self, batch: RecordBatch) -> Result { + let bytes = self.counter.count_batch(&batch); + self.res.try_grow(bytes)?; + self.batches.push_back(batch); + Ok(bytes) + } + + /// Preserves `batch` for exact-order replay after `self.batches` without + /// counting it in `self.counter` or growing `self.res`. + pub(super) fn push_unreserved(&mut self, batch: RecordBatch) { + self.unreserved.push_back(batch); + } + + /// Returns whether any sampled or unreserved batches are buffered. + pub(super) fn has_buffered(&self) -> bool { + !self.batches.is_empty() || !self.unreserved.is_empty() + } + + /// Splits this buffer into a reserved [`BuildPrefix`] and a build stream + /// that replays any unreserved trailing batches ahead of `tail` so + /// `collect_left_input` counts and reserves them normally. + pub(super) fn into_prefix_and_tail( + self, + tail: SendableRecordBatchStream, + ) -> (BuildPrefix, SendableRecordBatchStream) { + let Self { + batches, + unreserved, + counter, + res, + .. + } = self; + let prefix = BuildPrefix { + batches: Vec::from(batches), + counter, + reservation: res, + }; + let tail = if unreserved.is_empty() { + tail + } else { + Box::pin(UnreservedPrefixStream { unreserved, tail }) + }; + (prefix, tail) + } +} + +/// Replays unreserved trailing batches ahead of `tail` before `collect_left_input` +/// reserves their memory into the build side. +struct UnreservedPrefixStream { + unreserved: VecDeque, + tail: SendableRecordBatchStream, +} + +impl RecordBatchStream for UnreservedPrefixStream { + fn schema(&self) -> SchemaRef { + self.tail.schema() + } +} + +impl Stream for UnreservedPrefixStream { + type Item = Result; + + fn poll_next( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> Poll> { + if let Some(batch) = self.unreserved.pop_front() { + return Poll::Ready(Some(Ok(batch))); + } + self.tail.poll_next_unpin(cx) + } +} + +/// Arguments needed to start `collect_left_input` once sampling decides. +pub(super) struct DeferredBuildArgs { + pub(super) config: Arc, + pub(super) array_map_created_count: Count, +} + +/// Stream-local state held while in `HashJoinStreamState::AdaptiveSample`. +pub(super) struct AdaptiveState { + pub(super) h: Ticket, + pub(super) rx: watch::Receiver, + pub(super) left: SendableRecordBatchStream, + pub(super) lb: SideBuf, + pub(super) rb: SideBuf, + pub(super) wait: Option<(Phase, BoxFuture<'static, ()>)>, + pub(super) on_left: Vec, + pub(super) build_args: DeferredBuildArgs, + pub(super) entered_sample_right: bool, + pub(super) metrics: AdaptiveMetrics, +} + +/// Replays a sampled [`SideBuf`] prefix (and optional stashed error) before +/// streaming the remaining tail. +/// +/// Holds the entire prefix [`MemoryReservation`] until the final prefix batch +/// is yielded (or the stream is dropped) so shared backing buffers across sliced +/// batches are never undercharged mid-drain. +pub(super) struct ReplayStream { + prefix: SideBuf, + tail: SendableRecordBatchStream, +} + +impl ReplayStream { + pub(super) fn new(prefix: SideBuf, tail: SendableRecordBatchStream) -> Self { + Self { prefix, tail } + } +} + +impl RecordBatchStream for ReplayStream { + fn schema(&self) -> SchemaRef { + self.tail.schema() + } +} + +impl Stream for ReplayStream { + type Item = Result; + + fn poll_next( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> Poll> { + if let Some(batch) = self.prefix.batches.pop_front() { + if self.prefix.batches.is_empty() && self.prefix.unreserved.is_empty() { + self.prefix.res.free(); + } + return Poll::Ready(Some(Ok(batch))); + } + + if let Some(batch) = self.prefix.unreserved.pop_front() { + if self.prefix.unreserved.is_empty() { + self.prefix.res.free(); + } + return Poll::Ready(Some(Ok(batch))); + } + + if let Some(err) = self.prefix.err.take() { + self.prefix.res.free(); + let schema = self.tail.schema(); + self.tail = Box::pin(EmptyRecordBatchStream::new(schema)); + return Poll::Ready(Some(Err(err))); + } + + self.tail.poll_next_unpin(cx) + } +} + +/// Bounded synchronization gate for concurrency tests. +#[cfg(test)] +pub(super) struct TestGate { + open: Mutex, + cvar: parking_lot::Condvar, +} + +#[cfg(test)] +impl TestGate { + pub(super) fn new() -> Arc { + Arc::new(Self { + open: Mutex::new(false), + cvar: parking_lot::Condvar::new(), + }) + } + + pub(super) fn open(&self) { + let mut open = self.open.lock(); + *open = true; + self.cvar.notify_all(); + } + + pub(super) fn wait_timeout(&self, timeout: Duration) -> bool { + let deadline = Instant::now() + timeout; + let mut open = self.open.lock(); + while !*open { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() || self.cvar.wait_for(&mut open, remaining).timed_out() + { + return *open; + } + } + true + } +} + +/// Unconditionally opens a [`TestGate`] on drop so assertion panics never leave +/// worker threads wedged. +#[cfg(test)] +pub(super) struct GateReleaseGuard(pub(super) Arc); + +#[cfg(test)] +impl Drop for GateReleaseGuard { + fn drop(&mut self) { + self.0.open(); + } +} + +/// Installs a pre-release pause hook on `coord` that opens the returned +/// `entered` gate on entry and blocks until the returned [`GateReleaseGuard`] +/// is dropped (bounded by `timeout`). +#[cfg(test)] +pub(super) fn install_filter_release_pause( + coord: &AdaptiveBuildCoordinator, + timeout: Duration, +) -> (Arc, GateReleaseGuard) { + let entered = TestGate::new(); + let release = TestGate::new(); + let entered_hook = Arc::clone(&entered); + let release_hook = Arc::clone(&release); + coord.set_before_filter_release_hook(Some(Arc::new(move || { + entered_hook.open(); + assert!( + release_hook.wait_timeout(timeout), + "filter release hook timed out waiting to be released" + ); + }))); + (entered, GateReleaseGuard(release)) +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::joins::hash_join::shared_bounds::{ + completed_partitions_for_test, make_partitioned_accumulator_for_test, + }; + + const GATE_TIMEOUT: Duration = Duration::from_secs(5); + + fn make_coordinator( + p: usize, + cap: usize, + batch_size: usize, + ) -> ( + Arc, + Arc, + ExecutionPlanMetricsSet, + ) { + let acc = Arc::new(make_partitioned_accumulator_for_test(p)); + let metrics = ExecutionPlanMetricsSet::new(); + let coord = AdaptiveBuildCoordinator::new(p, cap, batch_size, &acc, &metrics); + (acc, coord, metrics) + } + + fn ticket(coord: &Arc, partition: usize) -> Ticket { + let Claim::Adaptive(t) = coord.claim(partition) else { + panic!("expected adaptive ticket for partition {partition}"); + }; + t + } + + fn metric_sum(metrics: &ExecutionPlanMetricsSet, name: &str) -> usize { + metrics + .clone_inner() + .sum_by_name(name) + .map(|v| v.as_usize()) + .unwrap_or(0) + } + + #[test] + fn coordinator_eof_then_cross_and_cross_then_eof() { + let (acc, coord, metrics) = make_coordinator(2, 100, 10); + let t0 = ticket(&coord, 0); + let t1 = ticket(&coord, 1); + t0.on_batch(JoinSide::Left, 40, 2); + t0.on_eof(JoinSide::Left); + assert_eq!(coord.phase(), Phase::SampleLeft); + assert!(!coord.is_filter_released()); + assert!(!acc.is_filter_complete_for_test()); + + t1.on_batch(JoinSide::Left, 70, 2); + assert_eq!(coord.phase(), Phase::SampleRight); + assert!(coord.is_filter_released()); + assert!(acc.is_filter_complete_for_test()); + assert_eq!(completed_partitions_for_test(&acc), 2); + + t0.on_batch(JoinSide::Right, 60, 2); + assert_eq!(coord.phase(), Phase::SampleRight); + t1.on_batch(JoinSide::Right, 50, 2); + assert_eq!( + coord.phase(), + Phase::Decided(Decision::KeepLeft(Reason::RightCrossed)) + ); + assert_eq!( + metric_sum(&metrics, "adaptive_decision_reason_right_crossed"), + 1 + ); + assert!(metric_sum(&metrics, "adaptive_decision_wall_time") > 0); + + // Left EOFs after entering SampleRight do not alter the sampling phase. + let (acc2, coord2, metrics2) = make_coordinator(2, 100, 10); + let a0 = ticket(&coord2, 0); + let a1 = ticket(&coord2, 1); + a0.on_batch(JoinSide::Left, 150, 3); + assert_eq!(coord2.phase(), Phase::SampleRight); + assert!(acc2.is_filter_complete_for_test()); + a0.on_eof(JoinSide::Left); + a1.on_eof(JoinSide::Left); + assert_eq!(coord2.phase(), Phase::SampleRight); + + // SwapRight requires EOF from every partition before any right-side sampling limit is crossed. + a0.on_batch(JoinSide::Right, 20, 1); + a0.on_eof(JoinSide::Right); + assert_eq!(coord2.phase(), Phase::SampleRight); + a1.on_batch(JoinSide::Right, 80, 1); + a1.on_eof(JoinSide::Right); + assert_eq!(coord2.phase(), Phase::Decided(Decision::SwapRight)); + assert_eq!( + metric_sum(&metrics2, "adaptive_decision_reason_swap_right"), + 1 + ); + assert!(metric_sum(&metrics2, "adaptive_decision_wall_time") > 0); + } + + #[test] + fn coordinator_last_eof_within_cap_keeps_left() { + let (acc, coord, metrics) = make_coordinator(2, 100, 10); + let t0 = ticket(&coord, 0); + let t1 = ticket(&coord, 1); + t0.on_batch(JoinSide::Left, 50, 2); + t0.on_eof(JoinSide::Left); + assert_eq!(coord.phase(), Phase::SampleLeft); + t1.on_batch(JoinSide::Left, 50, 2); + t1.on_eof(JoinSide::Left); + assert_eq!( + coord.phase(), + Phase::Decided(Decision::KeepLeft(Reason::LeftSmall)) + ); + assert!(!coord.is_filter_released()); + assert!(!acc.is_filter_complete_for_test()); + assert_eq!( + metric_sum(&metrics, "adaptive_decision_reason_left_small"), + 1 + ); + assert!(metric_sum(&metrics, "adaptive_decision_wall_time") > 0); + } + + #[test] + fn coordinator_batch_and_row_count_caps_trip_on_zero_byte_batches() { + // Batch count cap: 64 * P = 64 for P = 1 + let (_acc, coord, _metrics) = make_coordinator(1, 10_000, 100); + let t0 = ticket(&coord, 0); + for _ in 0..64 { + t0.on_batch(JoinSide::Left, 0, 0); + assert_eq!(coord.phase(), Phase::SampleLeft); + } + t0.on_batch(JoinSide::Left, 0, 0); + assert_eq!(coord.phase(), Phase::SampleRight); + + // Exceeding the right-side batch cap prevents SwapRight. + for _ in 0..64 { + t0.on_batch(JoinSide::Right, 0, 0); + assert_eq!(coord.phase(), Phase::SampleRight); + } + t0.on_batch(JoinSide::Right, 0, 0); + assert_eq!( + coord.phase(), + Phase::Decided(Decision::KeepLeft(Reason::RightCrossed)) + ); + + // Row count cap: 64 * P * batch_size = 64 * 1 * 2 = 128 + let (_acc2, coord2, _metrics2) = make_coordinator(1, 10_000, 2); + let r0 = ticket(&coord2, 0); + r0.on_batch(JoinSide::Left, 0, 128); + assert_eq!(coord2.phase(), Phase::SampleLeft); + r0.on_batch(JoinSide::Left, 0, 1); + assert_eq!(coord2.phase(), Phase::SampleRight); + } + + #[test] + fn coordinator_abandon_in_every_phase_and_reason_recorded_once() { + let (_acc, coord, metrics) = make_coordinator(2, 100, 10); + let t0 = ticket(&coord, 0); + t0.abandon(Reason::Abandoned); + t0.abandon(Reason::RightError); + assert_eq!( + coord.phase(), + Phase::Decided(Decision::KeepLeft(Reason::Abandoned)) + ); + assert!(!coord.is_filter_released()); + assert_eq!( + metric_sum(&metrics, "adaptive_decision_reason_abandoned"), + 1 + ); + assert_eq!( + metric_sum(&metrics, "adaptive_decision_reason_right_error"), + 0 + ); + + let (_acc2, coord2, metrics2) = make_coordinator(2, 100, 10); + let a0 = ticket(&coord2, 0); + a0.on_batch(JoinSide::Left, 200, 1); + assert_eq!(coord2.phase(), Phase::SampleRight); + assert!(coord2.is_filter_released()); + a0.abandon(Reason::RightError); + a0.abandon(Reason::Abandoned); + assert_eq!( + coord2.phase(), + Phase::Decided(Decision::KeepLeft(Reason::RightError)) + ); + assert_eq!( + metric_sum(&metrics2, "adaptive_decision_reason_right_error"), + 1 + ); + assert_eq!( + metric_sum(&metrics2, "adaptive_decision_reason_abandoned"), + 0 + ); + } + + #[test] + fn coordinator_claims_duplicate_oob_drop_and_post_release() { + let (_acc, coord, metrics) = make_coordinator(2, 100, 10); + let _t0 = ticket(&coord, 0); + assert!(matches!(coord.claim(0), Claim::Stock)); + assert_eq!( + coord.phase(), + Phase::Decided(Decision::KeepLeft(Reason::Duplicate)) + ); + assert_eq!( + metric_sum(&metrics, "adaptive_decision_reason_duplicate"), + 1 + ); + + let (_acc_oob, coord_oob, _) = make_coordinator(2, 100, 10); + assert!(matches!(coord_oob.claim(2), Claim::Stock)); + assert_eq!( + coord_oob.phase(), + Phase::Decided(Decision::KeepLeft(Reason::Duplicate)) + ); + + let (_acc_drop, coord_drop, metrics_drop) = make_coordinator(2, 100, 10); + { + let _t0 = ticket(&coord_drop, 0); + } + assert_eq!( + coord_drop.phase(), + Phase::Decided(Decision::KeepLeft(Reason::Abandoned)) + ); + assert_eq!( + metric_sum(&metrics_drop, "adaptive_decision_reason_abandoned"), + 1 + ); + // Late claim after pre-release abandon still attaches to the accumulator. + assert!(matches!(coord_drop.claim(1), Claim::Stock)); + + // Late claim after SwapRight receives StockDetached. + let (_acc_swap, coord_swap, _) = make_coordinator(1, 100, 10); + let t0 = ticket(&coord_swap, 0); + t0.on_batch(JoinSide::Left, 200, 1); + t0.on_eof(JoinSide::Right); + assert_eq!(coord_swap.phase(), Phase::Decided(Decision::SwapRight)); + assert!(matches!(coord_swap.claim(0), Claim::StockDetached)); + + // Late claim after RightCrossed (KeepLeft post-filter-release) receives StockDetached. + let (_acc_rc, coord_rc, _) = make_coordinator(2, 100, 10); + let r0 = ticket(&coord_rc, 0); + let _r1 = ticket(&coord_rc, 1); + r0.on_batch(JoinSide::Left, 200, 1); + assert_eq!(coord_rc.phase(), Phase::SampleRight); + r0.on_batch(JoinSide::Right, 200, 1); + assert_eq!( + coord_rc.phase(), + Phase::Decided(Decision::KeepLeft(Reason::RightCrossed)) + ); + assert!(matches!(coord_rc.claim(0), Claim::StockDetached)); + assert!(matches!(coord_rc.claim(1), Claim::StockDetached)); + + // Duplicate claim during SampleRight (after filter release) receives StockDetached. + let (_acc_dup_rel, coord_dup_rel, _) = make_coordinator(2, 100, 10); + let d0 = ticket(&coord_dup_rel, 0); + d0.on_batch(JoinSide::Left, 200, 1); + assert_eq!(coord_dup_rel.phase(), Phase::SampleRight); + assert!(matches!(coord_dup_rel.claim(0), Claim::StockDetached)); + assert_eq!( + coord_dup_rel.phase(), + Phase::Decided(Decision::KeepLeft(Reason::Duplicate)) + ); + assert!(matches!(coord_dup_rel.claim(1), Claim::StockDetached)); + + // Late claim after post-release abandon receives StockDetached. + let (_acc_ab_rel, coord_ab_rel, _) = make_coordinator(2, 100, 10); + let a0 = ticket(&coord_ab_rel, 0); + a0.on_batch(JoinSide::Left, 200, 1); + drop(a0); + assert_eq!( + coord_ab_rel.phase(), + Phase::Decided(Decision::KeepLeft(Reason::Abandoned)) + ); + assert!(matches!(coord_ab_rel.claim(1), Claim::StockDetached)); + } + + fn spawn_bounded( + f: F, + ) -> (std::thread::JoinHandle<()>, std::sync::mpsc::Receiver<()>) + where + F: FnOnce() + Send + 'static, + { + let (done_tx, done_rx) = std::sync::mpsc::channel(); + let handle = std::thread::spawn(move || { + f(); + let _ = done_tx.send(()); + }); + (handle, done_rx) + } + + fn join_bounded( + handle: std::thread::JoinHandle<()>, + done_rx: &std::sync::mpsc::Receiver<()>, + label: &str, + ) { + match done_rx.recv_timeout(GATE_TIMEOUT) { + Ok(()) => handle.join().unwrap(), + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => { + // Worker exited without sending (e.g. panicked); join to surface the panic. + handle.join().unwrap(); + panic!("{label} exited without sending completion acknowledgement"); + } + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { + panic!("{label} did not complete within {GATE_TIMEOUT:?}"); + } + } + } + + #[test] + fn coordinator_sample_right_releaser_discharges_all_slots_before_publish() { + let (acc, coord, _) = make_coordinator(3, 100, 10); + let t0 = ticket(&coord, 0); + let t1 = ticket(&coord, 1); + + let (entered, release_guard) = install_filter_release_pause(&coord, GATE_TIMEOUT); + + let (t0_tx, t0_rx) = std::sync::mpsc::channel(); + let (releaser, releaser_done) = spawn_bounded(move || { + t0.on_batch(JoinSide::Left, 200, 1); + t0_tx.send(t0).unwrap(); + }); + + // Releaser has entered ReleasingFilter under lock, paused before discharge. + assert!( + entered.wait_timeout(GATE_TIMEOUT), + "releaser did not reach pre-release hook within timeout" + ); + // Peers observe ReleasingFilter (not SampleRight) until all slots are discharged. + assert_eq!(t1.phase(), Phase::ReleasingFilter); + assert!(t1.is_filter_released()); + assert_eq!(completed_partitions_for_test(&acc), 0); + assert!(!acc.is_filter_complete_for_test()); + + // An unclaimed valid partition arriving during ReleasingFilter receives an + // Adaptive ticket (which starts detached in exec.rs because filter_released is true). + let t2 = ticket(&coord, 2); + assert!(t2.is_filter_released()); + assert_eq!(t2.phase(), Phase::ReleasingFilter); + + // Concurrent peer batches and Left EOFs during release must neither + // trigger a second discharge nor decide LeftSmall. + t1.on_batch(JoinSide::Left, 200, 1); + t1.on_eof(JoinSide::Left); + t2.on_eof(JoinSide::Left); + assert_eq!(t1.phase(), Phase::ReleasingFilter); + assert_eq!(completed_partitions_for_test(&acc), 0); + + drop(release_guard); + join_bounded(releaser, &releaser_done, "filter releaser"); + let t0 = t0_rx.recv().unwrap(); + + assert_eq!(t1.phase(), Phase::SampleRight); + assert_eq!(completed_partitions_for_test(&acc), 3); + assert!(acc.is_filter_complete_for_test()); + + // SwapRight publishes directly without a second discharge. + t0.on_eof(JoinSide::Right); + t1.on_eof(JoinSide::Right); + t2.on_eof(JoinSide::Right); + assert_eq!(t1.phase(), Phase::Decided(Decision::SwapRight)); + } + + #[test] + fn coordinator_early_abandon_during_filter_release_not_overwritten_by_sample_right() { + let (acc, coord, metrics) = make_coordinator(2, 100, 10); + let t0 = ticket(&coord, 0); + let t1 = ticket(&coord, 1); + + let (entered, release_guard) = install_filter_release_pause(&coord, GATE_TIMEOUT); + + let (releaser, releaser_done) = spawn_bounded(move || { + t0.on_batch(JoinSide::Left, 200, 1); + }); + + assert!( + entered.wait_timeout(GATE_TIMEOUT), + "releaser did not reach pre-release hook within timeout" + ); + assert_eq!(t1.phase(), Phase::ReleasingFilter); + assert!(t1.is_filter_released()); + + // Peer abandons while releaser is paused before cancel_all_partitions_and_wait. + assert_eq!( + t1.abandon(Reason::Abandoned), + Decision::KeepLeft(Reason::Abandoned) + ); + assert_eq!( + coord.phase(), + Phase::Decided(Decision::KeepLeft(Reason::Abandoned)) + ); + assert!(matches!(coord.claim(0), Claim::StockDetached)); + + drop(release_guard); + join_bounded(releaser, &releaser_done, "filter releaser"); + + // Releaser must NOT overwrite Decided(KeepLeft(Abandoned)) with SampleRight. + assert_eq!( + coord.phase(), + Phase::Decided(Decision::KeepLeft(Reason::Abandoned)) + ); + assert!(acc.is_filter_complete_for_test()); + assert_eq!(completed_partitions_for_test(&acc), 2); + assert_eq!( + metric_sum(&metrics, "adaptive_decision_reason_abandoned"), + 1 + ); + + // Duplicate claim during ReleasingFilter transitions to Duplicate and returns StockDetached. + let (acc_dup, coord_dup, metrics_dup) = make_coordinator(2, 100, 10); + let d0 = ticket(&coord_dup, 0); + let (entered_dup, release_dup) = + install_filter_release_pause(&coord_dup, GATE_TIMEOUT); + let (releaser_dup, releaser_dup_done) = spawn_bounded(move || { + d0.on_batch(JoinSide::Left, 200, 1); + }); + assert!( + entered_dup.wait_timeout(GATE_TIMEOUT), + "releaser did not reach pre-release hook within timeout" + ); + assert_eq!(coord_dup.phase(), Phase::ReleasingFilter); + assert!(matches!(coord_dup.claim(0), Claim::StockDetached)); + assert_eq!( + coord_dup.phase(), + Phase::Decided(Decision::KeepLeft(Reason::Duplicate)) + ); + drop(release_dup); + join_bounded(releaser_dup, &releaser_dup_done, "filter releaser dup"); + assert_eq!( + coord_dup.phase(), + Phase::Decided(Decision::KeepLeft(Reason::Duplicate)) + ); + assert!(acc_dup.is_filter_complete_for_test()); + assert_eq!( + metric_sum(&metrics_dup, "adaptive_decision_reason_duplicate"), + 1 + ); + } + + #[test] + fn coordinator_filter_release_waits_for_competing_finalizer_before_publish() { + let (acc, coord, _) = make_coordinator(2, 100, 10); + let t0 = ticket(&coord, 0); + let _t1 = ticket(&coord, 1); + + let peer_in_finish = TestGate::new(); + let release_peer = TestGate::new(); + let peer_in_finish_hook = Arc::clone(&peer_in_finish); + let release_peer_hook = Arc::clone(&release_peer); + acc.set_before_finish_hook(Some(Arc::new(move || { + peer_in_finish_hook.open(); + assert!( + release_peer_hook.wait_timeout(GATE_TIMEOUT), + "competing finalizer hook timed out waiting to be released" + ); + }))); + + let releaser_waiting_on_finalizing = TestGate::new(); + let releaser_waiting_hook = Arc::clone(&releaser_waiting_on_finalizing); + acc.set_before_wait_finalizing_hook(Some(Arc::new(move || { + releaser_waiting_hook.open(); + }))); + + // Cancel slot 0 first so the peer canceling slot 1 claims `Finalizing` + // and pauses before `mark_complete()`. + acc.report_canceled_partition(0); + + let acc_peer = Arc::clone(&acc); + let (peer, peer_done) = spawn_bounded(move || { + acc_peer.report_canceled_partition(1); + }); + + let release_guard = GateReleaseGuard(Arc::clone(&release_peer)); + assert!( + peer_in_finish.wait_timeout(GATE_TIMEOUT), + "competing finalizer did not reach before_finish_hook within timeout" + ); + assert!(!acc.is_filter_complete_for_test()); + + let (t0_tx, t0_rx) = std::sync::mpsc::channel(); + let (releaser, releaser_done) = spawn_bounded(move || { + t0.on_batch(JoinSide::Left, 200, 1); + t0_tx.send(t0).unwrap(); + }); + + assert!( + releaser_waiting_on_finalizing.wait_timeout(GATE_TIMEOUT), + "filter releaser did not encounter Finalizing inside cancel_all_partitions_and_wait within timeout" + ); + assert_eq!(coord.phase(), Phase::ReleasingFilter); + assert!(!acc.is_filter_complete_for_test()); + assert!(matches!( + releaser_done.try_recv(), + Err(std::sync::mpsc::TryRecvError::Empty) + )); + + drop(release_guard); + join_bounded(peer, &peer_done, "competing finalizer"); + join_bounded(releaser, &releaser_done, "filter releaser"); + let _t0 = t0_rx.recv().unwrap(); + + assert!(acc.is_filter_complete_for_test()); + assert_eq!(coord.phase(), Phase::SampleRight); + } +} diff --git a/datafusion/physical-plan/src/joins/hash_join/adaptive_tests.rs b/datafusion/physical-plan/src/joins/hash_join/adaptive_tests.rs new file mode 100644 index 0000000000000..c5a95fd73683c --- /dev/null +++ b/datafusion/physical-plan/src/joins/hash_join/adaptive_tests.rs @@ -0,0 +1,4055 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +//! End-to-end and adversarial tests for native runtime adaptive build-side +//! selection inside [`HashJoinExec`]. + +use std::collections::{HashMap, VecDeque}; +use std::fmt; +use std::pin::Pin; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::task::{Context, Poll}; +use std::time::Duration; + +use arrow::array::{ArrayRef, Int32Array, StringArray}; +use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; +use arrow::record_batch::RecordBatch; +use datafusion_common::config::ConfigOptions; +use datafusion_common::test_util::batches_to_sort_string; +use datafusion_common::tree_node::TreeNodeRecursion; +use datafusion_common::{ + DataFusionError, JoinSide, JoinType, NullEquality, Result, ScalarValue, exec_err, +}; +use datafusion_common_runtime::SpawnedTask; +use datafusion_execution::TaskContext; +use datafusion_execution::config::SessionConfig; +use datafusion_execution::disk_manager::{DiskManagerBuilder, DiskManagerMode}; +use datafusion_execution::memory_pool::{ + GreedyMemoryPool, MemoryConsumer, MemoryLimit, MemoryPool, MemoryReservation, +}; +use datafusion_execution::runtime_env::RuntimeEnvBuilder; +use datafusion_expr::Operator; +use datafusion_physical_expr::expressions::{ + BinaryExpr, Column, DynamicFilterPhysicalExpr, Literal, +}; +use datafusion_physical_expr::{ + EquivalenceProperties, LexOrdering, PhysicalExpr, PhysicalExprRef, PhysicalSortExpr, +}; +use futures::future::join_all; +use futures::task::{ArcWake, waker_ref}; +use futures::{FutureExt, Stream, StreamExt}; +use parking_lot::Mutex; +use tokio::sync::{Notify, Semaphore}; + +use crate::execution_plan::{Boundedness, EmissionType}; +use crate::filter::FilterExecBuilder; +use crate::hash_utils::create_hashes; +use crate::joins::hash_join::adaptive::{ + Decision, GateReleaseGuard, Phase, Reason, ReplayStream, SideBuf, TestGate, + install_filter_release_pause, +}; +use crate::joins::hash_join::exec::HashJoinExec; +use crate::joins::utils::{ColumnIndex, JoinFilter}; +use crate::joins::{JoinOn, PartitionMode}; +use crate::metrics::MetricsSet; +use crate::repartition::{REPARTITION_RANDOM_STATE, RepartitionExec}; +use crate::{ + ChildrenPropertiesMode, DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning, + PlanProperties, RecordBatchStream, ReplaceChildrenOptions, SendableRecordBatchStream, + common, +}; + +const TEST_TIMEOUT: Duration = Duration::from_secs(15); +const GATE_TIMEOUT: Duration = Duration::from_secs(5); + +/// Wraps a [`GreedyMemoryPool`] while recording peak reserved bytes. +#[derive(Debug)] +struct PeakTrackingMemoryPool { + inner: GreedyMemoryPool, + peak: AtomicUsize, +} + +impl PeakTrackingMemoryPool { + fn new(limit: usize) -> Self { + Self { + inner: GreedyMemoryPool::new(limit), + peak: AtomicUsize::new(0), + } + } + + fn peak_reserved(&self) -> usize { + self.peak.load(Ordering::SeqCst) + } + + fn update_peak(&self) { + let cur = self.inner.reserved(); + self.peak.fetch_max(cur, Ordering::SeqCst); + } +} + +impl fmt::Display for PeakTrackingMemoryPool { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "PeakTrackingMemoryPool({})", self.inner) + } +} + +impl MemoryPool for PeakTrackingMemoryPool { + fn name(&self) -> &str { + "PeakTrackingMemoryPool" + } + + fn grow(&self, reservation: &MemoryReservation, additional: usize) { + self.inner.grow(reservation, additional); + self.update_peak(); + } + + fn shrink(&self, reservation: &MemoryReservation, shrink: usize) { + self.inner.shrink(reservation, shrink); + } + + fn try_grow(&self, reservation: &MemoryReservation, additional: usize) -> Result<()> { + self.inner.try_grow(reservation, additional)?; + self.update_peak(); + Ok(()) + } + + fn reserved(&self) -> usize { + self.inner.reserved() + } + + fn memory_limit(&self) -> MemoryLimit { + self.inner.memory_limit() + } +} + +fn is_filter_complete(filter: &DynamicFilterPhysicalExpr) -> bool { + filter.wait_complete().now_or_never().is_some() +} + +fn is_literal_true(expr: &Arc) -> bool { + expr.downcast_ref::() + .is_some_and(|lit| lit.value() == &ScalarValue::Boolean(Some(true))) +} + +/// Finds a deterministic `i32` key `>= start` that hashes to `target_part` under +/// `REPARTITION_RANDOM_STATE` with `num_partitions` partitions. +fn key_for_partition_from(target_part: usize, num_partitions: usize, start: i32) -> i32 { + let mut hash_buf = [0u64; 1]; + for candidate in start..start.saturating_add(100_000) { + let arr: ArrayRef = Arc::new(Int32Array::from(vec![candidate])); + hash_buf[0] = 0; + create_hashes( + &[arr], + REPARTITION_RANDOM_STATE.random_state(), + &mut hash_buf, + ) + .unwrap(); + if (hash_buf[0] % (num_partitions as u64)) as usize == target_part { + return candidate; + } + } + panic!("failed to find key for partition {target_part}/{num_partitions}"); +} + +fn key_for_partition(target_part: usize, num_partitions: usize) -> i32 { + key_for_partition_from(target_part, num_partitions, 1) +} + +/// Waits briefly for background `RepartitionExec` tasks to drop after plan +/// teardown and asserts that all pool reservations return to zero. +async fn assert_pool_returns_to_zero(pool: &PeakTrackingMemoryPool) { + for _ in 0..50 { + if pool.reserved() == 0 { + return; + } + tokio::task::yield_now().await; + } + assert_eq!(pool.reserved(), 0); +} + +fn metric_sum(metrics: &MetricsSet, name: &str) -> usize { + metrics.sum_by_name(name).map(|v| v.as_usize()).unwrap_or(0) +} + +fn assert_no_adaptive_metrics(metrics: &MetricsSet) { + for name in [ + "adaptive_build_swapped", + "adaptive_right_sampled", + "adaptive_sampled_left_bytes", + "adaptive_sampled_right_bytes", + "adaptive_sample_poll_time", + "adaptive_decision_wall_time", + "adaptive_decision_reason_swap_right", + "adaptive_decision_reason_left_small", + "adaptive_decision_reason_right_crossed", + "adaptive_decision_reason_right_error", + "adaptive_decision_reason_abandoned", + "adaptive_decision_reason_duplicate", + ] { + assert!( + metrics.sum_by_name(name).is_none(), + "expected no adaptive metric `{name}` on stock path, found {:?}", + metrics.sum_by_name(name) + ); + } +} + +fn make_ctx_with( + cap: usize, + batch_size: usize, + pool: Option>, + disable_disk: bool, + tweak: impl FnOnce(&mut ConfigOptions), +) -> Arc { + let mut cfg = SessionConfig::default().with_batch_size(batch_size); + let opts = cfg.options_mut(); + opts.execution.hash_join_adaptive_build_side_threshold_bytes = cap; + opts.execution.hash_join_buffering_capacity = 0; + tweak(opts); + + let mut rt_builder = RuntimeEnvBuilder::new(); + if let Some(pool) = pool { + rt_builder = rt_builder.with_memory_pool(pool); + } + if disable_disk { + rt_builder = rt_builder.with_disk_manager_builder( + DiskManagerBuilder::default().with_mode(DiskManagerMode::Disabled), + ); + } + let rt = rt_builder.build_arc().unwrap(); + Arc::new( + TaskContext::default() + .with_session_config(cfg) + .with_runtime(rt), + ) +} + +fn make_ctx( + cap: usize, + batch_size: usize, + pool: Option>, + disable_disk: bool, +) -> Arc { + make_ctx_with(cap, batch_size, pool, disable_disk, |_| {}) +} + +fn schema_with_meta(side: &str, val: &str, pad: &str) -> SchemaRef { + let mut k_meta = HashMap::new(); + k_meta.insert("origin".to_string(), format!("{side}_key")); + let mut v_meta = HashMap::new(); + v_meta.insert("origin".to_string(), format!("{side}_val")); + let mut s_meta = HashMap::new(); + s_meta.insert("origin".to_string(), format!("{side}_pad")); + + Arc::new(Schema::new(vec![ + Field::new("k", DataType::Int32, true).with_metadata(k_meta), + Field::new(val, DataType::Int32, true).with_metadata(v_meta), + Field::new(pad, DataType::Utf8, false).with_metadata(s_meta), + ])) +} + +fn left_schema_with_meta() -> SchemaRef { + schema_with_meta("left", "lv", "lpad") +} + +fn right_schema_with_meta() -> SchemaRef { + schema_with_meta("right", "rv", "rpad") +} + +fn schemas_and_on() -> Result<(SchemaRef, SchemaRef, JoinOn)> { + let l_schema = left_schema_with_meta(); + let r_schema = right_schema_with_meta(); + let on: JoinOn = vec![( + Arc::new(Column::new_with_schema("k", &l_schema)?), + Arc::new(Column::new_with_schema("k", &r_schema)?), + )]; + Ok((l_schema, r_schema, on)) +} + +fn make_batch( + schema: &SchemaRef, + keys: &[Option], + vals: &[Option], + pad_len: usize, +) -> RecordBatch { + let pad_str = "x".repeat(pad_len); + let pads: Vec<&str> = vec![pad_str.as_str(); keys.len()]; + RecordBatch::try_new( + Arc::clone(schema), + vec![ + Arc::new(Int32Array::from(keys.to_vec())), + Arc::new(Int32Array::from(vals.to_vec())), + Arc::new(StringArray::from(pads)), + ], + ) + .unwrap() +} + +/// Custom test `ExecutionPlan` producing per-partition streams from a factory closure. +struct CustomPlan { + props: Arc, + factory: Arc< + dyn Fn(usize, Arc) -> Result + + Send + + Sync, + >, +} + +impl fmt::Debug for CustomPlan { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "CustomPlan") + } +} + +impl CustomPlan { + fn new( + schema: SchemaRef, + partitioning: Partitioning, + factory: impl Fn(usize, Arc) -> Result + + Send + + Sync + + 'static, + ) -> Self { + Self::with_props( + PlanProperties::new( + EquivalenceProperties::new(schema), + partitioning, + EmissionType::Incremental, + Boundedness::Bounded, + ), + factory, + ) + } + + fn with_props( + props: PlanProperties, + factory: impl Fn(usize, Arc) -> Result + + Send + + Sync + + 'static, + ) -> Self { + Self { + props: Arc::new(props), + factory: Arc::new(factory), + } + } +} + +impl DisplayAs for CustomPlan { + fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "CustomPlan") + } +} + +impl ExecutionPlan for CustomPlan { + fn name(&self) -> &'static str { + "CustomPlan" + } + + fn properties(&self) -> &Arc { + &self.props + } + + fn children(&self) -> Vec<&Arc> { + vec![] + } + + fn apply_expressions( + &self, + _f: &mut dyn FnMut(&Arc) -> Result, + ) -> Result { + Ok(TreeNodeRecursion::Continue) + } + + fn replace_children( + self: Arc, + _children: Vec>, + _options: ReplaceChildrenOptions, + ) -> Result> { + Ok(self) + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> Result> { + self.replace_children( + children, + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + ) + } + + fn execute( + &self, + partition: usize, + context: Arc, + ) -> Result { + (self.factory)(partition, context) + } +} + +/// Simple replayable in-memory stream of `Result`. +struct VecStream { + schema: SchemaRef, + items: VecDeque>, + drop_flag: Option>, + poll_counter: Option>, + on_first_poll: Option>, + polled_once: bool, +} + +impl VecStream { + fn new(schema: SchemaRef, items: Vec>) -> Self { + Self { + schema, + items: items.into(), + drop_flag: None, + poll_counter: None, + on_first_poll: None, + polled_once: false, + } + } + + fn with_drop_flag(mut self, flag: Arc) -> Self { + self.drop_flag = Some(flag); + self + } + + fn with_poll_counter(mut self, counter: Arc) -> Self { + self.poll_counter = Some(counter); + self + } + + fn with_on_first_poll(mut self, cb: Arc) -> Self { + self.on_first_poll = Some(cb); + self + } +} + +impl Drop for VecStream { + fn drop(&mut self) { + if let Some(flag) = &self.drop_flag { + flag.store(true, Ordering::SeqCst); + } + } +} + +impl RecordBatchStream for VecStream { + fn schema(&self) -> SchemaRef { + Arc::clone(&self.schema) + } +} + +impl Stream for VecStream { + type Item = Result; + + fn poll_next( + mut self: Pin<&mut Self>, + _cx: &mut Context<'_>, + ) -> Poll> { + if let Some(counter) = &self.poll_counter { + counter.fetch_add(1, Ordering::SeqCst); + } + if !self.polled_once { + self.polled_once = true; + if let Some(cb) = &self.on_first_poll { + cb(); + } + } + Poll::Ready(self.items.pop_front()) + } +} + +/// Stream that yields items with optional async gates (`Notify`) before specified items. +enum Step { + Batch(RecordBatch), + Wait(Arc), + Sleep(Duration), + WaitFilterComplete(Arc), + NotifyThenWait { + signal: Arc, + gate: Arc, + }, +} + +struct ScriptedStream { + schema: SchemaRef, + steps: VecDeque, + active_fut: Option + Send>>>, +} + +impl ScriptedStream { + fn new(schema: SchemaRef, steps: Vec) -> Self { + Self { + schema, + steps: steps.into(), + active_fut: None, + } + } +} + +impl RecordBatchStream for ScriptedStream { + fn schema(&self) -> SchemaRef { + Arc::clone(&self.schema) + } +} + +impl Stream for ScriptedStream { + type Item = Result; + + fn poll_next( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> Poll> { + loop { + if let Some(fut) = self.active_fut.as_mut() { + match fut.as_mut().poll(cx) { + Poll::Pending => return Poll::Pending, + Poll::Ready(()) => self.active_fut = None, + } + } + match self.steps.pop_front() { + None => return Poll::Ready(None), + Some(Step::Batch(b)) => return Poll::Ready(Some(Ok(b))), + Some(Step::Wait(notify)) => { + self.active_fut = Some(Box::pin(async move { + notify.notified().await; + })); + } + Some(Step::Sleep(dur)) => { + self.active_fut = Some(Box::pin(async move { + tokio::time::sleep(dur).await; + })); + } + Some(Step::WaitFilterComplete(df)) => { + self.active_fut = Some(Box::pin(async move { + df.wait_complete().await; + })); + } + Some(Step::NotifyThenWait { signal, gate }) => { + signal.notify_one(); + self.active_fut = Some(Box::pin(async move { + gate.notified().await; + })); + } + } + } + } +} + +fn vec_plan( + schema: SchemaRef, + key: &PhysicalExprRef, + partitions: usize, + items: impl Fn(usize, &SchemaRef) -> Vec> + Send + Sync + 'static, +) -> Arc { + let s = Arc::clone(&schema); + Arc::new(CustomPlan::new( + schema, + Partitioning::Hash(vec![Arc::clone(key)], partitions), + move |part, _| Ok(Box::pin(VecStream::new(Arc::clone(&s), items(part, &s)))), + )) +} + +fn new_dyn_filter(on: &JoinOn) -> Arc { + let right_keys: Vec<_> = on.iter().map(|(_, r)| Arc::clone(r)).collect(); + Arc::new(DynamicFilterPhysicalExpr::new( + right_keys, + datafusion_physical_expr::expressions::lit(true), + )) +} + +#[expect(clippy::too_many_arguments)] +fn wire_join( + left: Arc, + right: Arc, + dyn_filter: &Arc, + on: JoinOn, + filter: Option, + join_type: JoinType, + projection: Option>, + null_equality: NullEquality, + mode: PartitionMode, + null_aware: bool, +) -> Result { + let right_filtered: Arc = Arc::new( + FilterExecBuilder::new(Arc::clone(dyn_filter) as Arc, right) + .build()?, + ); + let mut join = HashJoinExec::try_new( + left, + right_filtered, + on, + filter, + &join_type, + projection, + mode, + null_equality, + null_aware, + )?; + join.set_dynamic_filter_for_test(Arc::clone(dyn_filter)); + Ok(join) +} + +/// Builds a partitioned `HashJoinExec` wired with `RepartitionExec(Hash, p)` on both +/// sides and `FilterExec(dyn_filter)` above the right repartition. +#[expect(clippy::too_many_arguments)] +fn build_partitioned_join( + left_src: Arc, + right_src: Arc, + on: JoinOn, + filter: Option, + join_type: JoinType, + projection: Option>, + null_equality: NullEquality, + partitions: usize, +) -> Result<(HashJoinExec, Arc)> { + let (left_expr, right_expr): (Vec<_>, Vec<_>) = on + .iter() + .map(|(l, r)| (Arc::clone(l), Arc::clone(r))) + .unzip(); + + let left_repart: Arc = Arc::new(RepartitionExec::try_new( + left_src, + Partitioning::Hash(left_expr, partitions), + )?); + let right_repart: Arc = Arc::new(RepartitionExec::try_new( + right_src, + Partitioning::Hash(right_expr, partitions), + )?); + + build_direct_partitioned_join( + left_repart, + right_repart, + on, + filter, + join_type, + projection, + null_equality, + ) +} + +/// Builds a partitioned `HashJoinExec` directly on already-co-partitioned `CustomPlan`s +/// with `FilterExec(dyn_filter)` above `right`. +fn build_direct_partitioned_join( + left: Arc, + right: Arc, + on: JoinOn, + filter: Option, + join_type: JoinType, + projection: Option>, + null_equality: NullEquality, +) -> Result<(HashJoinExec, Arc)> { + let dyn_filter = new_dyn_filter(&on); + let join = wire_join( + left, + right, + &dyn_filter, + on, + filter, + join_type, + projection, + null_equality, + PartitionMode::Partitioned, + false, + )?; + Ok((join, dyn_filter)) +} + +async fn execute_all_partitions( + plan: &HashJoinExec, + partitions: usize, + ctx: Arc, +) -> Result> { + let streams: Vec<_> = (0..partitions) + .map(|p| plan.execute(p, Arc::clone(&ctx))) + .collect::>()?; + let results = tokio::time::timeout( + TEST_TIMEOUT, + join_all(streams.into_iter().map(common::collect)), + ) + .await + .expect("join execution timed out") + .into_iter() + .collect::>>()?; + Ok(results + .into_iter() + .flatten() + .filter(|b| b.num_rows() > 0) + .collect()) +} + +async fn run_stock_vs_adaptive( + build: impl Fn() -> Result<(HashJoinExec, Arc)>, + partitions: usize, + batch_size: usize, + adapt_ctx: Arc, +) -> Result<( + Vec, + Vec, + HashJoinExec, + Arc, +)> { + let (stock_join, _) = build()?; + let stock_out = execute_all_partitions( + &stock_join, + partitions, + make_ctx(0, batch_size, None, false), + ) + .await?; + + let (adapt_join, adapt_df) = build()?; + let adapt_out = execute_all_partitions(&adapt_join, partitions, adapt_ctx).await?; + + assert_eq!(stock_join.schema(), adapt_join.schema()); + for batch in &stock_out { + assert_eq!(batch.schema(), stock_join.schema()); + } + for batch in &adapt_out { + assert_eq!(batch.schema(), adapt_join.schema()); + } + Ok((stock_out, adapt_out, adapt_join, adapt_df)) +} + +fn non_output_residual_filter() -> JoinFilter { + let intermediate_schema = Arc::new(Schema::new(vec![ + Field::new("lv", DataType::Int32, true), + Field::new("rv", DataType::Int32, true), + ])); + let expr = Arc::new(BinaryExpr::new( + Arc::new(Column::new("lv", 0)), + Operator::Lt, + Arc::new(Column::new("rv", 1)), + )); + JoinFilter::new( + expr, + vec![ + ColumnIndex { + index: 1, + side: JoinSide::Left, + }, + ColumnIndex { + index: 1, + side: JoinSide::Right, + }, + ], + intermediate_schema, + ) +} + +fn make_single_partition_src( + schema: SchemaRef, + batches: Vec, +) -> Arc { + let batches = Arc::new(batches); + let schema_cl = Arc::clone(&schema); + Arc::new(CustomPlan::new( + schema, + Partitioning::UnknownPartitioning(1), + move |p, _| { + assert_eq!(p, 0); + Ok(Box::pin(VecStream::new( + Arc::clone(&schema_cl), + batches.iter().cloned().map(Ok).collect(), + ))) + }, + )) +} + +#[tokio::test] +async fn adaptive_differential_parity_all_v1_join_types_and_modes() -> Result<()> { + let (l_schema, r_schema, on) = schemas_and_on()?; + + // Large padded left (~400 KiB), small right (<= 200 KiB across 3 partitions after + // FilterExec StringArray allocation) for swap/keep/tie. + let left_batches_big = vec![ + make_batch( + &l_schema, + &[Some(1), Some(2), Some(2), None, Some(5)], + &[Some(10), Some(20), Some(30), Some(40), Some(50)], + 40 * 1024, + ), + make_batch( + &l_schema, + &[Some(1), Some(3), None, Some(6), Some(2)], + &[Some(5), Some(35), Some(45), Some(60), Some(15)], + 40 * 1024, + ), + ]; + let right_batches_small = vec![make_batch( + &r_schema, + &[Some(1), Some(2), Some(2), None, Some(4)], + &[Some(12), Some(25), Some(18), Some(50), Some(40)], + 16, + )]; + let right_batches_big = vec![ + make_batch( + &r_schema, + &[Some(1), Some(2), Some(2), None, Some(4)], + &[Some(12), Some(25), Some(18), Some(50), Some(40)], + 40 * 1024, + ), + make_batch( + &r_schema, + &[Some(5), Some(7), None, Some(1)], + &[Some(55), Some(70), Some(80), Some(3)], + 40 * 1024, + ), + ]; + + let join_types = [ + JoinType::Inner, + JoinType::Left, + JoinType::LeftSemi, + JoinType::RightSemi, + JoinType::LeftAnti, + ]; + let null_eqs = [ + NullEquality::NullEqualsNothing, + NullEquality::NullEqualsNull, + ]; + + #[derive(Clone, Copy)] + enum Mode { + Keep, + Swap, + Tie, + } + + for join_type in join_types { + for with_filter in [false, true] { + for null_equality in null_eqs { + for mode in [Mode::Keep, Mode::Swap, Mode::Tie] { + let filter = with_filter.then(non_output_residual_filter); + let r_batches = match mode { + Mode::Tie => right_batches_big.clone(), + Mode::Keep | Mode::Swap => right_batches_small.clone(), + }; + let (cap, expected_reason) = match mode { + Mode::Keep => { + (10 * 1024 * 1024, "adaptive_decision_reason_left_small") + } + Mode::Swap => (256 * 1024, "adaptive_decision_reason_swap_right"), + Mode::Tie => { + (256 * 1024, "adaptive_decision_reason_right_crossed") + } + }; + + let p = 3; + let pool = Arc::new(PeakTrackingMemoryPool::new(64 * 1024 * 1024)); + let adapt_ctx = make_ctx(cap, 4, Some(Arc::clone(&pool)), false); + let (stock_out, adapt_out, adapt_join, adapt_df) = + run_stock_vs_adaptive( + || { + build_partitioned_join( + make_single_partition_src( + Arc::clone(&l_schema), + left_batches_big.clone(), + ), + make_single_partition_src( + Arc::clone(&r_schema), + r_batches.clone(), + ), + on.clone(), + filter.clone(), + join_type, + None, + null_equality, + p, + ) + }, + p, + 4, + adapt_ctx, + ) + .await?; + + let metrics = adapt_join.metrics().unwrap(); + assert_eq!( + batches_to_sort_string(&stock_out), + batches_to_sort_string(&adapt_out), + "row mismatch for {join_type:?} filter={with_filter} null_eq={null_equality:?}" + ); + drop(adapt_join); + assert_pool_returns_to_zero(&pool).await; + + assert_eq!(metric_sum(&metrics, expected_reason), 1); + + if matches!(mode, Mode::Swap) { + assert_eq!(metric_sum(&metrics, "adaptive_build_swapped"), p); + assert_eq!(metric_sum(&metrics, "adaptive_right_sampled"), p); + assert!(is_filter_complete(&adapt_df)); + let expr = adapt_df.current()?; + assert!( + is_literal_true(&expr), + "expected literal true dynamic filter on swap (null_eq={null_equality:?}), got {expr}" + ); + } else if matches!(mode, Mode::Tie) { + assert_eq!(metric_sum(&metrics, "adaptive_build_swapped"), 0); + assert!(is_filter_complete(&adapt_df)); + let expr = adapt_df.current()?; + assert!( + is_literal_true(&expr), + "expected literal true dynamic filter on RightCrossed after early release (null_eq={null_equality:?}), got {expr}" + ); + } + } + } + } + } + + Ok(()) +} + +#[tokio::test(start_paused = true)] +async fn adaptive_differential_parity_slow_and_waiting_right_swaps_all_v1_types() +-> Result<()> { + let (l_schema, r_schema, on) = schemas_and_on()?; + + let l_batch = make_batch( + &l_schema, + &[Some(1), Some(2), None, Some(3)], + &[Some(10), Some(20), Some(30), Some(40)], + 64 * 1024, + ); + let r_batch = make_batch( + &r_schema, + &[Some(1), Some(2), None, Some(4)], + &[Some(15), Some(15), Some(35), Some(45)], + 16, + ); + + let make_left = || { + let lb = l_batch.clone(); + vec_plan(Arc::clone(&l_schema), &on[0].0, 1, move |_, _| { + vec![Ok(lb.clone())] + }) + }; + + for join_type in [ + JoinType::Inner, + JoinType::Left, + JoinType::LeftSemi, + JoinType::RightSemi, + JoinType::LeftAnti, + ] { + let rb = r_batch.clone(); + let right_stock = vec_plan(Arc::clone(&r_schema), &on[0].1, 1, move |_, _| { + vec![Ok(rb.clone())] + }); + let (stock_join, _) = build_direct_partitioned_join( + make_left(), + right_stock, + on.clone(), + Some(non_output_residual_filter()), + join_type, + None, + NullEquality::NullEqualsNothing, + )?; + let stock_out = + execute_all_partitions(&stock_join, 1, make_ctx(0, 4, None, false)).await?; + + let dyn_filter = new_dyn_filter(&on); + let df_wait = Arc::clone(&dyn_filter); + let rb2 = r_batch.clone(); + let rs2 = Arc::clone(&r_schema); + // Right waits on dynamic filter completion and then sleeps (simulating a slow + // pipeline-breaking right child). Releasing the filter on entering SampleRight + // unblocks wait_complete immediately and allows the join to swap cleanly. + let right_adapt = Arc::new(CustomPlan::new( + Arc::clone(&rs2), + Partitioning::Hash(vec![Arc::clone(&on[0].1)], 1), + move |_, _| { + Ok(Box::pin(ScriptedStream::new( + Arc::clone(&rs2), + vec![ + Step::WaitFilterComplete(Arc::clone(&df_wait)), + Step::Sleep(Duration::from_secs(5)), + Step::Batch(rb2.clone()), + ], + ))) + }, + )); + let adapt_join = wire_join( + make_left(), + right_adapt, + &dyn_filter, + on.clone(), + Some(non_output_residual_filter()), + join_type, + None, + NullEquality::NullEqualsNothing, + PartitionMode::Partitioned, + false, + )?; + let adapt_out = + execute_all_partitions(&adapt_join, 1, make_ctx(128 * 1024, 4, None, false)) + .await?; + + assert_eq!( + batches_to_sort_string(&stock_out), + batches_to_sort_string(&adapt_out), + "slow/waiting right swap parity failed for {join_type:?}" + ); + assert!(is_filter_complete(&dyn_filter)); + assert!(is_literal_true(&dyn_filter.current()?)); + let metrics = adapt_join.metrics().unwrap(); + assert_eq!( + metric_sum(&metrics, "adaptive_decision_reason_swap_right"), + 1 + ); + assert_eq!(metric_sum(&metrics, "adaptive_build_swapped"), 1); + } + + Ok(()) +} + +#[tokio::test] +async fn adaptive_differential_parity_projections_and_empty_projection() -> Result<()> { + let (l_schema, r_schema, on) = schemas_and_on()?; + + let left_batches = vec![make_batch( + &l_schema, + &[Some(1), Some(2), Some(2), Some(3), None], + &[Some(10), Some(20), Some(30), Some(40), Some(50)], + 64 * 1024, + )]; + let right_batches = vec![make_batch( + &r_schema, + &[Some(1), Some(2), Some(4)], + &[Some(15), Some(25), Some(45)], + 16, + )]; + + let cases: &[(JoinType, Vec>>)] = &[ + ( + JoinType::Inner, + vec![None, Some(vec![4, 0]), Some(vec![0, 0, 3]), Some(vec![])], + ), + ( + JoinType::Left, + vec![None, Some(vec![4, 1, 0]), Some(vec![3, 3]), Some(vec![])], + ), + ( + JoinType::LeftSemi, + vec![None, Some(vec![2, 0]), Some(vec![0, 0]), Some(vec![])], + ), + ( + JoinType::RightSemi, + vec![None, Some(vec![2, 0]), Some(vec![1, 1]), Some(vec![])], + ), + ( + JoinType::LeftAnti, + vec![None, Some(vec![1, 0]), Some(vec![0, 0]), Some(vec![])], + ), + ]; + + for (join_type, projections) in cases { + for proj in projections { + let p = 2; + let (stock_out, adapt_out, adapt_join, _) = run_stock_vs_adaptive( + || { + build_partitioned_join( + make_single_partition_src( + Arc::clone(&l_schema), + left_batches.clone(), + ), + make_single_partition_src( + Arc::clone(&r_schema), + right_batches.clone(), + ), + on.clone(), + Some(non_output_residual_filter()), + *join_type, + proj.clone(), + NullEquality::NullEqualsNothing, + p, + ) + }, + p, + 2, + make_ctx(200 * 1024, 2, None, false), + ) + .await?; + + if proj.as_ref().is_some_and(|v| v.is_empty()) { + let stock_rows: usize = stock_out.iter().map(|b| b.num_rows()).sum(); + let adapt_rows: usize = adapt_out.iter().map(|b| b.num_rows()).sum(); + assert_eq!( + stock_rows, adapt_rows, + "empty projection row count mismatch for {join_type:?}" + ); + } else { + assert_eq!( + batches_to_sort_string(&stock_out), + batches_to_sort_string(&adapt_out), + "projection parity mismatch for {join_type:?} proj={proj:?}" + ); + } + let metrics = adapt_join.metrics().unwrap(); + assert_eq!(metric_sum(&metrics, "adaptive_build_swapped"), p); + } + } + + Ok(()) +} + +#[tokio::test] +async fn adaptive_differential_parity_edge_data_cases_and_late_duplicate_residual() +-> Result<()> { + let (l_schema, r_schema, on) = schemas_and_on()?; + + let data_cases = vec![ + ( + "empty_left", + vec![], + vec![make_batch(&r_schema, &[Some(1)], &[Some(10)], 16)], + ), + ( + "all_null_nonempty_left", + vec![make_batch( + &l_schema, + &[None, None, None], + &[Some(1), Some(2), Some(3)], + 4096, + )], + vec![make_batch( + &r_schema, + &[Some(1), None], + &[Some(10), Some(20)], + 16, + )], + ), + ( + "late_duplicate_residual", + vec![make_batch( + &l_schema, + &[Some(7), Some(7), Some(7), Some(7), Some(7)], + &[Some(100), Some(100), Some(100), Some(100), Some(1)], + 2048, + )], + vec![make_batch( + &r_schema, + &[Some(7), Some(7), Some(7), Some(7)], + &[Some(0), Some(0), Some(0), Some(50)], + 16, + )], + ), + ]; + + for (name, lb, rb) in data_cases { + for join_type in [ + JoinType::Inner, + JoinType::Left, + JoinType::LeftSemi, + JoinType::RightSemi, + JoinType::LeftAnti, + ] { + for null_eq in [ + NullEquality::NullEqualsNothing, + NullEquality::NullEqualsNull, + ] { + let p = 2; + let (stock_out, adapt_out, _, _) = run_stock_vs_adaptive( + || { + build_partitioned_join( + make_single_partition_src(Arc::clone(&l_schema), lb.clone()), + make_single_partition_src(Arc::clone(&r_schema), rb.clone()), + on.clone(), + Some(non_output_residual_filter()), + join_type, + None, + null_eq, + p, + ) + }, + p, + 2, + make_ctx(2048, 2, None, false), + ) + .await?; + + assert_eq!( + batches_to_sort_string(&stock_out), + batches_to_sort_string(&adapt_out), + "edge case `{name}` failed for {join_type:?} null_eq={null_eq:?}" + ); + } + } + } + + Ok(()) +} + +#[tokio::test] +async fn adaptive_swap_uses_perfect_hash_array_map() -> Result<()> { + let (l_schema, r_schema, on) = schemas_and_on()?; + + // Dense single integer key 0..10 on small right; padded large left triggers swap. + let left_batches = vec![make_batch( + &l_schema, + &(0..20).map(|i| Some(i % 10)).collect::>(), + &(0..20).map(Some).collect::>(), + 16 * 1024, + )]; + let right_batches = vec![make_batch( + &r_schema, + &(0..10).map(Some).collect::>(), + &(100..110).map(Some).collect::>(), + 4, + )]; + + let p = 1; + let ctx = make_ctx_with(128 * 1024, 64, None, false, |opts| { + opts.execution.perfect_hash_join_small_build_threshold = 1024; + opts.execution.perfect_hash_join_min_key_density = 0.0; + }); + let (stock_out, adapt_out, adapt_join, _) = run_stock_vs_adaptive( + || { + build_partitioned_join( + make_single_partition_src(Arc::clone(&l_schema), left_batches.clone()), + make_single_partition_src(Arc::clone(&r_schema), right_batches.clone()), + on.clone(), + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + p, + ) + }, + p, + 64, + ctx, + ) + .await?; + + assert_eq!( + batches_to_sort_string(&stock_out), + batches_to_sort_string(&adapt_out) + ); + let metrics = adapt_join.metrics().unwrap(); + assert_eq!(metric_sum(&metrics, "adaptive_build_swapped"), 1); + assert!( + metric_sum(&metrics, "array_map_created_count") >= 1, + "expected ArrayMap to be used on swapped dense integer build side" + ); + Ok(()) +} + +#[tokio::test] +async fn adaptive_swap_empty_and_all_null_right_and_early_release() -> Result<()> { + let (l_schema, r_schema, on) = schemas_and_on()?; + + let big_left = make_batch( + &l_schema, + &[Some(1), Some(2), None], + &[Some(10), Some(20), Some(30)], + 96 * 1024, + ); + let all_null_right = make_batch(&r_schema, &[None, None], &[Some(1), Some(2)], 8); + + // Exercise swapped Left and LeftAnti joins with empty and all-NULL right inputs. + for (r_name, r_batches) in [ + ("empty_right", vec![]), + ("all_null_right", vec![all_null_right.clone()]), + ] { + for join_type in [JoinType::Left, JoinType::LeftAnti] { + let (stock_out, adapt_out, adapt_join, _) = run_stock_vs_adaptive( + || { + build_partitioned_join( + make_single_partition_src( + Arc::clone(&l_schema), + vec![big_left.clone()], + ), + make_single_partition_src( + Arc::clone(&r_schema), + r_batches.clone(), + ), + on.clone(), + None, + join_type, + None, + NullEquality::NullEqualsNothing, + 2, + ) + }, + 2, + 4, + make_ctx(200 * 1024, 4, None, false), + ) + .await?; + assert_eq!( + batches_to_sort_string(&stock_out), + batches_to_sort_string(&adapt_out), + "empty/all-null right `{r_name}` mismatch for {join_type:?}" + ); + assert_eq!( + metric_sum(&adapt_join.metrics().unwrap(), "adaptive_build_swapped"), + 2 + ); + } + } + + // Verify empty-build inner/semi joins release the sampled left reservation before the stream is dropped. + for join_type in [JoinType::Inner, JoinType::LeftSemi, JoinType::RightSemi] { + let pool = Arc::new(PeakTrackingMemoryPool::new(16 * 1024 * 1024)); + let lb = big_left.clone(); + let left_plan = vec_plan(Arc::clone(&l_schema), &on[0].0, 1, move |_, _| { + vec![Ok(lb.clone())] + }); + let right_plan = vec_plan(Arc::clone(&r_schema), &on[0].1, 1, |_, _| vec![]); + let (adapt_join, _) = build_direct_partitioned_join( + left_plan, + right_plan, + on.clone(), + None, + join_type, + None, + NullEquality::NullEqualsNothing, + )?; + let ctx = make_ctx(1024, 4, Some(Arc::clone(&pool)), false); + let mut stream = adapt_join.execute(0, ctx)?; + assert!(stream.next().await.is_none()); + // Only the empty build map's small header may remain reserved after early completion. + assert!( + pool.reserved() < 4096, + "expected sampled left replay reservation to be released immediately on early Completed for {join_type:?}, reserved={}", + pool.reserved() + ); + drop(stream); + assert_eq!(pool.reserved(), 0); + } + + Ok(()) +} + +/// Shared pacing state between [`PacedStream`] and [`PermitReleasingExec`]. +struct PacingState { + permits: Arc, + sent: Vec, + received: Vec, + closed: Vec, +} + +impl PacingState { + fn new(partitions: usize, max_in_flight: usize) -> Arc { + Arc::new(Self { + permits: Arc::new(Semaphore::new(max_in_flight)), + sent: (0..partitions).map(|_| AtomicUsize::new(0)).collect(), + received: (0..partitions).map(|_| AtomicUsize::new(0)).collect(), + closed: (0..partitions).map(|_| AtomicBool::new(false)).collect(), + }) + } +} + +/// Paced producer emitting `(target_partition, batch)` pairs one at a time gated by +/// a semaphore of in-flight permits, keeping RepartitionExec queue backlog bounded +/// without spilling. +struct PacedStream { + schema: SchemaRef, + batches: VecDeque<(usize, RecordBatch)>, + pacing: Arc, + #[expect(clippy::type_complexity)] + acquire_fut: Option< + Pin< + Box< + dyn Future< + Output = std::result::Result< + tokio::sync::OwnedSemaphorePermit, + tokio::sync::AcquireError, + >, + > + Send, + >, + >, + >, +} + +impl PacedStream { + fn new( + schema: SchemaRef, + batches: Vec<(usize, RecordBatch)>, + pacing: Arc, + ) -> Self { + Self { + schema, + batches: batches.into(), + pacing, + acquire_fut: None, + } + } +} + +impl RecordBatchStream for PacedStream { + fn schema(&self) -> SchemaRef { + Arc::clone(&self.schema) + } +} + +impl Stream for PacedStream { + type Item = Result; + + fn poll_next( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> Poll> { + loop { + let Some(&(part, _)) = self.batches.front() else { + return Poll::Ready(None); + }; + if self.pacing.closed[part].load(Ordering::SeqCst) { + self.batches.pop_front(); + continue; + } + let permits = Arc::clone(&self.pacing.permits); + let fut = self.acquire_fut.get_or_insert_with(|| { + Box::pin(async move { permits.acquire_owned().await }) + }); + match fut.as_mut().poll(cx) { + Poll::Pending => return Poll::Pending, + Poll::Ready(Ok(permit)) => { + self.acquire_fut = None; + let (part, batch) = self.batches.pop_front().unwrap(); + if self.pacing.closed[part].load(Ordering::SeqCst) { + drop(permit); + continue; + } + permit.forget(); + self.pacing.sent[part].fetch_add(1, Ordering::SeqCst); + return Poll::Ready(Some(Ok(batch))); + } + Poll::Ready(Err(_)) => return Poll::Ready(None), + } + } + } +} + +/// Thin pass-through plan above `RepartitionExec` that returns one semaphore +/// permit each time a downstream partition consumes a repartitioned batch. +struct PermitReleasingExec { + child: Arc, + pacing: Arc, +} + +impl fmt::Debug for PermitReleasingExec { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "PermitReleasingExec") + } +} + +impl DisplayAs for PermitReleasingExec { + fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "PermitReleasingExec") + } +} + +impl ExecutionPlan for PermitReleasingExec { + fn name(&self) -> &'static str { + "PermitReleasingExec" + } + + fn properties(&self) -> &Arc { + self.child.properties() + } + + fn children(&self) -> Vec<&Arc> { + vec![&self.child] + } + + fn apply_expressions( + &self, + _f: &mut dyn FnMut(&Arc) -> Result, + ) -> Result { + Ok(TreeNodeRecursion::Continue) + } + + fn replace_children( + self: Arc, + children: Vec>, + _options: ReplaceChildrenOptions, + ) -> Result> { + Ok(Arc::new(Self { + child: Arc::clone(&children[0]), + pacing: Arc::clone(&self.pacing), + })) + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> Result> { + self.replace_children( + children, + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + ) + } + + fn execute( + &self, + partition: usize, + context: Arc, + ) -> Result { + let inner = self.child.execute(partition, context)?; + Ok(Box::pin(PermitReleasingStream { + partition, + inner, + pacing: Arc::clone(&self.pacing), + })) + } +} + +struct PermitReleasingStream { + partition: usize, + inner: SendableRecordBatchStream, + pacing: Arc, +} + +impl Drop for PermitReleasingStream { + fn drop(&mut self) { + self.pacing.closed[self.partition].store(true, Ordering::SeqCst); + let sent = self.pacing.sent[self.partition].load(Ordering::SeqCst); + let received = self.pacing.received[self.partition].load(Ordering::SeqCst); + if sent > received { + self.pacing.permits.add_permits(sent - received); + } + } +} + +impl RecordBatchStream for PermitReleasingStream { + fn schema(&self) -> SchemaRef { + self.inner.schema() + } +} + +impl Stream for PermitReleasingStream { + type Item = Result; + + fn poll_next( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> Poll> { + let poll = self.inner.poll_next_unpin(cx); + if matches!(poll, Poll::Ready(Some(Ok(_)))) { + self.pacing.received[self.partition].fetch_add(1, Ordering::SeqCst); + self.pacing.permits.add_permits(1); + } + poll + } +} + +fn make_paced_batches( + schema: &SchemaRef, + num_batches: usize, + rows_per_batch: usize, + pad_len: usize, + skewed_key: Option, +) -> Vec { + let mut out = Vec::with_capacity(num_batches); + for b in 0..num_batches { + let keys: Vec> = (0..rows_per_batch) + .map(|r| Some(skewed_key.unwrap_or((b * rows_per_batch + r) as i32))) + .collect(); + let vals: Vec> = (0..rows_per_batch) + .map(|r| Some((b * rows_per_batch + r) as i32)) + .collect(); + out.push(make_batch(schema, &keys, &vals, pad_len)); + } + out +} + +#[tokio::test] +async fn adaptive_oom_avoidance_balanced_62_partitions() -> Result<()> { + let p = 62; + let l_schema = left_schema_with_meta(); + // Compact Int32-only right schema so 62-way FilterExec does not allocate a + // 64 KiB StringBuilder buffer per partition for tiny right batches. + let r_schema = Arc::new(Schema::new(vec![ + Field::new("k", DataType::Int32, true), + Field::new("rv", DataType::Int32, true), + ])); + let on: JoinOn = vec![( + Arc::new(Column::new_with_schema("k", &l_schema)?), + Arc::new(Column::new_with_schema("k", &r_schema)?), + )]; + + // Route each batch to one partition and include a sparse key so stock uses JoinHashMapU32 rather than ArrayMap. + let part_keys: Vec = (0..p).map(|part| key_for_partition(part, p)).collect(); + let sparse_keys: Vec = (0..p) + .map(|part| key_for_partition_from(part, p, 2_000_000)) + .collect(); + let rows_per_batch = 512; + let rounds = 3; + let mut left_batches = Vec::with_capacity(p * rounds); + for round in 0..rounds { + for part in 0..p { + let mut keys = vec![Some(part_keys[part]); rows_per_batch]; + keys[rows_per_batch - 1] = Some(sparse_keys[part]); + let vals: Vec> = (0..rows_per_batch) + .map(|r| Some(((round * p + part) * rows_per_batch + r) as i32)) + .collect(); + left_batches.push((part, make_batch(&l_schema, &keys, &vals, 48))); + } + } + // Tiny right: one row for each of the first 16 partition keys. + let right_batches = vec![RecordBatch::try_new( + Arc::clone(&r_schema), + vec![ + Arc::new(Int32Array::from( + (0..16).map(|i| Some(part_keys[i])).collect::>(), + )), + Arc::new(Int32Array::from( + (0..16).map(|i| Some(i * 10)).collect::>(), + )), + ], + )?]; + + // Keep the pool limit above bounded shuffle buffering but below the stock build's peak reservation. + let pool_limit = 7 * 1024 * 1024; + let adaptive_cap = 1536 * 1024; + let max_in_flight = 8; + + let build_paced_join = + |left_batches: Vec<(usize, RecordBatch)>, + right_batches: Vec| + -> Result<(HashJoinExec, Arc)> { + let pacing = PacingState::new(p, max_in_flight); + let lb = Arc::new(left_batches); + let ls = Arc::clone(&l_schema); + let pacing_prod = Arc::clone(&pacing); + let left_src = Arc::new(CustomPlan::new( + Arc::clone(&l_schema), + Partitioning::UnknownPartitioning(1), + move |_, _| { + Ok(Box::pin(PacedStream::new( + Arc::clone(&ls), + lb.as_ref().clone(), + Arc::clone(&pacing_prod), + ))) + }, + )); + let left_repart: Arc = Arc::new(RepartitionExec::try_new( + left_src, + Partitioning::Hash(vec![Arc::clone(&on[0].0)], p), + )?); + let left_paced: Arc = Arc::new(PermitReleasingExec { + child: left_repart, + pacing, + }); + let right_repart: Arc = + Arc::new(RepartitionExec::try_new( + make_single_partition_src(Arc::clone(&r_schema), right_batches), + Partitioning::Hash(vec![Arc::clone(&on[0].1)], p), + )?); + build_direct_partitioned_join( + left_paced, + right_repart, + on.clone(), + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + ) + }; + + let stock_pool = Arc::new(PeakTrackingMemoryPool::new(pool_limit)); + let (stock_join, _) = build_paced_join(left_batches.clone(), right_batches.clone())?; + let stock_err = execute_all_partitions( + &stock_join, + p, + make_ctx(0, rows_per_batch, Some(Arc::clone(&stock_pool)), true), + ) + .await + .expect_err("stock join should OOM under tight memory budget"); + assert!( + matches!(stock_err, DataFusionError::ResourcesExhausted(_)) + || stock_err.to_string().contains("Resources exhausted"), + "expected ResourcesExhausted, got: {stock_err}" + ); + assert!( + stock_err.to_string().contains("HashJoinInput"), + "expected stock OOM to name HashJoinInput, got: {stock_err}" + ); + + let adapt_pool = Arc::new(PeakTrackingMemoryPool::new(pool_limit)); + let (adapt_join, adapt_df) = build_paced_join(left_batches, right_batches)?; + let adapt_out = execute_all_partitions( + &adapt_join, + p, + make_ctx( + adaptive_cap, + rows_per_batch, + Some(Arc::clone(&adapt_pool)), + true, + ), + ) + .await?; + + let total_rows: usize = adapt_out.iter().map(|b| b.num_rows()).sum(); + assert_eq!(total_rows, 16 * rounds * (rows_per_batch - 1)); + let metrics = adapt_join.metrics().unwrap(); + assert_eq!(metric_sum(&metrics, "adaptive_build_swapped"), p); + assert_eq!( + metric_sum(&metrics, "adaptive_decision_reason_swap_right"), + 1 + ); + assert_eq!(metric_sum(&metrics, "spill_count"), 0); + assert!(adapt_pool.peak_reserved() <= pool_limit); + drop(adapt_join); + assert_pool_returns_to_zero(&adapt_pool).await; + assert!(is_filter_complete(&adapt_df)); + assert!(is_literal_true(&adapt_df.current()?)); + + Ok(()) +} + +#[tokio::test] +async fn adaptive_oom_avoidance_skewed_hot_partition() -> Result<()> { + let p = 4; + let (l_schema, r_schema, on) = schemas_and_on()?; + + // All left rows share key=42 -> 100% routed to one hot partition (~2 MiB). + // Right has 2 matching rows for key=42 (~64 B). + let hot_batches = make_paced_batches(&l_schema, 32, 8, 8 * 1024, Some(42)); + let right_batches = vec![make_batch( + &r_schema, + &[Some(42), Some(42)], + &[Some(1), Some(2)], + 16, + )]; + + // Direct co-partitioned plans (putting all hot batches in partition 0) give + // exact paced control without RepartitionExec accumulating an unpaced backlog. + let pool_limit = 1024 * 1024; + let adaptive_cap = 128 * 1024; + + let make_part0_plan = |schema: SchemaRef, + key: &PhysicalExprRef, + batches: Vec| + -> Arc { + let batches = Arc::new(batches); + vec_plan(schema, key, p, move |part, _| { + if part == 0 { + batches.iter().cloned().map(Ok).collect() + } else { + vec![] + } + }) + }; + + let stock_pool = Arc::new(PeakTrackingMemoryPool::new(pool_limit)); + let (stock_join, _) = build_direct_partitioned_join( + make_part0_plan(Arc::clone(&l_schema), &on[0].0, hot_batches.clone()), + make_part0_plan(Arc::clone(&r_schema), &on[0].1, right_batches.clone()), + on.clone(), + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + )?; + let stock_err = + execute_all_partitions(&stock_join, p, make_ctx(0, 64, Some(stock_pool), true)) + .await + .expect_err("stock skewed join should OOM"); + assert!( + stock_err.to_string().contains("HashJoinInput[0]"), + "expected HashJoinInput[0] OOM, got: {stock_err}" + ); + + let adapt_pool = Arc::new(PeakTrackingMemoryPool::new(pool_limit)); + let (adapt_join, adapt_df) = build_direct_partitioned_join( + make_part0_plan(Arc::clone(&l_schema), &on[0].0, hot_batches), + make_part0_plan(Arc::clone(&r_schema), &on[0].1, right_batches), + on, + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + )?; + let adapt_out = execute_all_partitions( + &adapt_join, + p, + make_ctx(adaptive_cap, 64, Some(Arc::clone(&adapt_pool)), true), + ) + .await?; + + let total_rows: usize = adapt_out.iter().map(|b| b.num_rows()).sum(); + assert_eq!(total_rows, 32 * 8 * 2); + assert!(adapt_pool.peak_reserved() <= pool_limit); + assert_eq!(adapt_pool.reserved(), 0); + assert!(is_filter_complete(&adapt_df)); + assert_eq!( + metric_sum(&adapt_join.metrics().unwrap(), "adaptive_build_swapped"), + p + ); + + Ok(()) +} + +#[tokio::test] +async fn adaptive_retained_errored_stream_sample_left() -> Result<()> { + let p = 3; + let (l_schema, r_schema, on) = schemas_and_on()?; + + let p2_right_dropped = Arc::new(AtomicBool::new(false)); + let p2_right_dropped_cl = Arc::clone(&p2_right_dropped); + + let rs = Arc::clone(&r_schema); + let ok_left = make_batch(&l_schema, &[Some(1)], &[Some(10)], 64); + let ok_right = make_batch(&r_schema, &[Some(1)], &[Some(20)], 16); + + let left_plan = vec_plan(Arc::clone(&l_schema), &on[0].0, p, move |part, ls| { + if part == 2 { + vec![ + Ok(make_batch(ls, &[Some(2)], &[Some(20)], 4096)), + exec_err!("p2 left sample boom"), + ] + } else { + vec![Ok(ok_left.clone())] + } + }); + let right_plan = Arc::new(CustomPlan::new( + Arc::clone(&r_schema), + Partitioning::Hash(vec![Arc::clone(&on[0].1)], p), + move |part, _| { + let mut s = VecStream::new(Arc::clone(&rs), vec![Ok(ok_right.clone())]); + if part == 2 { + s = s.with_drop_flag(Arc::clone(&p2_right_dropped_cl)); + } + Ok(Box::pin(s)) + }, + )); + + let (join, _df) = build_direct_partitioned_join( + left_plan, + right_plan, + on, + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + )?; + + let pool = Arc::new(PeakTrackingMemoryPool::new(16 * 1024 * 1024)); + let ctx = make_ctx(64 * 1024, 16, Some(Arc::clone(&pool)), false); + + let s0 = join.execute(0, Arc::clone(&ctx))?; + let s1 = join.execute(1, Arc::clone(&ctx))?; + let mut s2 = join.execute(2, Arc::clone(&ctx))?; + + // Keep p2's errored stream alive while its siblings finish. + let err = s2 + .next() + .await + .expect("expected Err item from p2") + .expect_err("expected Err from p2"); + assert!(err.to_string().contains("p2 left sample boom")); + + // The error must release p2's child and sampling reservations before s2 is dropped. + assert!( + p2_right_dropped.load(Ordering::SeqCst), + "p2 right child must be dropped immediately on terminal error" + ); + assert_eq!( + pool.reserved(), + 0, + "p2 reservations must be 0 immediately after terminal error" + ); + + let (r0, r1) = tokio::time::timeout(TEST_TIMEOUT, async { + tokio::join!(common::collect(s0), common::collect(s1)) + }) + .await + .expect("siblings hung while errored p2 stream was retained"); + assert!(r0.is_ok()); + assert!(r1.is_ok()); + + assert!(s2.next().await.is_none()); + drop(s2); + assert_eq!(pool.reserved(), 0); + Ok(()) +} + +#[tokio::test] +async fn adaptive_retained_errored_stream_wait_build_side() -> Result<()> { + let p = 3; + let (l_schema, r_schema, on) = schemas_and_on()?; + + let p2_right_dropped = Arc::new(AtomicBool::new(false)); + let p2_right_dropped_cl = Arc::clone(&p2_right_dropped); + + let rs = Arc::clone(&r_schema); + + // Force right-side sampling over its limit, then fail while collecting the left tail. + let left_plan = vec_plan(Arc::clone(&l_schema), &on[0].0, p, |part, ls| { + if part == 2 { + vec![ + Ok(make_batch(ls, &[Some(2)], &[Some(20)], 8192)), + exec_err!("p2 left tail build boom"), + ] + } else { + vec![Ok(make_batch(ls, &[Some(1)], &[Some(10)], 64))] + } + }); + let right_plan = Arc::new(CustomPlan::new( + Arc::clone(&r_schema), + Partitioning::Hash(vec![Arc::clone(&on[0].1)], p), + move |part, _| { + let batch = make_batch(&rs, &[Some(1)], &[Some(20)], 8192); + let mut s = VecStream::new(Arc::clone(&rs), vec![Ok(batch)]); + if part == 2 { + s = s.with_drop_flag(Arc::clone(&p2_right_dropped_cl)); + } + Ok(Box::pin(s)) + }, + )); + + let (join, _df) = build_direct_partitioned_join( + left_plan, + right_plan, + on, + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + )?; + + let pool = Arc::new(PeakTrackingMemoryPool::new(16 * 1024 * 1024)); + let ctx = make_ctx(4096, 16, Some(Arc::clone(&pool)), false); + + let s0 = join.execute(0, Arc::clone(&ctx))?; + let s1 = join.execute(1, Arc::clone(&ctx))?; + let mut s2 = join.execute(2, Arc::clone(&ctx))?; + + // Keep p2's failed stream alive while verifying the other partitions finish. + let err = s2 + .next() + .await + .expect("expected Err from p2 WaitBuildSide") + .expect_err("expected Err from p2"); + assert!(err.to_string().contains("p2 left tail build boom")); + assert!( + p2_right_dropped.load(Ordering::SeqCst), + "p2 right/replay stream must be dropped immediately on WaitBuildSide error" + ); + assert_eq!(pool.reserved(), 0); + + let (r0, r1) = tokio::time::timeout(TEST_TIMEOUT, async { + tokio::join!(common::collect(s0), common::collect(s1)) + }) + .await + .expect("siblings hung after post-KeepLeft WaitBuildSide error"); + assert!(r0.is_ok()); + assert!(r1.is_ok()); + + assert!(s2.next().await.is_none()); + drop(s2); + assert_eq!(pool.reserved(), 0); + Ok(()) +} + +#[tokio::test] +async fn adaptive_sync_right_execute_error_unblocks_sibling() -> Result<()> { + let p = 2; + let (l_schema, r_schema, on) = schemas_and_on()?; + + let rs = Arc::clone(&r_schema); + let left_plan = vec_plan(Arc::clone(&l_schema), &on[0].0, p, |_, ls| { + vec![Ok(make_batch(ls, &[Some(1)], &[Some(10)], 64))] + }); + let right_plan = Arc::new(CustomPlan::new( + Arc::clone(&r_schema), + Partitioning::Hash(vec![Arc::clone(&on[0].1)], p), + move |part, _| { + if part == 1 { + return exec_err!("sync right execute boom"); + } + Ok(Box::pin(VecStream::new( + Arc::clone(&rs), + vec![Ok(make_batch(&rs, &[Some(1)], &[Some(20)], 16))], + ))) + }, + )); + + let (join, df) = build_direct_partitioned_join( + left_plan, + right_plan, + on, + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + )?; + + let ctx = make_ctx(64 * 1024, 16, None, false); + let s0 = join.execute(0, Arc::clone(&ctx))?; + let err = match join.execute(1, Arc::clone(&ctx)) { + Ok(_) => panic!("expected sync error from partition 1 right.execute"), + Err(err) => err, + }; + assert!(err.to_string().contains("sync right execute boom")); + + // Returning an error from p1's execute drops its ticket and report handle, so p0 must resume and finish. + let out0 = tokio::time::timeout(TEST_TIMEOUT, common::collect(s0)) + .await + .expect("sibling p0 hung after sync right.execute error on p1")?; + assert_eq!(out0.iter().map(|b| b.num_rows()).sum::(), 1); + assert!(is_filter_complete(&df)); + Ok(()) +} + +#[tokio::test] +async fn adaptive_waiting_right_consumer_unblocks_on_sample_right_and_swaps_or_keeps_left() +-> Result<()> { + let (l_schema, r_schema, on) = schemas_and_on()?; + + // Case 1: Blocking consumer calling `wait_complete().await` (including both an + // early background waiter subscribed BEFORE `SampleRight` and a late subscriber + // arriving AFTER `SampleRight` starts) unblocks immediately on `SampleRight` + // and the join still swaps cleanly (`SwapRight`) with exact stock parity. + { + let p = 2; + let dyn_filter = new_dyn_filter(&on); + let early_waiter = SpawnedTask::spawn({ + let df = Arc::clone(&dyn_filter); + async move { + df.wait_complete().await; + } + }); + // Give the early waiter a chance to park before sampling begins. + tokio::task::yield_now().await; + + let left_batches = vec![make_batch( + &l_schema, + &[Some(1), Some(2), Some(3), None], + &[Some(10), Some(20), Some(30), Some(40)], + 64 * 1024, + )]; + let right_batches = vec![make_batch( + &r_schema, + &[Some(1), Some(2), Some(4)], + &[Some(100), Some(200), Some(400)], + 16, + )]; + + let (stock_join, _) = build_partitioned_join( + make_single_partition_src(Arc::clone(&l_schema), left_batches.clone()), + make_single_partition_src(Arc::clone(&r_schema), right_batches.clone()), + on.clone(), + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + p, + )?; + let stock_out = + execute_all_partitions(&stock_join, p, make_ctx(0, 16, None, false)).await?; + + let left_repart: Arc = Arc::new(RepartitionExec::try_new( + make_single_partition_src(Arc::clone(&l_schema), left_batches), + Partitioning::Hash(vec![Arc::clone(&on[0].0)], p), + )?); + let right_repart: Arc = Arc::new(RepartitionExec::try_new( + make_single_partition_src(Arc::clone(&r_schema), right_batches), + Partitioning::Hash(vec![Arc::clone(&on[0].1)], p), + )?); + + // Wrap right partitions so partition 0 waits on `wait_complete()` before + // yielding (arriving AFTER `SampleRight` starts) while partition 1 also + // subscribes to `wait_complete()` after `SampleRight` starts. + let df_wait = Arc::clone(&dyn_filter); + let rs = Arc::clone(&r_schema); + let right_waiting = Arc::new(CustomPlan::new( + Arc::clone(&rs), + Partitioning::Hash(vec![Arc::clone(&on[0].1)], p), + move |part, ctx| { + let inner = right_repart.execute(part, ctx)?; + let df = Arc::clone(&df_wait); + let schema = inner.schema(); + let stream = futures::stream::once(async move { + // Late subscriber arriving once right sampling starts. + df.wait_complete().await; + inner + }) + .flatten(); + Ok(Box::pin(crate::stream::RecordBatchStreamAdapter::new( + schema, stream, + ))) + }, + )); + + let join = wire_join( + left_repart, + right_waiting, + &dyn_filter, + on.clone(), + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + PartitionMode::Partitioned, + false, + )?; + + let pool = Arc::new(PeakTrackingMemoryPool::new(16 * 1024 * 1024)); + let adapt_out = execute_all_partitions( + &join, + p, + make_ctx(200 * 1024, 16, Some(Arc::clone(&pool)), false), + ) + .await?; + + tokio::time::timeout(TEST_TIMEOUT, early_waiter) + .await + .expect("early wait_complete subscriber did not unblock") + .unwrap(); + assert_eq!( + batches_to_sort_string(&stock_out), + batches_to_sort_string(&adapt_out) + ); + assert!(is_filter_complete(&dyn_filter)); + assert!(is_literal_true(&dyn_filter.current()?)); + let metrics = join.metrics().unwrap(); + assert_eq!( + metric_sum(&metrics, "adaptive_decision_reason_swap_right"), + 1 + ); + assert_eq!(metric_sum(&metrics, "adaptive_build_swapped"), p); + drop(join); + assert_pool_returns_to_zero(&pool).await; + } + + // Case 2: Blocking consumer calling `wait_complete().await` unblocks on + // `SampleRight`, then right exceeds cap -> `KeepLeft(RightCrossed)` with filter + // finalized to `lit(true)`, exact stock parity, and clean accumulator detach. + { + let p = 2; + let dyn_filter = new_dyn_filter(&on); + let rs = Arc::clone(&r_schema); + let df_wait = Arc::clone(&dyn_filter); + + let left_batches_per_part = move |part: usize, ls: &SchemaRef| { + let key = key_for_partition(part, p); + vec![Ok(make_batch( + ls, + &[Some(key), Some(key)], + &[Some(10), Some(20)], + 4096, + ))] + }; + let right_batches_per_part = move |part: usize, rs: &SchemaRef| { + let key = key_for_partition(part, p); + vec![Ok(make_batch(rs, &[Some(key)], &[Some(100)], 4096))] + }; + + let (stock_join, _) = build_direct_partitioned_join( + vec_plan(Arc::clone(&l_schema), &on[0].0, p, left_batches_per_part), + vec_plan(Arc::clone(&r_schema), &on[0].1, p, right_batches_per_part), + on.clone(), + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + )?; + let stock_out = + execute_all_partitions(&stock_join, p, make_ctx(0, 16, None, false)).await?; + + let right_waiting = Arc::new(CustomPlan::new( + Arc::clone(&rs), + Partitioning::Hash(vec![Arc::clone(&on[0].1)], p), + move |part, _| { + let key = key_for_partition(part, p); + Ok(Box::pin(ScriptedStream::new( + Arc::clone(&rs), + vec![ + Step::WaitFilterComplete(Arc::clone(&df_wait)), + Step::Batch(make_batch(&rs, &[Some(key)], &[Some(100)], 4096)), + ], + ))) + }, + )); + let adapt_join = wire_join( + vec_plan(Arc::clone(&l_schema), &on[0].0, p, left_batches_per_part), + right_waiting, + &dyn_filter, + on.clone(), + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + PartitionMode::Partitioned, + false, + )?; + + let pool = Arc::new(PeakTrackingMemoryPool::new(16 * 1024 * 1024)); + let adapt_out = execute_all_partitions( + &adapt_join, + p, + make_ctx(1024, 16, Some(Arc::clone(&pool)), false), + ) + .await?; + + assert_eq!( + batches_to_sort_string(&stock_out), + batches_to_sort_string(&adapt_out) + ); + assert!(is_filter_complete(&dyn_filter)); + assert!(is_literal_true(&dyn_filter.current()?)); + let metrics = adapt_join.metrics().unwrap(); + assert_eq!( + metric_sum(&metrics, "adaptive_decision_reason_right_crossed"), + 1 + ); + assert_eq!(metric_sum(&metrics, "adaptive_build_swapped"), 0); + // Late execute() after RightCrossed (post filter release) takes StockDetached + // cleanly without hanging or touching the discharged accumulator. + let late_stream = adapt_join.execute(0, make_ctx(1024, 16, None, false))?; + let late_out = tokio::time::timeout(TEST_TIMEOUT, common::collect(late_stream)) + .await + .expect("late StockDetached partition hung after RightCrossed")?; + assert_eq!(late_out.iter().map(|b| b.num_rows()).sum::(), 2); + drop(adapt_join); + assert_pool_returns_to_zero(&pool).await; + } + + Ok(()) +} + +#[tokio::test] +async fn adaptive_decision_wall_time_recorded_once_and_sample_poll_time_separate() +-> Result<()> { + let p = 4; + let (l_schema, r_schema, on) = schemas_and_on()?; + let rs = Arc::clone(&r_schema); + + let left_plan = vec_plan(Arc::clone(&l_schema), &on[0].0, p, move |part, ls| { + let key = key_for_partition(part, p); + vec![Ok(make_batch(ls, &[Some(key)], &[Some(10)], 128 * 1024))] + }); + let right_delay = Duration::from_millis(80); + let right_plan = Arc::new(CustomPlan::new( + Arc::clone(&r_schema), + Partitioning::Hash(vec![Arc::clone(&on[0].1)], p), + move |part, _| { + let key = key_for_partition(part, p); + Ok(Box::pin(ScriptedStream::new( + Arc::clone(&rs), + vec![ + Step::Sleep(right_delay), + Step::Batch(make_batch(&rs, &[Some(key)], &[Some(20)], 16)), + ], + ))) + }, + )); + + let (join, _) = build_direct_partitioned_join( + left_plan, + right_plan, + on, + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + )?; + + let wall_start = datafusion_common::instant::Instant::now(); + let out = + execute_all_partitions(&join, p, make_ctx(400 * 1024, 16, None, false)).await?; + let total_elapsed = wall_start.elapsed(); + assert_eq!(out.iter().map(|b| b.num_rows()).sum::(), p); + + let metrics = join.metrics().unwrap(); + assert_eq!( + metric_sum(&metrics, "adaptive_decision_reason_swap_right"), + 1 + ); + + // `adaptive_decision_wall_time` must be recorded once join-wide (partition = None), + // not summed P times across all partitions. + let wall_entries: Vec<_> = metrics + .iter() + .filter(|m| m.value().name() == "adaptive_decision_wall_time") + .collect(); + assert_eq!( + wall_entries.len(), + 1, + "expected exactly one global adaptive_decision_wall_time metric" + ); + assert!( + wall_entries[0].partition().is_none(), + "adaptive_decision_wall_time must be a global (unpartitioned) metric" + ); + let wall_ns = wall_entries[0].value().as_usize() as u64; + let wall_dur = Duration::from_nanos(wall_ns); + assert!( + wall_dur >= Duration::from_millis(60), + "expected adaptive_decision_wall_time ({wall_dur:?}) to include the ~80ms parked right delay" + ); + assert!( + wall_dur <= total_elapsed + Duration::from_millis(50), + "adaptive_decision_wall_time ({wall_dur:?}) exceeded single-run elapsed ({total_elapsed:?}), indicating multi-partition summation" + ); + + // `adaptive_sample_poll_time` is per-partition inline CPU poll time (excludes parked sleep). + let poll_entries: Vec<_> = metrics + .iter() + .filter(|m| m.value().name() == "adaptive_sample_poll_time") + .collect(); + assert_eq!( + poll_entries.len(), + p, + "expected one adaptive_sample_poll_time metric per partition" + ); + assert!(poll_entries.iter().all(|m| m.partition().is_some())); + let poll_sum = + Duration::from_nanos(metric_sum(&metrics, "adaptive_sample_poll_time") as u64); + assert!( + poll_sum > Duration::ZERO, + "expected nonzero inline adaptive_sample_poll_time" + ); + assert!( + poll_sum < wall_dur, + "expected summed inline poll CPU time ({poll_sum:?}) to stay below parked wall time ({wall_dur:?})" + ); + Ok(()) +} + +#[tokio::test] +async fn adaptive_selective_filter_preserved_when_left_small() -> Result<()> { + let p = 2; + let (l_schema, r_schema, on) = schemas_and_on()?; + let dyn_filter = new_dyn_filter(&on); + + let scan_polls = Arc::new(AtomicUsize::new(0)); + let filter_complete_at_first_poll = Arc::new(AtomicBool::new(false)); + let filter_selective_at_first_poll = Arc::new(AtomicBool::new(false)); + + let rs = Arc::clone(&r_schema); + let left_plan = vec_plan(Arc::clone(&l_schema), &on[0].0, p, move |part, ls| { + let key = key_for_partition(part, p); + vec![Ok(make_batch(ls, &[Some(key)], &[Some(10)], 16))] + }); + + let scan_polls_cl = Arc::clone(&scan_polls); + let df_check = Arc::clone(&dyn_filter); + let complete_flag = Arc::clone(&filter_complete_at_first_poll); + let selective_flag = Arc::clone(&filter_selective_at_first_poll); + let right_leaf = Arc::new(CustomPlan::new( + Arc::clone(&r_schema), + Partitioning::Hash(vec![Arc::clone(&on[0].1)], p), + move |part, _| { + let key = key_for_partition(part, p); + let df_inner = Arc::clone(&df_check); + let complete_inner = Arc::clone(&complete_flag); + let selective_inner = Arc::clone(&selective_flag); + let cb = Arc::new(move || { + complete_inner.store(is_filter_complete(&df_inner), Ordering::SeqCst); + let expr = df_inner.current().unwrap(); + selective_inner.store(!is_literal_true(&expr), Ordering::SeqCst); + }); + Ok(Box::pin( + VecStream::new( + Arc::clone(&rs), + vec![Ok(make_batch( + &rs, + &[Some(key), Some(999)], + &[Some(1), Some(2)], + 16, + ))], + ) + .with_poll_counter(Arc::clone(&scan_polls_cl)) + .with_on_first_poll(cb), + )) + }, + )); + let join = wire_join( + left_plan, + right_leaf, + &dyn_filter, + on, + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + PartitionMode::Partitioned, + false, + )?; + + let out = + execute_all_partitions(&join, p, make_ctx(1024 * 1024, 16, None, false)).await?; + assert_eq!(out.iter().map(|b| b.num_rows()).sum::(), 2); + assert!(scan_polls.load(Ordering::SeqCst) > 0); + assert!( + filter_complete_at_first_poll.load(Ordering::SeqCst), + "right leaf scan must not be polled before dynamic filter completes" + ); + assert!( + filter_selective_at_first_poll.load(Ordering::SeqCst), + "dynamic filter must be selective (not literal true) at first scan poll" + ); + + let metrics = join.metrics().unwrap(); + assert_eq!(metric_sum(&metrics, "adaptive_right_sampled"), 0); + assert_eq!(metric_sum(&metrics, "adaptive_build_swapped"), 0); + assert_eq!( + metric_sum(&metrics, "adaptive_decision_reason_left_small"), + 1 + ); + Ok(()) +} + +#[tokio::test] +async fn adaptive_liveness_dropped_partition_in_sample_right() -> Result<()> { + let p = 3; + let (l_schema, r_schema, on) = schemas_and_on()?; + + let rs = Arc::clone(&r_schema); + let p2_entered_right = Arc::new(Notify::new()); + let p2_entered_right_cl = Arc::clone(&p2_entered_right); + let never = Arc::new(Notify::new()); + + let left_plan = vec_plan(Arc::clone(&l_schema), &on[0].0, p, move |part, ls| { + let key = key_for_partition(part, p); + vec![Ok(make_batch(ls, &[Some(key)], &[Some(10)], 256 * 1024))] + }); + let right_plan = Arc::new(CustomPlan::new( + Arc::clone(&r_schema), + Partitioning::Hash(vec![Arc::clone(&on[0].1)], p), + move |part, _| { + if part == 2 { + Ok(Box::pin(ScriptedStream::new( + Arc::clone(&rs), + vec![Step::NotifyThenWait { + signal: Arc::clone(&p2_entered_right_cl), + gate: Arc::clone(&never), + }], + ))) + } else { + let key = key_for_partition(part, p); + Ok(Box::pin(VecStream::new( + Arc::clone(&rs), + vec![Ok(make_batch(&rs, &[Some(key)], &[Some(20)], 16))], + ))) + } + }, + )); + + let (join, _) = build_direct_partitioned_join( + left_plan, + right_plan, + on, + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + )?; + + let pool = Arc::new(PeakTrackingMemoryPool::new(16 * 1024 * 1024)); + let ctx = make_ctx(200 * 1024, 16, Some(Arc::clone(&pool)), false); + let s0 = join.execute(0, Arc::clone(&ctx))?; + let s1 = join.execute(1, Arc::clone(&ctx))?; + let mut s2 = join.execute(2, Arc::clone(&ctx))?; + + // Dropping a partition stalled in SampleRight must unblock its siblings. + let drop_task = SpawnedTask::spawn(async move { + tokio::select! { + _ = p2_entered_right.notified() => {}, + _ = s2.next() => {}, + }; + drop(s2); + }); + + let (r0, r1) = tokio::time::timeout(TEST_TIMEOUT, async { + let res = tokio::join!(common::collect(s0), common::collect(s1)); + drop_task.await.unwrap(); + res + }) + .await + .expect("siblings hung after p2 dropped in SampleRight"); + assert!(r0.is_ok()); + assert!(r1.is_ok()); + assert_eq!(pool.reserved(), 0); + assert_eq!( + metric_sum( + &join.metrics().unwrap(), + "adaptive_decision_reason_abandoned" + ), + 1 + ); + Ok(()) +} + +#[tokio::test] +async fn adaptive_liveness_dual_waker_pending_left_switches_to_right() -> Result<()> { + let p = 2; + let (l_schema, r_schema, on) = schemas_and_on()?; + + let p0_left_parked = Arc::new(Notify::new()); + let p0_left_parked_cl = Arc::clone(&p0_left_parked); + let unblock_p0_left = Arc::new(Notify::new()); + let unblock_p0_left_cl = Arc::clone(&unblock_p0_left); + let unblock_p0_left_on_right = Arc::clone(&unblock_p0_left); + let p0_polled_right = Arc::new(AtomicBool::new(false)); + let p0_polled_right_cl = Arc::clone(&p0_polled_right); + + let ls = Arc::clone(&l_schema); + let rs = Arc::clone(&r_schema); + + // Keep p0's left stream pending until its right stream is polled. + let left_plan = Arc::new(CustomPlan::new( + Arc::clone(&l_schema), + Partitioning::Hash(vec![Arc::clone(&on[0].0)], p), + move |part, _| { + let key = key_for_partition(part, p); + if part == 0 { + Ok(Box::pin(ScriptedStream::new( + Arc::clone(&ls), + vec![ + Step::NotifyThenWait { + signal: Arc::clone(&p0_left_parked_cl), + gate: Arc::clone(&unblock_p0_left_cl), + }, + Step::Batch(make_batch(&ls, &[Some(key)], &[Some(10)], 16)), + ], + ))) + } else { + Ok(Box::pin(ScriptedStream::new( + Arc::clone(&ls), + vec![ + Step::Wait(Arc::clone(&p0_left_parked)), + Step::Batch(make_batch( + &ls, + &[Some(key)], + &[Some(20)], + 256 * 1024, + )), + ], + ))) + } + }, + )); + let right_plan = Arc::new(CustomPlan::new( + Arc::clone(&r_schema), + Partitioning::Hash(vec![Arc::clone(&on[0].1)], p), + move |part, _| { + let key = key_for_partition(part, p); + let mut s = VecStream::new( + Arc::clone(&rs), + vec![Ok(make_batch(&rs, &[Some(key)], &[Some(100)], 16))], + ); + if part == 0 { + let flag = Arc::clone(&p0_polled_right_cl); + let notify = Arc::clone(&unblock_p0_left_on_right); + s = s.with_on_first_poll(Arc::new(move || { + flag.store(true, Ordering::SeqCst); + notify.notify_one(); + })); + } + Ok(Box::pin(s)) + }, + )); + + let (join, _) = build_direct_partitioned_join( + left_plan, + right_plan, + on, + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + )?; + + let pool = Arc::new(PeakTrackingMemoryPool::new(16 * 1024 * 1024)); + let out = execute_all_partitions( + &join, + p, + make_ctx(200 * 1024, 16, Some(Arc::clone(&pool)), false), + ) + .await?; + assert!( + p0_polled_right.load(Ordering::SeqCst), + "p0 must switch from pending left to sampling right" + ); + assert_eq!(out.iter().map(|b| b.num_rows()).sum::(), 2); + assert_eq!( + metric_sum(&join.metrics().unwrap(), "adaptive_build_swapped"), + p + ); + assert_eq!(pool.reserved(), 0); + Ok(()) +} + +#[tokio::test] +async fn adaptive_liveness_nested_partitioned_hash_join_on_right() -> Result<()> { + let p = 2; + let l_schema = left_schema_with_meta(); + let r_schema = right_schema_with_meta(); + + let inner_on: JoinOn = vec![( + Arc::new(Column::new_with_schema("k", &r_schema)?), + Arc::new(Column::new_with_schema("k", &r_schema)?), + )]; + let (inner_join, _) = build_partitioned_join( + make_single_partition_src( + Arc::clone(&r_schema), + vec![make_batch( + &r_schema, + &[Some(1), Some(2)], + &[Some(10), Some(20)], + 16, + )], + ), + make_single_partition_src( + Arc::clone(&r_schema), + vec![make_batch( + &r_schema, + &[Some(1), Some(2)], + &[Some(100), Some(200)], + 16, + )], + ), + inner_on, + None, + JoinType::Inner, + Some(vec![0, 1, 2]), + NullEquality::NullEqualsNothing, + p, + )?; + + let outer_on: JoinOn = vec![( + Arc::new(Column::new_with_schema("k", &l_schema)?), + Arc::new(Column::new_with_schema("k", &inner_join.schema())?), + )]; + let outer_left = Arc::new(RepartitionExec::try_new( + make_single_partition_src( + Arc::clone(&l_schema), + vec![make_batch( + &l_schema, + &[Some(1), Some(2), Some(3)], + &[Some(5), Some(6), Some(7)], + 96 * 1024, + )], + ), + Partitioning::Hash(vec![Arc::clone(&outer_on[0].0)], p), + )?); + + let (outer_join, _) = build_direct_partitioned_join( + outer_left, + Arc::new(inner_join), + outer_on, + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + )?; + + let pool = Arc::new(PeakTrackingMemoryPool::new(32 * 1024 * 1024)); + let out = execute_all_partitions( + &outer_join, + p, + make_ctx(200 * 1024, 16, Some(Arc::clone(&pool)), false), + ) + .await?; + assert_eq!(out.iter().map(|b| b.num_rows()).sum::(), 2); + let metrics = outer_join.metrics().unwrap(); + drop(outer_join); + assert_pool_returns_to_zero(&pool).await; + assert_eq!(metric_sum(&metrics, "adaptive_build_swapped"), p); + Ok(()) +} + +#[tokio::test] +async fn adaptive_liveness_asymmetric_eof_tie() -> Result<()> { + let p = 2; + let (l_schema, r_schema, on) = schemas_and_on()?; + + let left_plan = vec_plan(Arc::clone(&l_schema), &on[0].0, p, |part, ls| { + let key = (part as i32) + 1; + vec![Ok(make_batch(ls, &[Some(key)], &[Some(10)], 4096))] + }); + // Combine an empty right stream on one partition with an over-limit batch on another. + let right_plan = vec_plan(Arc::clone(&r_schema), &on[0].1, p, |part, rs| { + if part == 0 { + vec![] + } else { + vec![Ok(make_batch(rs, &[Some(2)], &[Some(20)], 4096))] + } + }); + + let (join, _) = build_direct_partitioned_join( + left_plan, + right_plan, + on, + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + )?; + + let pool = Arc::new(PeakTrackingMemoryPool::new(16 * 1024 * 1024)); + let out = execute_all_partitions( + &join, + p, + make_ctx(1024, 16, Some(Arc::clone(&pool)), false), + ) + .await?; + assert_eq!(out.iter().map(|b| b.num_rows()).sum::(), 1); + assert_eq!(pool.reserved(), 0); + let metrics = join.metrics().unwrap(); + assert_eq!( + metric_sum(&metrics, "adaptive_decision_reason_right_crossed"), + 1 + ); + assert_eq!(metric_sum(&metrics, "adaptive_build_swapped"), 0); + Ok(()) +} + +#[tokio::test] +async fn adaptive_right_error_in_sample_right_replay_and_empty_inner() -> Result<()> { + let (l_schema, r_schema, on) = schemas_and_on()?; + + // A right-side sampling error must surface after buffered batches are replayed. + { + let rs = Arc::clone(&r_schema); + let right_tail_dropped = Arc::new(AtomicBool::new(false)); + let dropped_cl = Arc::clone(&right_tail_dropped); + + let left_plan = vec_plan(Arc::clone(&l_schema), &on[0].0, 1, |_, ls| { + vec![Ok(make_batch(ls, &[Some(1)], &[Some(10)], 200 * 1024))] + }); + let right_plan = Arc::new(CustomPlan::new( + Arc::clone(&r_schema), + Partitioning::Hash(vec![Arc::clone(&on[0].1)], 1), + move |_, _| { + Ok(Box::pin( + VecStream::new( + Arc::clone(&rs), + vec![ + Ok(make_batch(&rs, &[Some(1)], &[Some(20)], 16)), + exec_err!("right sample boom"), + ], + ) + .with_drop_flag(Arc::clone(&dropped_cl)), + )) + }, + )); + + let (join, _) = build_direct_partitioned_join( + left_plan, + right_plan, + on.clone(), + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + )?; + let pool = Arc::new(PeakTrackingMemoryPool::new(16 * 1024 * 1024)); + let err = execute_all_partitions( + &join, + 1, + make_ctx(128 * 1024, 16, Some(Arc::clone(&pool)), false), + ) + .await + .expect_err("expected right sample error to surface on replay"); + assert!(err.to_string().contains("right sample boom")); + assert!(right_tail_dropped.load(Ordering::SeqCst)); + assert_eq!(pool.reserved(), 0); + assert_eq!( + metric_sum( + &join.metrics().unwrap(), + "adaptive_decision_reason_right_error" + ), + 1 + ); + } + + // An empty inner build discards a right-side sampling error, matching the stock path. + { + let p1_key = key_for_partition(1, 2); + let left_plan = vec_plan(Arc::clone(&l_schema), &on[0].0, 2, move |part, ls| { + if part == 0 { + vec![] + } else { + vec![Ok(make_batch(ls, &[Some(p1_key)], &[Some(20)], 200 * 1024))] + } + }); + let right_plan = vec_plan(Arc::clone(&r_schema), &on[0].1, 2, move |part, rs| { + if part == 0 { + vec![exec_err!("p0 right error hidden by empty inner build")] + } else { + vec![Ok(make_batch(rs, &[Some(p1_key)], &[Some(200)], 16))] + } + }); + + let (join, _) = build_direct_partitioned_join( + left_plan, + right_plan, + on, + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + )?; + let pool = Arc::new(PeakTrackingMemoryPool::new(16 * 1024 * 1024)); + let out = execute_all_partitions( + &join, + 2, + make_ctx(128 * 1024, 16, Some(Arc::clone(&pool)), false), + ) + .await?; + assert_eq!(out.iter().map(|b| b.num_rows()).sum::(), 1); + assert_eq!(pool.reserved(), 0); + assert_eq!( + metric_sum( + &join.metrics().unwrap(), + "adaptive_decision_reason_right_error" + ), + 1 + ); + } + + Ok(()) +} + +#[tokio::test] +async fn adaptive_duplicate_execute_abandons_safely() -> Result<()> { + let p = 2; + let (l_schema, r_schema, on) = schemas_and_on()?; + + let left_plan = vec_plan(Arc::clone(&l_schema), &on[0].0, p, move |part, ls| { + let key = key_for_partition(part, p); + vec![Ok(make_batch(ls, &[Some(key)], &[Some(10)], 64))] + }); + let right_plan = vec_plan(Arc::clone(&r_schema), &on[0].1, p, move |part, rs| { + let key = key_for_partition(part, p); + vec![Ok(make_batch(rs, &[Some(key)], &[Some(20)], 16))] + }); + + let (join, _) = build_direct_partitioned_join( + left_plan, + right_plan, + on, + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + )?; + + let pool = Arc::new(PeakTrackingMemoryPool::new(16 * 1024 * 1024)); + let ctx = make_ctx(64 * 1024, 16, Some(Arc::clone(&pool)), false); + + let s0_orig = join.execute(0, Arc::clone(&ctx))?; + let s0_dup = join.execute(0, Arc::clone(&ctx))?; + let s1 = join.execute(1, Arc::clone(&ctx))?; + + let (r0_orig, r0_dup, r1) = tokio::time::timeout(TEST_TIMEOUT, async { + tokio::join!( + common::collect(s0_orig), + common::collect(s0_dup), + common::collect(s1) + ) + }) + .await + .expect("duplicate execute hung"); + + assert_eq!(r0_orig?.iter().map(|b| b.num_rows()).sum::(), 1); + assert_eq!(r0_dup?.iter().map(|b| b.num_rows()).sum::(), 1); + assert_eq!(r1?.iter().map(|b| b.num_rows()).sum::(), 1); + assert_eq!(pool.reserved(), 0); + assert_eq!( + metric_sum( + &join.metrics().unwrap(), + "adaptive_decision_reason_duplicate" + ), + 1 + ); + Ok(()) +} + +#[tokio::test] +async fn adaptive_replay_holds_full_shared_buffer_reservation_until_drained() -> Result<()> +{ + let schema = left_schema_with_meta(); + let big = make_batch( + &schema, + &[Some(1), Some(2), Some(3), Some(4)], + &[Some(10), Some(20), Some(30), Some(40)], + 64 * 1024, + ); + // Two zero-copy slices sharing the same backing buffer: charged [~256 KiB, 0]. + let slice0 = big.slice(0, 2); + let slice1 = big.slice(2, 2); + let tail_slice = big.slice(0, 1); + + let pool = Arc::new(PeakTrackingMemoryPool::new(16 * 1024 * 1024)); + let res = MemoryConsumer::new("HashJoinInput[0]") + .register(&(Arc::clone(&pool) as Arc)); + let mut buf = SideBuf::new(res); + let b0_bytes = buf.push_batch(slice0)?; + let b1_bytes = buf.push_batch(slice1)?; + assert!( + b0_bytes >= 200 * 1024, + "first slice should charge whole shared buffer" + ); + assert_eq!(b1_bytes, 0, "second slice shares the same backing buffer"); + let shared_alloc = pool.reserved(); + assert_eq!(shared_alloc, b0_bytes); + + let tail_gate = Arc::new(Notify::new()); + let tail = Box::pin(ScriptedStream::new( + schema, + vec![Step::Wait(Arc::clone(&tail_gate)), Step::Batch(tail_slice)], + )); + let mut replay = ReplayStream::new(buf, tail); + + // Keep the shared backing allocation reserved until both prefix slices are yielded. + let first = replay.next().await.unwrap()?; + assert_eq!(first.num_rows(), 2); + assert!( + pool.reserved() >= shared_alloc, + "intermediate reserved {} dropped below shared allocation {}", + pool.reserved(), + shared_alloc + ); + + // Release the prefix reservation as soon as the final slice is yielded. + let second = replay.next().await.unwrap()?; + assert_eq!(second.num_rows(), 2); + assert_eq!(pool.reserved(), 0); + + tail_gate.notify_one(); + let third = replay.next().await.unwrap()?; + assert_eq!(third.num_rows(), 1); + assert!(replay.next().await.is_none()); + assert_eq!(pool.reserved(), 0); + Ok(()) +} + +#[tokio::test] +async fn adaptive_replay_holds_reservation_until_unreserved_slice_drained() -> Result<()> +{ + let schema = left_schema_with_meta(); + let big = make_batch( + &schema, + &[Some(1), Some(2), Some(3), Some(4)], + &[Some(10), Some(20), Some(30), Some(40)], + 64 * 1024, + ); + // Two zero-copy slices sharing the same backing buffer: first reserved in + // `batches`, second trailing in `unreserved`. + let slice0 = big.slice(0, 2); + let slice1 = big.slice(2, 2); + let tail_slice = big.slice(0, 1); + + let pool = Arc::new(PeakTrackingMemoryPool::new(16 * 1024 * 1024)); + let res = MemoryConsumer::new("HashJoinInput[0]") + .register(&(Arc::clone(&pool) as Arc)); + let mut buf = SideBuf::new(res); + let b0_bytes = buf.push_batch(slice0)?; + buf.push_unreserved(slice1); + assert!( + b0_bytes >= 200 * 1024, + "first slice should charge whole shared buffer" + ); + let shared_alloc = pool.reserved(); + assert_eq!(shared_alloc, b0_bytes); + + let tail_gate = Arc::new(Notify::new()); + let tail = Box::pin(ScriptedStream::new( + schema, + vec![Step::Wait(Arc::clone(&tail_gate)), Step::Batch(tail_slice)], + )); + let mut replay = ReplayStream::new(buf, tail); + + // Reservation must stay live after yielding the reserved slice while the + // unreserved slice sharing its backing buffer is still buffered. + let first = replay.next().await.unwrap()?; + assert_eq!(first.num_rows(), 2); + assert!( + pool.reserved() > 0 && pool.reserved() >= shared_alloc, + "intermediate reserved {} dropped below shared allocation {}", + pool.reserved(), + shared_alloc + ); + + // Release the prefix reservation once the final unreserved slice is yielded. + let second = replay.next().await.unwrap()?; + assert_eq!(second.num_rows(), 2); + assert_eq!(pool.reserved(), 0); + + tail_gate.notify_one(); + let third = replay.next().await.unwrap()?; + assert_eq!(third.num_rows(), 1); + assert!(replay.next().await.is_none()); + assert_eq!(pool.reserved(), 0); + Ok(()) +} + +#[tokio::test] +async fn adaptive_swapped_empty_build_skips_planned_left_error() -> Result<()> { + let (l_schema, r_schema, on) = schemas_and_on()?; + + for join_type in [JoinType::Inner, JoinType::LeftSemi, JoinType::RightSemi] { + let left_plan = vec_plan(Arc::clone(&l_schema), &on[0].0, 1, |_, ls| { + vec![ + Ok(make_batch(ls, &[Some(1)], &[Some(10)], 8192)), + exec_err!("planned-left tail error"), + ] + }); + let right_plan = vec_plan(Arc::clone(&r_schema), &on[0].1, 1, |_, _| vec![]); + + let (join, _) = build_direct_partitioned_join( + left_plan, + right_plan, + on.clone(), + None, + join_type, + None, + NullEquality::NullEqualsNothing, + )?; + let pool = Arc::new(PeakTrackingMemoryPool::new(16 * 1024 * 1024)); + let out = execute_all_partitions( + &join, + 1, + make_ctx(1024, 16, Some(Arc::clone(&pool)), false), + ) + .await?; + assert!( + out.is_empty(), + "expected empty output for swapped empty {join_type:?}" + ); + assert_eq!(pool.reserved(), 0); + assert_eq!( + metric_sum(&join.metrics().unwrap(), "adaptive_build_swapped"), + 1 + ); + } + + Ok(()) +} + +/// Stream whose first poll returns `Poll::Pending` without waking `cx.waker()`, +/// letting the test reach the watch-construction window inside `poll_adaptive_sample`. +struct PendingOnceStream { + schema: SchemaRef, + pending_once: bool, + items: VecDeque>, +} + +impl RecordBatchStream for PendingOnceStream { + fn schema(&self) -> SchemaRef { + Arc::clone(&self.schema) + } +} + +impl Stream for PendingOnceStream { + type Item = Result; + + fn poll_next( + mut self: Pin<&mut Self>, + _cx: &mut Context<'_>, + ) -> Poll> { + if self.pending_once { + self.pending_once = false; + return Poll::Pending; + } + Poll::Ready(self.items.pop_front()) + } +} + +struct FlagWaker { + woken: AtomicBool, +} + +impl ArcWake for FlagWaker { + fn wake_by_ref(arc_self: &Arc) { + arc_self.woken.store(true, Ordering::SeqCst); + } +} + +#[tokio::test] +async fn adaptive_forced_lost_wakeup_reloops_and_builds() -> Result<()> { + let p = 2; + let (l_schema, r_schema, on) = schemas_and_on()?; + + let s1_slot: Arc>> = + Arc::new(Mutex::new(None)); + let transitioned_before_watch = Arc::new(AtomicBool::new(false)); + + let ls = Arc::clone(&l_schema); + let left_plan = Arc::new(CustomPlan::new( + Arc::clone(&l_schema), + Partitioning::Hash(vec![Arc::clone(&on[0].0)], p), + move |part, _| { + let key = key_for_partition(part, p); + if part == 0 { + Ok(Box::pin(PendingOnceStream { + schema: Arc::clone(&ls), + pending_once: true, + items: VecDeque::from(vec![Ok(make_batch( + &ls, + &[Some(key)], + &[Some(10)], + 16, + ))]), + })) + } else { + Ok(Box::pin(VecStream::new( + Arc::clone(&ls), + vec![Ok(make_batch(&ls, &[Some(key)], &[Some(20)], 8192))], + ))) + } + }, + )); + let right_plan = vec_plan(Arc::clone(&r_schema), &on[0].1, p, move |part, rs| { + let key = key_for_partition(part, p); + let pad = if part == 1 { 8192 } else { 16 }; + vec![Ok(make_batch(rs, &[Some(key)], &[Some(100)], pad))] + }); + + let (join, _) = build_direct_partitioned_join( + left_plan, + right_plan, + on, + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + )?; + + let ctx = make_ctx(1024, 16, None, false); + let mut s0 = join.execute(0, Arc::clone(&ctx))?; + let s1 = join.execute(1, Arc::clone(&ctx))?; + + let coord = join + .adaptive_coordinator_for_test() + .expect("adaptive coordinator should exist"); + *s1_slot.lock() = Some(s1); + + // Force p1's KeepLeft(RightCrossed) transition strictly after p0's last + // phase recheck and right before p0 constructs its `watch::Receiver::wait_for` + // future, proving that pinning `seen = phase` prevents a lost wakeup. + let s1_slot_hook = Arc::clone(&s1_slot); + let s1_early_batches: Arc>> = Arc::new(Mutex::new(Vec::new())); + let s1_early_hook = Arc::clone(&s1_early_batches); + let coord_hook = Arc::clone(&coord); + let transitioned_hook = Arc::clone(&transitioned_before_watch); + coord.set_before_watch_build_hook(Some(Box::new(move || { + let noop = futures::task::noop_waker(); + let mut noop_cx = Context::from_waker(&noop); + let mut guard = s1_slot_hook.lock(); + let s1 = guard.as_mut().expect("s1 must be stored before polling s0"); + // Since RightCrossed detaches the already-released accumulator, s1 may + // immediately produce its output batch without waiting for p0's bounds. + if let Poll::Ready(Some(batch)) = s1.poll_next_unpin(&mut noop_cx) { + s1_early_hook + .lock() + .push(batch.expect("s1 batch should succeed")); + } + assert_eq!( + coord_hook.phase(), + Phase::Decided(Decision::KeepLeft(Reason::RightCrossed)) + ); + transitioned_hook.store(true, Ordering::SeqCst); + }))); + + // Poll s0 with a strict waker loop that refuses to re-poll after Pending + // unless s0's own waker was actually fired. + let flag_waker = Arc::new(FlagWaker { + woken: AtomicBool::new(true), + }); + let waker = waker_ref(&flag_waker); + let mut cx = Context::from_waker(&waker); + let mut r0 = Vec::new(); + loop { + assert!( + flag_waker.woken.swap(false, Ordering::SeqCst), + "s0 returned Pending without firing a wakeup" + ); + match s0.poll_next_unpin(&mut cx) { + Poll::Ready(Some(Ok(batch))) => { + r0.push(batch); + flag_waker.woken.store(true, Ordering::SeqCst); + } + Poll::Ready(Some(Err(err))) => return Err(err), + Poll::Ready(None) => break, + Poll::Pending => { + assert!( + flag_waker.woken.load(Ordering::SeqCst), + "s0 parked Pending with no wakeup after p1 transitioned before watch construction" + ); + } + } + } + + assert!(transitioned_before_watch.load(Ordering::SeqCst)); + assert_eq!(r0.iter().map(|b| b.num_rows()).sum::(), 1); + + let s1 = s1_slot.lock().take().expect("s1 should still be present"); + let mut r1 = std::mem::take(&mut *s1_early_batches.lock()); + r1.extend( + tokio::time::timeout(TEST_TIMEOUT, common::collect(s1)) + .await + .expect("s1 hung after s0 completed")?, + ); + assert_eq!(r1.iter().map(|b| b.num_rows()).sum::(), 1); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn adaptive_filter_releaser_paused_before_discharge_hides_sample_right_from_peer() +-> Result<()> { + let p = 2; + let (l_schema, r_schema, on) = schemas_and_on()?; + + let left_plan = vec_plan(Arc::clone(&l_schema), &on[0].0, p, move |part, ls| { + let key = key_for_partition(part, p); + vec![Ok(make_batch(ls, &[Some(key)], &[Some(10)], 256 * 1024))] + }); + let right_plan = vec_plan(Arc::clone(&r_schema), &on[0].1, p, move |part, rs| { + let key = key_for_partition(part, p); + vec![Ok(make_batch(rs, &[Some(key)], &[Some(20)], 16))] + }); + + let (join, df) = build_direct_partitioned_join( + left_plan, + right_plan, + on, + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + )?; + + let ctx = make_ctx(200 * 1024, 16, None, false); + let s0 = join.execute(0, Arc::clone(&ctx))?; + let s1 = join.execute(1, Arc::clone(&ctx))?; + + let coord = join + .adaptive_coordinator_for_test() + .expect("adaptive coordinator should exist"); + + let (entered, release_guard) = install_filter_release_pause(&coord, GATE_TIMEOUT); + + // Run s0 and s1 on multi-thread tasks so the synchronous gate hook + // can pause the releaser without blocking the peer observation thread. + let t0 = SpawnedTask::spawn(common::collect(s0)); + let t1 = SpawnedTask::spawn(common::collect(s1)); + + let coord_obs = Arc::clone(&coord); + let df_obs = Arc::clone(&df); + SpawnedTask::spawn_blocking(move || { + let _release_guard = release_guard; + assert!( + entered.wait_timeout(GATE_TIMEOUT), + "releaser never reached pre-release hook within timeout" + ); + // Peers observe ReleasingFilter (not SampleRight) until all accumulator slots are discharged. + assert_eq!(coord_obs.phase(), Phase::ReleasingFilter); + assert!(!is_filter_complete(&df_obs)); + }) + .await + .unwrap(); + + let (r0, r1) = tokio::time::timeout(TEST_TIMEOUT, async { + let a = t0.await.unwrap()?; + let b = t1.await.unwrap()?; + Ok::<_, DataFusionError>((a, b)) + }) + .await + .expect("filter release test timed out")?; + + assert!(is_filter_complete(&df)); + assert!(is_literal_true(&df.current()?)); + assert_eq!(r0.iter().map(|b| b.num_rows()).sum::(), 1); + assert_eq!(r1.iter().map(|b| b.num_rows()).sum::(), 1); + assert_eq!( + metric_sum(&join.metrics().unwrap(), "adaptive_build_swapped"), + p + ); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn adaptive_dropping_peer_during_filter_release_detaches_without_overwriting() +-> Result<()> { + let p = 2; + let (l_schema, r_schema, on) = schemas_and_on()?; + + let left_plan = vec_plan(Arc::clone(&l_schema), &on[0].0, p, move |part, ls| { + let key = key_for_partition(part, p); + let pad = if part == 0 { 256 * 1024 } else { 16 }; + vec![Ok(make_batch(ls, &[Some(key)], &[Some(10)], pad))] + }); + let right_plan = vec_plan(Arc::clone(&r_schema), &on[0].1, p, move |part, rs| { + let key = key_for_partition(part, p); + vec![Ok(make_batch(rs, &[Some(key)], &[Some(20)], 16))] + }); + + let (join, df) = build_direct_partitioned_join( + left_plan, + right_plan, + on, + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + )?; + + let ctx = make_ctx(200 * 1024, 16, None, false); + let s0 = join.execute(0, Arc::clone(&ctx))?; + let mut s1 = join.execute(1, Arc::clone(&ctx))?; + + let coord = join + .adaptive_coordinator_for_test() + .expect("adaptive coordinator should exist"); + + // Advance p1 to left EOF and park it in SampleLeft before p0 crosses the cap. + let noop = futures::task::noop_waker(); + let mut noop_cx = Context::from_waker(&noop); + assert!(s1.poll_next_unpin(&mut noop_cx).is_pending()); + assert_eq!(coord.phase(), Phase::SampleLeft); + + let (entered, release_guard) = install_filter_release_pause(&coord, GATE_TIMEOUT); + + let t0 = SpawnedTask::spawn(common::collect(s0)); + + let coord_obs = Arc::clone(&coord); + let df_obs = Arc::clone(&df); + SpawnedTask::spawn_blocking(move || { + let _release_guard = release_guard; + assert!( + entered.wait_timeout(GATE_TIMEOUT), + "releaser never reached pre-release hook within timeout" + ); + assert_eq!(coord_obs.phase(), Phase::ReleasingFilter); + assert_eq!(coord_obs.accumulator_completed_partitions_for_test(), 0); + // Dropping p1 after filter release is reserved must detach without + // competing to finalize the accumulator, and must transition the + // coordinator to KeepLeft(Abandoned) without being overwritten by SampleRight. + drop(s1); + assert_eq!(coord_obs.accumulator_completed_partitions_for_test(), 0); + assert_eq!( + coord_obs.phase(), + Phase::Decided(Decision::KeepLeft(Reason::Abandoned)) + ); + assert!(!is_filter_complete(&df_obs)); + }) + .await + .unwrap(); + + let r0 = tokio::time::timeout(TEST_TIMEOUT, t0) + .await + .expect("releaser timed out after peer drop") + .unwrap()?; + + assert_eq!(coord.accumulator_completed_partitions_for_test(), p); + assert!(is_filter_complete(&df)); + assert!(is_literal_true(&df.current()?)); + assert_eq!( + coord.phase(), + Phase::Decided(Decision::KeepLeft(Reason::Abandoned)) + ); + assert_eq!(r0.iter().map(|b| b.num_rows()).sum::(), 1); + let metrics = join.metrics().unwrap(); + assert_eq!( + metric_sum(&metrics, "adaptive_decision_reason_abandoned"), + 1 + ); + assert_eq!(metric_sum(&metrics, "adaptive_build_swapped"), 0); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn adaptive_peer_parks_during_releasing_filter_without_consuming_tight_pool() +-> Result<()> { + let p = 2; + let peer_batches = 20; + let pool_limit = 640 * 1024; + let (l_schema, r_schema, on) = schemas_and_on()?; + + let p1_left_polls = Arc::new(AtomicUsize::new(0)); + let p1_left_polls_cl = Arc::clone(&p1_left_polls); + let ls = Arc::clone(&l_schema); + let left_plan = Arc::new(CustomPlan::new( + Arc::clone(&l_schema), + Partitioning::Hash(vec![Arc::clone(&on[0].0)], p), + move |part, _| { + let key = key_for_partition(part, p); + if part == 0 { + Ok(Box::pin(VecStream::new( + Arc::clone(&ls), + vec![Ok(make_batch(&ls, &[Some(key)], &[Some(10)], 256 * 1024))], + ))) + } else { + // 20 ready 128 KiB batches (~2.5 MiB total) >> 640 KiB tight memory pool. + let items = (0..peer_batches) + .map(|i| { + Ok(make_batch(&ls, &[Some(key)], &[Some(i as i32)], 128 * 1024)) + }) + .collect(); + Ok(Box::pin( + VecStream::new(Arc::clone(&ls), items) + .with_poll_counter(Arc::clone(&p1_left_polls_cl)), + )) + } + }, + )); + let right_plan = vec_plan(Arc::clone(&r_schema), &on[0].1, p, move |part, rs| { + let key = key_for_partition(part, p); + vec![Ok(make_batch(rs, &[Some(key)], &[Some(20)], 16))] + }); + + let (join, df) = build_direct_partitioned_join( + left_plan, + right_plan, + on, + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + )?; + + let pool = Arc::new(PeakTrackingMemoryPool::new(pool_limit)); + let ctx = make_ctx(200 * 1024, 16, Some(Arc::clone(&pool)), true); + let s0 = join.execute(0, Arc::clone(&ctx))?; + let mut s1 = join.execute(1, Arc::clone(&ctx))?; + + let coord = join + .adaptive_coordinator_for_test() + .expect("adaptive coordinator should exist"); + let (entered, release_guard) = install_filter_release_pause(&coord, GATE_TIMEOUT); + + // Let p0 trip the left limit and pause inside ReleasingFilter. + let t0 = SpawnedTask::spawn(common::collect(s0)); + SpawnedTask::spawn_blocking(move || { + assert!( + entered.wait_timeout(GATE_TIMEOUT), + "releaser never reached pre-release hook within timeout" + ); + }) + .await + .unwrap(); + + assert_eq!(coord.phase(), Phase::ReleasingFilter); + let reserved_before_peer = pool.reserved(); + + // Polling p1 during ReleasingFilter must park without polling or buffering left. + let flag_waker = Arc::new(FlagWaker { + woken: AtomicBool::new(false), + }); + let waker = waker_ref(&flag_waker); + let mut cx = Context::from_waker(&waker); + assert!(s1.poll_next_unpin(&mut cx).is_pending()); + assert!(!flag_waker.woken.load(Ordering::SeqCst)); + assert_eq!(p1_left_polls.load(Ordering::SeqCst), 0); + assert_eq!(pool.reserved(), reserved_before_peer); + + // Even when spawned and scheduled concurrently while release is paused, p1 stays parked. + let t1 = SpawnedTask::spawn(common::collect(s1)); + for _ in 0..16 { + tokio::task::yield_now().await; + } + assert_eq!(p1_left_polls.load(Ordering::SeqCst), 0); + assert_eq!(pool.reserved(), reserved_before_peer); + + // Resume filter release and verify SwapRight succeeds under the tight pool. + drop(release_guard); + let (r0, r1) = tokio::time::timeout(TEST_TIMEOUT, async { + let a = t0.await.unwrap()?; + let b = t1.await.unwrap()?; + Ok::<_, DataFusionError>((a, b)) + }) + .await + .expect("tight-pool ReleasingFilter test timed out")?; + + assert!(is_filter_complete(&df)); + assert!(is_literal_true(&df.current()?)); + assert_eq!(r0.iter().map(|b| b.num_rows()).sum::(), 1); + assert_eq!(r1.iter().map(|b| b.num_rows()).sum::(), peer_batches); + assert!(pool.peak_reserved() <= pool_limit); + assert_eq!(pool.reserved(), 0); + let metrics = join.metrics().unwrap(); + assert_eq!( + metric_sum(&metrics, "adaptive_decision_reason_swap_right"), + 1 + ); + assert_eq!(metric_sum(&metrics, "adaptive_build_swapped"), p); + Ok(()) +} + +/// Stream that pauses synchronously inside `poll_next` on a designated batch +/// index so a test can interleave another partition's phase transition while +/// this partition's child poll is actively in-flight. +struct BlockingGatedPollStream { + schema: SchemaRef, + items: VecDeque, + polls: Arc, + gate_on_poll: usize, + entered: Arc, + allow: Arc, +} + +impl RecordBatchStream for BlockingGatedPollStream { + fn schema(&self) -> SchemaRef { + Arc::clone(&self.schema) + } +} + +impl Stream for BlockingGatedPollStream { + type Item = Result; + + fn poll_next( + mut self: Pin<&mut Self>, + _cx: &mut Context<'_>, + ) -> Poll> { + let poll_idx = self.polls.fetch_add(1, Ordering::SeqCst); + if poll_idx == self.gate_on_poll { + self.entered.open(); + assert!( + self.allow.wait_timeout(GATE_TIMEOUT), + "in-flight poll gate timed out waiting to be released" + ); + } + Poll::Ready(self.items.pop_front().map(Ok)) + } +} + +fn collect_i32_column(batches: &[RecordBatch], name: &str) -> Vec { + let mut vals = Vec::new(); + for batch in batches { + let col = batch + .column_by_name(name) + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + for i in 0..col.len() { + vals.push(col.value(i)); + } + } + vals +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn adaptive_inflight_left_poll_during_releasing_filter_skips_reservation_and_replays_swap_right() +-> Result<()> { + let p = 2; + let pool_limit = 512 * 1024; + let inflight_pad = 512 * 1024; + let (l_schema, r_schema, on) = schemas_and_on()?; + + let p0_left_polls = Arc::new(AtomicUsize::new(0)); + let p0_poll_entered = TestGate::new(); + let p0_allow_return = TestGate::new(); + let p0_allow_guard = GateReleaseGuard(Arc::clone(&p0_allow_return)); + + let p0_left_polls_cl = Arc::clone(&p0_left_polls); + let p0_poll_entered_cl = Arc::clone(&p0_poll_entered); + let p0_allow_return_cl = Arc::clone(&p0_allow_return); + let ls = Arc::clone(&l_schema); + let left_plan = Arc::new(CustomPlan::new( + Arc::clone(&l_schema), + Partitioning::Hash(vec![Arc::clone(&on[0].0)], p), + move |part, _| { + let key = key_for_partition(part, p); + if part == 0 { + // Batch 0 is sampled & reserved during SampleLeft; batch 1 is + // returned from an in-flight poll after p1 transitions to + // ReleasingFilter (and is larger than the remaining pool); + // batch 2 remains in the left tail for SwapRight probe replay. + let items = VecDeque::from(vec![ + make_batch(&ls, &[Some(key)], &[Some(100)], 16), + make_batch(&ls, &[Some(key)], &[Some(101)], inflight_pad), + make_batch(&ls, &[Some(key)], &[Some(102)], 16), + ]); + Ok(Box::pin(BlockingGatedPollStream { + schema: Arc::clone(&ls), + items, + polls: Arc::clone(&p0_left_polls_cl), + gate_on_poll: 1, + entered: Arc::clone(&p0_poll_entered_cl), + allow: Arc::clone(&p0_allow_return_cl), + })) + } else { + Ok(Box::pin(VecStream::new( + Arc::clone(&ls), + vec![Ok(make_batch(&ls, &[Some(key)], &[Some(200)], 256 * 1024))], + ))) + } + }, + )); + let right_plan = vec_plan(Arc::clone(&r_schema), &on[0].1, p, move |part, rs| { + let key = key_for_partition(part, p); + vec![Ok(make_batch(rs, &[Some(key)], &[Some(300)], 16))] + }); + + let (join, df) = build_direct_partitioned_join( + left_plan, + right_plan, + on, + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + )?; + + let pool = Arc::new(PeakTrackingMemoryPool::new(pool_limit)); + let ctx = make_ctx(200 * 1024, 16, Some(Arc::clone(&pool)), true); + let s0 = join.execute(0, Arc::clone(&ctx))?; + let s1 = join.execute(1, Arc::clone(&ctx))?; + + let coord = join + .adaptive_coordinator_for_test() + .expect("adaptive coordinator should exist"); + let (filter_entered, filter_release_guard) = + install_filter_release_pause(&coord, GATE_TIMEOUT); + + // Start polling p0 while phase == SampleLeft. It will reserve batch 0 and + // pause inside its in-flight left.poll_next() for batch 1. + let s0_poll = SpawnedTask::spawn_blocking(move || { + let mut s0 = s0; + let flag_waker = Arc::new(FlagWaker { + woken: AtomicBool::new(false), + }); + let waker = waker_ref(&flag_waker); + let mut cx = Context::from_waker(&waker); + let poll = s0.poll_next_unpin(&mut cx); + (s0, poll, flag_waker) + }); + + SpawnedTask::spawn_blocking(move || { + assert!( + p0_poll_entered.wait_timeout(GATE_TIMEOUT), + "p0 never entered in-flight left poll within timeout" + ); + }) + .await + .unwrap(); + assert_eq!(coord.phase(), Phase::SampleLeft); + + // Now drive p1 to trip the left cap and pause inside ReleasingFilter. + let t1 = SpawnedTask::spawn(common::collect(s1)); + SpawnedTask::spawn_blocking(move || { + assert!( + filter_entered.wait_timeout(GATE_TIMEOUT), + "releaser never reached pre-release hook within timeout" + ); + }) + .await + .unwrap(); + + assert_eq!(coord.phase(), Phase::ReleasingFilter); + let reserved_before = pool.reserved(); + assert!( + pool_limit - reserved_before < inflight_pad, + "in-flight batch ({inflight_pad}) must exceed remaining pool ({})", + pool_limit - reserved_before + ); + + // Release p0's in-flight left batch while ReleasingFilter is active. + // p0 must NOT grow its reservation or fail with ResourcesExhausted; it must + // preserve the batch unreserved for replay and park in ReleasingFilter. + drop(p0_allow_guard); + let (s0, poll, flag_waker) = tokio::time::timeout(TEST_TIMEOUT, s0_poll) + .await + .expect("p0 in-flight poll timed out") + .unwrap(); + assert!( + poll.is_pending(), + "expected p0 to park in ReleasingFilter, got {poll:?}" + ); + assert!(!flag_waker.woken.load(Ordering::SeqCst)); + assert_eq!(pool.reserved(), reserved_before); + assert_eq!(p0_left_polls.load(Ordering::SeqCst), 2); + + // Resume filter release and verify SwapRight replays batch 0 (reserved), + // batch 1 (unreserved in-flight), and batch 2 (tail) in exact order. + let t0 = SpawnedTask::spawn(common::collect(s0)); + drop(filter_release_guard); + let (r0, r1) = tokio::time::timeout(TEST_TIMEOUT, async { + let a = t0.await.unwrap()?; + let b = t1.await.unwrap()?; + Ok::<_, DataFusionError>((a, b)) + }) + .await + .expect("in-flight ReleasingFilter SwapRight test timed out")?; + + assert!(is_filter_complete(&df)); + assert!(is_literal_true(&df.current()?)); + assert_eq!(collect_i32_column(&r0, "lv"), vec![100, 101, 102]); + assert_eq!(collect_i32_column(&r1, "lv"), vec![200]); + assert!(pool.peak_reserved() <= pool_limit); + assert_eq!(pool.reserved(), 0); + let metrics = join.metrics().unwrap(); + assert_eq!( + metric_sum(&metrics, "adaptive_decision_reason_swap_right"), + 1 + ); + assert_eq!(metric_sum(&metrics, "adaptive_build_swapped"), p); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn adaptive_inflight_left_poll_during_releasing_filter_replays_into_keep_left_build() +-> Result<()> { + let p = 2; + let pool_limit = 4 * 1024 * 1024; + let inflight_pad = 64 * 1024; + let (l_schema, r_schema, on) = schemas_and_on()?; + + let p0_left_polls = Arc::new(AtomicUsize::new(0)); + let p0_poll_entered = TestGate::new(); + let p0_allow_return = TestGate::new(); + let p0_allow_guard = GateReleaseGuard(Arc::clone(&p0_allow_return)); + + let p0_left_polls_cl = Arc::clone(&p0_left_polls); + let p0_poll_entered_cl = Arc::clone(&p0_poll_entered); + let p0_allow_return_cl = Arc::clone(&p0_allow_return); + let ls = Arc::clone(&l_schema); + let left_plan = Arc::new(CustomPlan::new( + Arc::clone(&l_schema), + Partitioning::Hash(vec![Arc::clone(&on[0].0)], p), + move |part, _| { + let key = key_for_partition(part, p); + if part == 0 { + let items = VecDeque::from(vec![ + make_batch(&ls, &[Some(key)], &[Some(100)], 16), + make_batch(&ls, &[Some(key)], &[Some(101)], inflight_pad), + make_batch(&ls, &[Some(key)], &[Some(102)], 16), + ]); + Ok(Box::pin(BlockingGatedPollStream { + schema: Arc::clone(&ls), + items, + polls: Arc::clone(&p0_left_polls_cl), + gate_on_poll: 1, + entered: Arc::clone(&p0_poll_entered_cl), + allow: Arc::clone(&p0_allow_return_cl), + })) + } else { + Ok(Box::pin(VecStream::new( + Arc::clone(&ls), + vec![Ok(make_batch(&ls, &[Some(key)], &[Some(200)], 256 * 1024))], + ))) + } + }, + )); + // Right also exceeds the 200 KiB cap so sampling decides KeepLeft(RightCrossed). + let right_plan = vec_plan(Arc::clone(&r_schema), &on[0].1, p, move |part, rs| { + let key = key_for_partition(part, p); + let pad = if part == 1 { 256 * 1024 } else { 16 }; + vec![Ok(make_batch(rs, &[Some(key)], &[Some(300)], pad))] + }); + + let (join, df) = build_direct_partitioned_join( + left_plan, + right_plan, + on, + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + )?; + + let pool = Arc::new(PeakTrackingMemoryPool::new(pool_limit)); + let ctx = make_ctx(200 * 1024, 16, Some(Arc::clone(&pool)), true); + let s0 = join.execute(0, Arc::clone(&ctx))?; + let s1 = join.execute(1, Arc::clone(&ctx))?; + + let coord = join + .adaptive_coordinator_for_test() + .expect("adaptive coordinator should exist"); + let (filter_entered, filter_release_guard) = + install_filter_release_pause(&coord, GATE_TIMEOUT); + + let s0_poll = SpawnedTask::spawn_blocking(move || { + let mut s0 = s0; + let flag_waker = Arc::new(FlagWaker { + woken: AtomicBool::new(false), + }); + let waker = waker_ref(&flag_waker); + let mut cx = Context::from_waker(&waker); + let poll = s0.poll_next_unpin(&mut cx); + (s0, poll, flag_waker) + }); + + SpawnedTask::spawn_blocking(move || { + assert!( + p0_poll_entered.wait_timeout(GATE_TIMEOUT), + "p0 never entered in-flight left poll within timeout" + ); + }) + .await + .unwrap(); + + let t1 = SpawnedTask::spawn(common::collect(s1)); + SpawnedTask::spawn_blocking(move || { + assert!( + filter_entered.wait_timeout(GATE_TIMEOUT), + "releaser never reached pre-release hook within timeout" + ); + }) + .await + .unwrap(); + + assert_eq!(coord.phase(), Phase::ReleasingFilter); + let reserved_before = pool.reserved(); + + drop(p0_allow_guard); + let (s0, poll, flag_waker) = tokio::time::timeout(TEST_TIMEOUT, s0_poll) + .await + .expect("p0 in-flight poll timed out") + .unwrap(); + assert!(poll.is_pending()); + assert!(!flag_waker.woken.load(Ordering::SeqCst)); + assert_eq!(pool.reserved(), reserved_before); + assert_eq!(p0_left_polls.load(Ordering::SeqCst), 2); + + let t0 = SpawnedTask::spawn(common::collect(s0)); + drop(filter_release_guard); + let (r0, r1) = tokio::time::timeout(TEST_TIMEOUT, async { + let a = t0.await.unwrap()?; + let b = t1.await.unwrap()?; + Ok::<_, DataFusionError>((a, b)) + }) + .await + .expect("in-flight ReleasingFilter KeepLeft test timed out")?; + + assert!(is_filter_complete(&df)); + assert!(is_literal_true(&df.current()?)); + let mut p0_vals = collect_i32_column(&r0, "lv"); + p0_vals.sort(); + assert_eq!(p0_vals, vec![100, 101, 102]); + assert_eq!(collect_i32_column(&r1, "lv"), vec![200]); + assert_eq!(pool.reserved(), 0); + let metrics = join.metrics().unwrap(); + assert_eq!( + metric_sum(&metrics, "adaptive_decision_reason_right_crossed"), + 1 + ); + assert_eq!(metric_sum(&metrics, "adaptive_build_swapped"), 0); + Ok(()) +} + +#[tokio::test] +async fn adaptive_gate_negatives_take_stock_path_with_zero_adaptive_metrics() -> Result<()> +{ + let (l_schema, r_schema, on) = schemas_and_on()?; + + let lb = vec![make_batch( + &l_schema, + &[Some(1), Some(2)], + &[Some(10), Some(20)], + 4096, + )]; + let rb = vec![make_batch( + &r_schema, + &[Some(1), Some(2)], + &[Some(30), Some(40)], + 16, + )]; + + let make_plain = |schema: SchemaRef, + batches: Vec, + partitioning: Partitioning, + boundedness: Boundedness, + ordered: bool| + -> Arc { + let sc_cl = Arc::clone(&schema); + let mut eq = EquivalenceProperties::new(Arc::clone(&schema)); + if ordered { + eq.add_ordering( + LexOrdering::new(vec![PhysicalSortExpr::new_default(Arc::new( + Column::new("k", 0), + ))]) + .unwrap(), + ); + } + Arc::new(CustomPlan::with_props( + PlanProperties::new(eq, partitioning, EmissionType::Incremental, boundedness), + move |_, _| { + Ok(Box::pin(VecStream::new( + Arc::clone(&sc_cl), + batches.iter().cloned().map(Ok).collect(), + ))) + }, + )) + }; + + let plain_join = |join_type: JoinType, + right_boundedness: Boundedness, + right_ordered: bool| + -> Result { + let (join, _) = build_direct_partitioned_join( + make_plain( + Arc::clone(&l_schema), + lb.clone(), + Partitioning::Hash(vec![Arc::clone(&on[0].0)], 1), + Boundedness::Bounded, + false, + ), + make_plain( + Arc::clone(&r_schema), + rb.clone(), + Partitioning::Hash(vec![Arc::clone(&on[0].1)], 1), + right_boundedness, + right_ordered, + ), + on.clone(), + None, + join_type, + None, + NullEquality::NullEqualsNothing, + )?; + Ok(join) + }; + + let default_ctx = || make_ctx(1024, 16, None, false); + + { + let df = new_dyn_filter(&on); + let join = wire_join( + make_plain( + Arc::clone(&l_schema), + lb.clone(), + Partitioning::UnknownPartitioning(1), + Boundedness::Bounded, + false, + ), + make_plain( + Arc::clone(&r_schema), + rb.clone(), + Partitioning::UnknownPartitioning(1), + Boundedness::Bounded, + false, + ), + &df, + on.clone(), + None, + JoinType::Inner, + None, + NullEquality::NullEqualsNothing, + PartitionMode::CollectLeft, + false, + )?; + let _ = execute_all_partitions(&join, 1, default_ctx()).await?; + assert_no_adaptive_metrics(&join.metrics().unwrap()); + } + + // Null-aware anti joins are ineligible even when non-null keys permit dynamic filtering. + { + let nn_left_schema = + Arc::new(Schema::new(vec![Field::new("k", DataType::Int32, false)])); + let nn_right_schema = + Arc::new(Schema::new(vec![Field::new("k", DataType::Int32, false)])); + let nn_on: JoinOn = + vec![(Arc::new(Column::new("k", 0)), Arc::new(Column::new("k", 0)))]; + let left_p = vec_plan(Arc::clone(&nn_left_schema), &nn_on[0].0, 1, |_, sc| { + vec![Ok(RecordBatch::try_new( + Arc::clone(sc), + vec![Arc::new(Int32Array::from(vec![1, 2]))], + ) + .unwrap())] + }); + let right_p = vec_plan(Arc::clone(&nn_right_schema), &nn_on[0].1, 1, |_, sc| { + vec![Ok(RecordBatch::try_new( + Arc::clone(sc), + vec![Arc::new(Int32Array::from(vec![1]))], + ) + .unwrap())] + }); + let df = new_dyn_filter(&nn_on); + let join = wire_join( + left_p, + right_p, + &df, + nn_on, + None, + JoinType::LeftAnti, + None, + NullEquality::NullEqualsNothing, + PartitionMode::Partitioned, + true, + )?; + let _ = execute_all_partitions(&join, 1, default_ctx()).await?; + assert_no_adaptive_metrics(&join.metrics().unwrap()); + } + + // Joins that preserve output ordering remain on the stock path. + { + let join = plain_join(JoinType::Inner, Boundedness::Bounded, true)?; + assert!(join.properties().output_ordering().is_some()); + let _ = execute_all_partitions(&join, 1, default_ctx()).await?; + assert_no_adaptive_metrics(&join.metrics().unwrap()); + } + + // Fetch-limited joins remain on the stock path. + { + let join = plain_join(JoinType::Inner, Boundedness::Bounded, false)?; + let join = join.builder().with_fetch(Some(1)).build()?; + let _ = execute_all_partitions(&join, 1, default_ctx()).await?; + assert_no_adaptive_metrics(&join.metrics().unwrap()); + } + + // An unbounded input is ineligible for adaptive sampling. + { + let join = plain_join( + JoinType::Inner, + Boundedness::Unbounded { + requires_infinite_memory: false, + }, + false, + )?; + let _ = execute_all_partitions(&join, 1, default_ctx()).await?; + assert_no_adaptive_metrics(&join.metrics().unwrap()); + } + + // Nonzero hash-join buffering disables adaptive sampling. + { + let join = plain_join(JoinType::Inner, Boundedness::Bounded, false)?; + let ctx = make_ctx_with(1024, 16, None, false, |opts| { + opts.execution.hash_join_buffering_capacity = 4096; + }); + let _ = execute_all_partitions(&join, 1, ctx).await?; + assert_no_adaptive_metrics(&join.metrics().unwrap()); + } + + // Adaptive sampling is disabled when join reordering is off. + { + let join = plain_join(JoinType::Inner, Boundedness::Bounded, false)?; + let ctx = make_ctx_with(1024, 16, None, false, |opts| { + opts.optimizer.join_reordering = false; + }); + let _ = execute_all_partitions(&join, 1, ctx).await?; + assert_no_adaptive_metrics(&join.metrics().unwrap()); + } + + // LeftMark, Right, and Full joins are ineligible for adaptive sampling. + for ineligible_type in [JoinType::LeftMark, JoinType::Right, JoinType::Full] { + let join = plain_join(ineligible_type, Boundedness::Bounded, false)?; + let _ = execute_all_partitions(&join, 1, default_ctx()).await?; + assert_no_adaptive_metrics(&join.metrics().unwrap()); + } + + // A zero threshold disables adaptive sampling. + { + let join = plain_join(JoinType::Inner, Boundedness::Bounded, false)?; + let _ = execute_all_partitions(&join, 1, make_ctx(0, 16, None, false)).await?; + assert_no_adaptive_metrics(&join.metrics().unwrap()); + } + + Ok(()) +} diff --git a/datafusion/physical-plan/src/joins/hash_join/exec.rs b/datafusion/physical-plan/src/joins/hash_join/exec.rs index 08d209003ad91..d2e0df4108a37 100644 --- a/datafusion/physical-plan/src/joins/hash_join/exec.rs +++ b/datafusion/physical-plan/src/joins/hash_join/exec.rs @@ -32,12 +32,17 @@ use crate::filter_pushdown::{ }; use crate::joins::Map; use crate::joins::array_map::ArrayMap; +use crate::joins::hash_join::adaptive::{ + AdaptiveBuildCoordinator, AdaptiveMetrics, AdaptiveState, BuildPrefix, Claim, + DeferredBuildArgs, Reason, SideBuf, Ticket, +}; use crate::joins::hash_join::inlist_builder::build_struct_inlist_values; use crate::joins::hash_join::shared_bounds::{ ColumnBounds, PartitionBounds, PushdownStrategy, SharedBuildAccumulator, }; use crate::joins::hash_join::stream::{ - BuildSide, BuildSideInitialState, HashJoinStream, HashJoinStreamState, + BuildReportHandle, BuildSide, BuildSideInitialState, HashJoinStream, + HashJoinStreamState, }; use crate::joins::join_hash_map::{JoinHashMapU32, JoinHashMapU64}; use crate::joins::utils::{ @@ -781,13 +786,18 @@ pub struct HashJoinExec { fetch: Option, } +struct BuildGeneration { + accumulator: Arc, + adaptive: Option>, +} + #[derive(Clone)] struct HashJoinExecDynamicFilter { /// Dynamic filter that we'll update with the results of the build side once that is done. filter: Arc, - /// Build accumulator to collect build-side information (hash maps and/or bounds) from each partition. - /// It is lazily initialized during execution to make sure we use the actual execution time partition counts. - build_accumulator: OnceLock>, + /// Shared per-generation build accumulator and optional adaptive coordinator. + /// Lazily initialized during execution to use the actual runtime partition counts. + generation: OnceLock>, } impl fmt::Debug for HashJoinExec { @@ -1000,13 +1010,33 @@ impl HashJoinExec { } self.dynamic_filter = Some(HashJoinExecDynamicFilter { filter, - // Initialize with an empty accumulator which will be lazily populated - // during execution. - build_accumulator: OnceLock::new(), + // The per-plan generation is initialized lazily when dynamic filter pushdown is enabled. + generation: OnceLock::new(), }); Ok(self) } + #[cfg(test)] + pub(super) fn adaptive_coordinator_for_test( + &self, + ) -> Option> { + self.dynamic_filter + .as_ref() + .and_then(|df| df.generation.get()) + .and_then(|g| g.adaptive.as_ref().map(Arc::clone)) + } + + #[cfg(test)] + pub(super) fn set_dynamic_filter_for_test( + &mut self, + filter: Arc, + ) { + self.dynamic_filter = Some(HashJoinExecDynamicFilter { + filter, + generation: OnceLock::new(), + }); + } + /// Calculate order preservation flags for this hash join. fn maintains_input_order(join_type: JoinType) -> Vec { vec![ @@ -1457,10 +1487,10 @@ impl ExecutionPlan for HashJoinExec { .with_category(MetricCategory::Rows) .counter(ARRAY_MAP_CREATED_COUNT_METRIC_NAME, partition); - // Initialize build_accumulator lazily with runtime partition counts (only if enabled) - // Use RepartitionExec's random state (seeds: 0,0,0,0) for partition routing + // Initialize generation lazily with runtime partition counts (only if enabled). + // Use RepartitionExec's random state (seeds: 0,0,0,0) for partition routing. let repartition_random_state = REPARTITION_RANDOM_STATE; - let build_accumulator = enable_dynamic_filter_pushdown + let generation = enable_dynamic_filter_pushdown .then(|| { self.dynamic_filter.as_ref().map(|df| { let filter = Arc::clone(&df.filter); @@ -1469,79 +1499,59 @@ impl ExecutionPlan for HashJoinExec { .iter() .map(|(_, right_expr)| Arc::clone(right_expr)) .collect::>(); - Some(Arc::clone(df.build_accumulator.get_or_init(|| { - Arc::new(SharedBuildAccumulator::new_from_partition_mode( - self.mode, - self.left.as_ref(), - self.right.as_ref(), - filter, - on_right, - repartition_random_state, - self.null_equality, - self.null_aware, - )) - }))) + Arc::clone(df.generation.get_or_init(|| { + let accumulator = + Arc::new(SharedBuildAccumulator::new_from_partition_mode( + self.mode, + self.left.as_ref(), + self.right.as_ref(), + filter, + on_right, + repartition_random_state, + self.null_equality, + self.null_aware, + )); + + let opts = context.session_config().options(); + let b_cap = + opts.execution.hash_join_adaptive_build_side_threshold_bytes; + let adaptive_eligible = b_cap > 0 + && opts.optimizer.join_reordering + && opts.execution.hash_join_buffering_capacity == 0 + && self.mode == PartitionMode::Partitioned + && !self.null_aware + && self.fetch.is_none() + && self.properties().output_ordering().is_none() + && !self.left.boundedness().is_unbounded() + && !self.right.boundedness().is_unbounded() + && matches!( + self.join_type, + JoinType::Inner + | JoinType::Left + | JoinType::LeftSemi + | JoinType::RightSemi + | JoinType::LeftAnti + ); + + let adaptive = adaptive_eligible.then(|| { + AdaptiveBuildCoordinator::new( + left_partitions, + b_cap, + context.session_config().batch_size(), + &accumulator, + &self.metrics, + ) + }); + + Arc::new(BuildGeneration { + accumulator, + adaptive, + }) + })) }) }) - .flatten() .flatten(); - let left_fut = match self.mode { - PartitionMode::CollectLeft => self.left_fut.try_once(|| { - let left_stream = self.left.execute(0, Arc::clone(&context))?; - - let reservation = - MemoryConsumer::new("HashJoinInput").register(context.memory_pool()); - - Ok(collect_left_input( - self.random_state.random_state().clone(), - left_stream, - on_left.clone(), - join_metrics.clone(), - reservation, - need_produce_result_in_final(self.join_type), - self.right().output_partitioning().partition_count(), - enable_dynamic_filter_pushdown, - Arc::clone(context.session_config().options()), - self.null_equality, - array_map_created_count, - )) - })?, - PartitionMode::Partitioned => { - let left_stream = self.left.execute(partition, Arc::clone(&context))?; - - let reservation = - MemoryConsumer::new(format!("HashJoinInput[{partition}]")) - .register(context.memory_pool()); - OnceFut::new(collect_left_input( - self.random_state.random_state().clone(), - left_stream, - on_left.clone(), - join_metrics.clone(), - reservation, - need_produce_result_in_final(self.join_type), - 1, - enable_dynamic_filter_pushdown, - Arc::clone(context.session_config().options()), - self.null_equality, - array_map_created_count, - )) - } - PartitionMode::Auto => { - return plan_err!( - "Invalid HashJoinExec, unsupported PartitionMode {:?} in execute()", - PartitionMode::Auto - ); - } - }; - - let batch_size = context.session_config().batch_size(); - - // we have the batches and the hash map with their keys. We can how create a stream - // over the right that uses this information to issue new batches. - let right_stream = self.right.execute(partition, context)?; - - // update column indices to reflect the projection let column_indices_after_projection = match self.projection.as_ref() { Some(projection) => projection .iter() @@ -1556,6 +1566,170 @@ impl ExecutionPlan for HashJoinExec { .map(|(_, right_expr)| Arc::clone(right_expr)) .collect::>(); + let batch_size = context.session_config().batch_size(); + + let claim = generation + .as_ref() + .and_then(|g| g.adaptive.as_ref()) + .map(|coord| coord.claim(partition)); + + let (right_stream, state, build_side, build_report, adaptive) = if let Some( + Claim::Adaptive(ticket), + ) = claim + { + // Guard child `execute()` calls so a synchronous error or unwind abandons + // the ticket first and then obeys the detach invariant if a sibling + // entered `ReleasingFilter`/`SampleRight` concurrently. + struct ExecuteGuard { + ticket: Option, + build_report: Option, + } + + impl ExecuteGuard { + fn into_parts(mut self) -> (Ticket, BuildReportHandle) { + ( + self.ticket.take().expect("ticket present"), + self.build_report.take().expect("build_report present"), + ) + } + } + + impl Drop for ExecuteGuard { + fn drop(&mut self) { + let Some(ticket) = self.ticket.take() else { + return; + }; + let _ = ticket.abandon(Reason::Abandoned); + if let Some(mut build_report) = self.build_report.take() { + if ticket.is_filter_released() { + build_report.detach_without_cancel(); + } else { + build_report.cancel_pending(); + } + } + } + } + + let build_accumulator = if ticket.is_filter_released() { + None + } else { + generation.as_ref().map(|g| Arc::clone(&g.accumulator)) + }; + let guard = ExecuteGuard { + ticket: Some(ticket), + build_report: Some(BuildReportHandle::new( + partition, + self.mode, + build_accumulator, + )), + }; + let left_stream = self.left.execute(partition, Arc::clone(&context))?; + let right_stream = self.right.execute(partition, Arc::clone(&context))?; + let (ticket, build_report) = guard.into_parts(); + + let left_res = MemoryConsumer::new(format!("HashJoinInput[{partition}]")) + .register(context.memory_pool()); + let right_res = MemoryConsumer::new(format!("HashJoinInput[{partition}]")) + .register(context.memory_pool()); + + let rx = ticket.subscribe(); + let adaptive_state = AdaptiveState { + h: ticket, + rx, + left: left_stream, + lb: SideBuf::new(left_res), + rb: SideBuf::new(right_res), + wait: None, + on_left, + build_args: DeferredBuildArgs { + config: Arc::clone(context.session_config().options()), + array_map_created_count, + }, + entered_sample_right: false, + metrics: AdaptiveMetrics::new(partition, &self.metrics), + }; + + ( + right_stream, + HashJoinStreamState::AdaptiveSample, + BuildSide::Deferred, + build_report, + Some(Box::new(adaptive_state)), + ) + } else { + let detached = matches!(claim, Some(Claim::StockDetached)); + let build_accumulator = if detached { + None + } else { + generation.as_ref().map(|g| Arc::clone(&g.accumulator)) + }; + let compute_dynamic_filters = enable_dynamic_filter_pushdown && !detached; + let build_report = + BuildReportHandle::new(partition, self.mode, build_accumulator); + + let left_fut = match self.mode { + PartitionMode::CollectLeft => self.left_fut.try_once(|| { + let left_stream = self.left.execute(0, Arc::clone(&context))?; + + let reservation = MemoryConsumer::new("HashJoinInput") + .register(context.memory_pool()); + + Ok(collect_left_input( + self.random_state.random_state().clone(), + BuildPrefix::empty(reservation), + left_stream, + on_left.clone(), + join_metrics.clone(), + need_produce_result_in_final(self.join_type), + self.right().output_partitioning().partition_count(), + compute_dynamic_filters, + Arc::clone(context.session_config().options()), + self.null_equality, + array_map_created_count, + )) + })?, + PartitionMode::Partitioned => { + let left_stream = + self.left.execute(partition, Arc::clone(&context))?; + + let reservation = + MemoryConsumer::new(format!("HashJoinInput[{partition}]")) + .register(context.memory_pool()); + OnceFut::new(collect_left_input( + self.random_state.random_state().clone(), + BuildPrefix::empty(reservation), + left_stream, + on_left.clone(), + join_metrics.clone(), + need_produce_result_in_final(self.join_type), + 1, + compute_dynamic_filters, + Arc::clone(context.session_config().options()), + self.null_equality, + array_map_created_count, + )) + } + PartitionMode::Auto => { + return plan_err!( + "Invalid HashJoinExec, unsupported PartitionMode {:?} in execute()", + PartitionMode::Auto + ); + } + }; + + // we have the batches and the hash map with their keys. We can how create a stream + // over the right that uses this information to issue new batches. + let right_stream = self.right.execute(partition, context)?; + + ( + right_stream, + HashJoinStreamState::WaitBuildSide, + BuildSide::Initial(BuildSideInitialState { left_fut }), + build_report, + None, + ) + }; + Ok(Box::pin(HashJoinStream::new( partition, self.schema(), @@ -1567,15 +1741,16 @@ impl ExecutionPlan for HashJoinExec { join_metrics, column_indices_after_projection, self.null_equality, - HashJoinStreamState::WaitBuildSide, - BuildSide::Initial(BuildSideInitialState { left_fut }), + state, + build_side, batch_size, vec![], self.right.output_ordering().is_some(), - build_accumulator, + build_report, self.mode, self.null_aware, self.fetch, + adaptive, ))) } @@ -1810,7 +1985,7 @@ impl ExecutionPlan for HashJoinExec { .builder() .with_dynamic_filter(Some(HashJoinExecDynamicFilter { filter: dynamic_filter, - build_accumulator: OnceLock::new(), + generation: OnceLock::new(), })) .build_exec()?; result = result.with_updated_node(new_node); @@ -2159,28 +2334,51 @@ struct BuildSideState { } impl BuildSideState { - /// Create a new BuildSideState with optional accumulators for bounds computation - fn try_new( + /// Create a new BuildSideState seeded with a pre-sampled [`BuildPrefix`]. + fn try_new_with_prefix( metrics: BuildProbeJoinMetrics, - reservation: MemoryReservation, + prefix: BuildPrefix, on_left: Vec>, schema: &SchemaRef, - should_compute_dynamic_filters: bool, + should_compute_bounds: bool, ) -> Result { + let mut bounds_accumulators = should_compute_bounds + .then(|| { + on_left + .into_iter() + .map(|expr| CollectLeftAccumulator::try_new(expr, schema)) + .collect::>>() + }) + .transpose()?; + + let mut num_rows = 0usize; + for batch in &prefix.batches { + if let Some(ref mut accumulators) = bounds_accumulators { + for accumulator in accumulators { + accumulator.update_batch(batch)?; + } + } + num_rows += batch.num_rows(); + } + + let prefix_mem = prefix.reservation.size(); + if prefix_mem > 0 { + metrics.build_mem_used.add(prefix_mem); + } + if !prefix.batches.is_empty() { + metrics.build_input_batches.add(prefix.batches.len()); + } + if num_rows > 0 { + metrics.build_input_rows.add(num_rows); + } + Ok(Self { - batches: Vec::new(), - num_rows: 0, + batches: prefix.batches, + num_rows, metrics, - reservation, - memory_counter: RecordBatchMemoryCounter::new(), - bounds_accumulators: should_compute_dynamic_filters - .then(|| { - on_left - .into_iter() - .map(|expr| CollectLeftAccumulator::try_new(expr, schema)) - .collect::>>() - }) - .transpose()?, + reservation: prefix.reservation, + memory_counter: prefix.counter, + bounds_accumulators, }) } } @@ -2227,12 +2425,12 @@ fn should_collect_min_max_for_perfect_hash( /// `JoinLeftData` containing the hash map, consolidated batch, join key values, /// visited indices bitmap, and computed bounds (if requested). #[expect(clippy::too_many_arguments)] -async fn collect_left_input( +pub(super) async fn collect_left_input( random_state: RandomState, + prefix: BuildPrefix, left_stream: SendableRecordBatchStream, on_left: Vec, metrics: BuildProbeJoinMetrics, - reservation: MemoryReservation, with_visited_indices_bitmap: bool, probe_threads_count: usize, should_compute_dynamic_filters: bool, @@ -2245,9 +2443,9 @@ async fn collect_left_input( let should_collect_min_max_for_phj = should_collect_min_max_for_perfect_hash(&on_left, &schema)?; - let initial = BuildSideState::try_new( + let initial = BuildSideState::try_new_with_prefix( metrics, - reservation, + prefix, on_left.clone(), &schema, should_compute_dynamic_filters || should_collect_min_max_for_phj, @@ -2807,7 +3005,7 @@ mod tests { )?; join.dynamic_filter = Some(HashJoinExecDynamicFilter { filter: Arc::clone(&dynamic_filter), - build_accumulator: OnceLock::new(), + generation: OnceLock::new(), }); Ok((join, dynamic_filter)) diff --git a/datafusion/physical-plan/src/joins/hash_join/mod.rs b/datafusion/physical-plan/src/joins/hash_join/mod.rs index b915802ea4015..6ad3089ba15a2 100644 --- a/datafusion/physical-plan/src/joins/hash_join/mod.rs +++ b/datafusion/physical-plan/src/joins/hash_join/mod.rs @@ -20,6 +20,9 @@ pub use exec::{HashJoinExec, HashJoinExecBuilder}; pub use partitioned_hash_eval::{HashExpr, HashTableLookupExpr, SeededRandomState}; +mod adaptive; +#[cfg(test)] +mod adaptive_tests; mod exec; mod inlist_builder; mod partitioned_hash_eval; diff --git a/datafusion/physical-plan/src/joins/hash_join/shared_bounds.rs b/datafusion/physical-plan/src/joins/hash_join/shared_bounds.rs index 94ec4565a4cef..d484bedfb7216 100644 --- a/datafusion/physical-plan/src/joins/hash_join/shared_bounds.rs +++ b/datafusion/physical-plan/src/joins/hash_join/shared_bounds.rs @@ -48,7 +48,7 @@ use datafusion_physical_expr::{ PhysicalExpr, PhysicalExprRef, RangePartitioning, ScalarFunctionExpr, }; -use parking_lot::Mutex; +use parking_lot::{Condvar, Mutex}; use tokio::sync::Notify; /// Represents the minimum and maximum values for a specific column. @@ -253,6 +253,10 @@ pub(crate) struct SharedBuildAccumulator { /// result, then broadcasts), so late subscribers simply re-check the /// state under the mutex and return immediately. completion_notify: Notify, + /// Wakes synchronous waiters (e.g. the adaptive filter releaser entering + /// `SampleRight` waiting for a competing finalizer) once + /// [`AccumulatorState::completion`] transitions to [`CompletionState::Ready`]. + completion_condvar: Condvar, /// Dynamic filter for pushdown to probe side dynamic_filter: Arc, /// Right side join expressions needed for creating filter expressions @@ -270,6 +274,10 @@ pub(crate) struct SharedBuildAccumulator { /// Null-aware anti join (`NOT IN`). A probe-side NULL must reach the join so its /// three-valued logic can collapse the result, so the pushed filter keeps NULL rows. null_aware: bool, + #[cfg(test)] + before_finish_hook: Mutex>>, + #[cfg(test)] + before_wait_finalizing_hook: Mutex>>, } /// Strategy for filter pushdown (decided at collection time) @@ -431,6 +439,7 @@ impl SharedBuildAccumulator { completion: CompletionState::Pending, }), completion_notify: Notify::new(), + completion_condvar: Condvar::new(), dynamic_filter, on_right, repartition_random_state, @@ -438,6 +447,10 @@ impl SharedBuildAccumulator { probe_range_partitioning, null_equality, null_aware, + #[cfg(test)] + before_finish_hook: Mutex::new(None), + #[cfg(test)] + before_wait_finalizing_hook: Mutex::new(None), } } @@ -479,6 +492,73 @@ impl SharedBuildAccumulator { } } + /// Cancels all remaining pending partitions in `Partitioned` mode and waits + /// until finalization (including `dynamic_filter.mark_complete()`) has + /// transitioned to [`CompletionState::Ready`]. + /// + /// Used when adaptive sampling enters `SampleRight` so `SampleRight` is + /// never published while a competing finalizer is still between claiming + /// `Finalizing` and calling `mark_complete()`. + pub(crate) fn cancel_all_partitions_and_wait(&self) { + let finalize_input = { + let mut guard = self.inner.lock(); + match &mut guard.data { + AccumulatedBuildData::Partitioned { + partitions, + completed_partitions, + } => { + for slot in partitions.iter_mut() { + if matches!(slot, PartitionStatus::Pending) { + *slot = PartitionStatus::CanceledUnknown; + *completed_partitions += 1; + } + } + } + AccumulatedBuildData::CollectLeft { .. } => return, + } + self.take_finalize_input_if_ready(&mut guard) + }; + + if let Some(finalize_input) = finalize_input { + self.finish(finalize_input); + return; + } + + let mut guard = self.inner.lock(); + while !matches!(guard.completion, CompletionState::Ready(_)) { + #[cfg(test)] + if matches!(guard.completion, CompletionState::Finalizing) { + let hook = self.before_wait_finalizing_hook.lock().clone(); + if let Some(hook) = hook { + hook(); + } + } + self.completion_condvar.wait(&mut guard); + } + } + + #[cfg(test)] + pub(super) fn set_before_finish_hook( + &self, + hook: Option>, + ) { + *self.before_finish_hook.lock() = hook; + } + + #[cfg(test)] + pub(super) fn set_before_wait_finalizing_hook( + &self, + hook: Option>, + ) { + *self.before_wait_finalizing_hook.lock() = hook; + } + + #[cfg(test)] + pub(super) fn is_filter_complete_for_test(&self) -> bool { + use futures::FutureExt; + self.dynamic_filter.wait_complete().now_or_never().is_some() + } + fn store_build_data( &self, guard: &mut AccumulatorState, @@ -545,9 +625,10 @@ impl SharedBuildAccumulator { partitions, completed_partitions, } = &mut guard.data - && matches!(partitions[partition_id], PartitionStatus::Pending) + && let Some(slot) = partitions.get_mut(partition_id) + && matches!(slot, PartitionStatus::Pending) { - partitions[partition_id] = PartitionStatus::CanceledUnknown; + *slot = PartitionStatus::CanceledUnknown; *completed_partitions += 1; } } @@ -582,12 +663,21 @@ impl SharedBuildAccumulator { } fn finish(&self, finalize_input: FinalizeInput) { + #[cfg(test)] + { + let hook = self.before_finish_hook.lock().clone(); + if let Some(hook) = hook { + hook(); + } + } + let result = self.build_filter(finalize_input).map_err(Arc::new); self.dynamic_filter.mark_complete(); let mut guard = self.inner.lock(); guard.completion = CompletionState::Ready(result); drop(guard); + self.completion_condvar.notify_all(); self.completion_notify.notify_waiters(); } @@ -693,12 +783,19 @@ impl SharedBuildAccumulator { } } - let filter_expr = if has_canceled_unknown + if has_canceled_unknown && real_partition_ids.is_empty() && empty_partition_ids.is_empty() { - lit(true) - } else if !has_canceled_unknown && real_partition_ids.is_empty() { + // Every partition was canceled; `lit(true)` already admits NULL keys, + // so bypass `preserve_probe_nulls`. + self.dynamic_filter.update(lit(true))?; + return Ok(()); + } + + let filter_expr = if !has_canceled_unknown + && real_partition_ids.is_empty() + { lit(false) } else if !has_canceled_unknown && real_partition_ids.len() == 1 @@ -869,6 +966,7 @@ pub(super) fn make_partitioned_accumulator_for_test( completion: CompletionState::Pending, }), completion_notify: Notify::new(), + completion_condvar: Condvar::new(), dynamic_filter, on_right: vec![], repartition_random_state: SeededRandomState::with_seed(1), @@ -876,6 +974,8 @@ pub(super) fn make_partitioned_accumulator_for_test( probe_range_partitioning: None, null_equality: NullEquality::NullEqualsNothing, null_aware: false, + before_finish_hook: Mutex::new(None), + before_wait_finalizing_hook: Mutex::new(None), } } @@ -934,6 +1034,7 @@ mod tests { completion: CompletionState::Pending, }), completion_notify: Notify::new(), + completion_condvar: Condvar::new(), dynamic_filter, on_right, repartition_random_state: SeededRandomState::with_seed(1), @@ -941,6 +1042,8 @@ mod tests { probe_range_partitioning: None, null_equality: NullEquality::NullEqualsNothing, null_aware: false, + before_finish_hook: Mutex::new(None), + before_wait_finalizing_hook: Mutex::new(None), } } @@ -1413,6 +1516,7 @@ mod tests { completion: CompletionState::Pending, }), completion_notify: Notify::new(), + completion_condvar: Condvar::new(), dynamic_filter: Arc::new(DynamicFilterPhysicalExpr::new(vec![], lit(true))), on_right, repartition_random_state: SeededRandomState::with_seed(1), @@ -1420,6 +1524,8 @@ mod tests { probe_range_partitioning: None, null_equality, null_aware, + before_finish_hook: Mutex::new(None), + before_wait_finalizing_hook: Mutex::new(None), } } @@ -1513,4 +1619,20 @@ mod tests { let widened = acc.preserve_probe_nulls(lit(true), false).unwrap(); assert_eq!(format!("{widened}").matches("IS NULL").count(), 1); } + + #[test] + fn partitioned_all_canceled_publishes_literal_true_without_null_wrapper() { + let probe_schema = + Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, true)])); + let on_right: Vec = vec![Arc::new(Column::new("a", 0))]; + let acc = null_equal_accumulator(probe_schema, on_right); + + acc.build_filter(FinalizeInput::Partitioned(vec![ + PartitionStatus::CanceledUnknown, + ])) + .unwrap(); + + let expr = current_expr(&acc); + assert_literal_bool(&expr, true); + } } diff --git a/datafusion/physical-plan/src/joins/hash_join/stream.rs b/datafusion/physical-plan/src/joins/hash_join/stream.rs index 686939537e73e..08229f2c97679 100644 --- a/datafusion/physical-plan/src/joins/hash_join/stream.rs +++ b/datafusion/physical-plan/src/joins/hash_join/stream.rs @@ -28,7 +28,10 @@ use crate::coalesce::{LimitedBatchCoalescer, PushBatchStatus}; use crate::joins::Map; use crate::joins::MapOffset; use crate::joins::PartitionMode; -use crate::joins::hash_join::exec::JoinLeftData; +use crate::joins::hash_join::adaptive::{ + AdaptiveState, Decision, Phase, Reason, ReplayStream, +}; +use crate::joins::hash_join::exec::{JoinLeftData, collect_left_input}; use crate::joins::hash_join::shared_bounds::{ PartitionBounds, PartitionBuildData, SharedBuildAccumulator, }; @@ -52,7 +55,8 @@ use arrow::buffer::NullBuffer; use arrow::datatypes::{Schema, SchemaRef}; use arrow::record_batch::RecordBatch; use datafusion_common::{ - JoinSide, JoinType, NullEquality, Result, internal_datafusion_err, internal_err, + DataFusionError, JoinSide, JoinType, NullEquality, Result, internal_datafusion_err, + internal_err, }; use datafusion_physical_expr::PhysicalExprRef; @@ -62,6 +66,8 @@ use futures::{Stream, StreamExt, ready}; /// Represents build-side of hash join. pub(super) enum BuildSide { + /// Build side deferred until adaptive sampling decides which input to build + Deferred, /// Indicates that build-side not collected yet Initial(BuildSideInitialState), /// Indicates that build-side data has been collected @@ -125,6 +131,8 @@ impl BuildSide { /// ``` #[derive(Debug, Clone)] pub(super) enum HashJoinStreamState { + /// Sampling inputs to choose the build side adaptively before building + AdaptiveSample, /// Initial state for HashJoinStream indicating that build-side data not collected yet WaitBuildSide, /// Waiting for bounds to be reported by all partitions @@ -193,7 +201,7 @@ enum BuildReportState { } /// Owns the stream-side lifecycle for one partition's build-data report. -struct BuildReportHandle { +pub(super) struct BuildReportHandle { partition: usize, mode: PartitionMode, build_accumulator: Option>, @@ -202,7 +210,7 @@ struct BuildReportHandle { } impl BuildReportHandle { - fn new( + pub(super) fn new( partition: usize, mode: PartitionMode, build_accumulator: Option>, @@ -247,7 +255,7 @@ impl BuildReportHandle { Poll::Ready(Ok(())) } - fn cancel_pending(&mut self) { + pub(super) fn cancel_pending(&mut self) { if matches!( self.state, BuildReportState::Delivered @@ -271,6 +279,16 @@ impl BuildReportHandle { self.state = BuildReportState::Finalized; } + /// Detaches the accumulator without canceling this partition's slot. + /// + /// Used once adaptive sampling has released the dynamic filter on entering + /// `SampleRight`, because the partition that triggered the release owns + /// discharging and finalizing all accumulator slots. + pub(super) fn detach_without_cancel(&mut self) { + self.finalize(); + self.build_accumulator = None; + } + #[cfg(test)] fn state(&self) -> &BuildReportState { &self.state @@ -336,6 +354,8 @@ pub(super) struct HashJoinStream { output_buffer: LimitedBatchCoalescer, /// Whether this is a null-aware anti join null_aware: bool, + /// Stream-local state for adaptive build-side sampling (present only while in `AdaptiveSample`) + adaptive: Option>, } impl RecordBatchStream for HashJoinStream { @@ -344,6 +364,16 @@ impl RecordBatchStream for HashJoinStream { } } +impl Drop for HashJoinStream { + fn drop(&mut self) { + if self.abandon_adaptive() { + // The partition that entered ReleasingFilter/SampleRight owns + // discharging and finalizing all accumulator slots; detach without competing. + self.build_report.detach_without_cancel(); + } + } +} + /// Executes lookups by hash against JoinHashMap and resolves potential /// hash collisions. /// Returns build/probe indices satisfying the equality condition, along with @@ -465,6 +495,10 @@ fn count_distinct_sorted_indices(indices: &UInt32Array) -> usize { count } +/// Maximum consecutive ready batches processed in `poll_adaptive_sample` before +/// yielding cooperatively back to the executor. +const MAX_ADAPTIVE_READY_BATCHES_PER_POLL: usize = 32; + impl HashJoinStream { #[expect(clippy::too_many_arguments)] pub(super) fn new( @@ -483,10 +517,11 @@ impl HashJoinStream { batch_size: usize, hashes_buffer: Vec, right_side_ordered: bool, - build_accumulator: Option>, + build_report: BuildReportHandle, mode: PartitionMode, null_aware: bool, fetch: Option, + adaptive: Option>, ) -> Self { // Create output buffer with coalescing and optional fetch limit. let output_buffer = @@ -510,11 +545,285 @@ impl HashJoinStream { probe_indices_buffer: Vec::with_capacity(batch_size), build_indices_buffer: Vec::with_capacity(batch_size), right_side_ordered, - build_report: BuildReportHandle::new(partition, mode, build_accumulator), + build_report, mode, output_buffer, null_aware, + adaptive, + } + } + + /// Replaces `self.right` with a typed empty stream, immediately releasing + /// any buffered replay reservations or child stream resources. + fn release_right_stream(&mut self) { + let right_schema = self.right.schema(); + self.right = Box::pin(EmptyRecordBatchStream::new(right_schema)); + } + + /// Updates `self.state`, immediately releasing `self.right` whenever the + /// stream enters [`HashJoinStreamState::Completed`]. + fn set_state(&mut self, state: HashJoinStreamState) { + if matches!(state, HashJoinStreamState::Completed) { + self.release_right_stream(); + } + self.state = state; + } + + /// Abandons any active adaptive sampling state and returns whether the + /// dynamic filter had already been released for this generation. + fn abandon_adaptive(&mut self) -> bool { + self.adaptive.take().is_some_and(|adaptive| { + let _ = adaptive.h.abandon(Reason::Abandoned); + adaptive.h.is_filter_released() + }) + } + + /// Terminal error cleanup for sampling, build, and bounds-wait failures. + /// + /// Releases adaptive state, pending build-report slots, and `self.right` + /// immediately so sibling partitions never strand even if the caller retains + /// this errored stream without dropping it. + fn fail_terminal( + &mut self, + err: DataFusionError, + ) -> Poll>> { + if self.abandon_adaptive() { + self.build_report.detach_without_cancel(); + } else { + self.build_report.cancel_pending(); } + self.set_state(HashJoinStreamState::Completed); + Poll::Ready(Some(Err(err))) + } + + /// Polls inputs during the adaptive build-side sampling phase until the + /// coordinator reaches a terminal [`Decision`]. + fn poll_adaptive_sample( + &mut self, + cx: &mut std::task::Context<'_>, + ) -> Poll>>> { + let sample_poll_time = self + .adaptive + .as_ref() + .ok_or_else(|| { + internal_datafusion_err!("Expected adaptive state in AdaptiveSample") + })? + .metrics + .sample_poll_time + .clone(); + let _timer = sample_poll_time.timer(); + + let mut ready_batches = 0usize; + + loop { + let adaptive = self.adaptive.as_deref_mut().ok_or_else(|| { + internal_datafusion_err!("Expected adaptive state in AdaptiveSample") + })?; + let phase = adaptive.h.phase(); + + if let Phase::Decided(decision) = phase { + self.apply_adaptive_decision(decision)?; + return Poll::Ready(Ok(StatefulStreamResult::Continue)); + } + + match phase { + Phase::SampleLeft if !adaptive.lb.eof => { + match adaptive.left.poll_next_unpin(cx) { + Poll::Ready(Some(Ok(batch))) => { + if let Some(bytes) = adaptive.h.admit_batch( + JoinSide::Left, + &mut adaptive.lb, + batch, + )? { + adaptive.metrics.sampled_left_bytes.add(bytes); + ready_batches += 1; + if ready_batches >= MAX_ADAPTIVE_READY_BATCHES_PER_POLL { + cx.waker().wake_by_ref(); + return Poll::Pending; + } + } + continue; + } + Poll::Ready(Some(Err(err))) => return Poll::Ready(Err(err)), + Poll::Ready(None) => { + let left_schema = adaptive.left.schema(); + adaptive.left = + Box::pin(EmptyRecordBatchStream::new(left_schema)); + adaptive.lb.eof = true; + adaptive.h.on_eof(JoinSide::Left); + continue; + } + Poll::Pending => {} + } + } + Phase::SampleRight if !adaptive.rb.eof => { + if !adaptive.entered_sample_right { + adaptive.entered_sample_right = true; + adaptive.metrics.right_sampled.add(1); + } + match self.right.poll_next_unpin(cx) { + Poll::Ready(Some(Ok(batch))) => { + if let Some(bytes) = adaptive.h.admit_batch( + JoinSide::Right, + &mut adaptive.rb, + batch, + )? { + adaptive.metrics.sampled_right_bytes.add(bytes); + ready_batches += 1; + if ready_batches >= MAX_ADAPTIVE_READY_BATCHES_PER_POLL { + cx.waker().wake_by_ref(); + return Poll::Pending; + } + } + continue; + } + Poll::Ready(Some(Err(err))) => { + adaptive.rb.err = Some(err); + let right_schema = self.right.schema(); + self.right = + Box::pin(EmptyRecordBatchStream::new(right_schema)); + adaptive.rb.eof = true; + adaptive.h.abandon(Reason::RightError); + continue; + } + Poll::Ready(None) => { + let right_schema = self.right.schema(); + self.right = + Box::pin(EmptyRecordBatchStream::new(right_schema)); + adaptive.rb.eof = true; + adaptive.h.on_eof(JoinSide::Right); + continue; + } + Poll::Pending => {} + } + } + Phase::SampleLeft | Phase::ReleasingFilter | Phase::SampleRight => {} + Phase::Decided(_) => unreachable!("handled above"), + } + + // `seen` is the loop-top `phase` (`SampleLeft`, `ReleasingFilter`, or + // `SampleRight`, never `Decided`). Do not re-read `h.phase()` to build + // the watch predicate; if the phase has already moved, re-enter the + // loop immediately. + let seen = phase; + if adaptive.h.phase() != seen { + adaptive.wait = None; + continue; + } + + let need_new_wait = match &adaptive.wait { + Some((tagged, _)) => *tagged != seen, + None => true, + }; + if need_new_wait { + #[cfg(test)] + adaptive.h.run_before_watch_build_hook(); + + let mut rx = adaptive.rx.clone(); + adaptive.wait = Some(( + seen, + Box::pin(async move { + let _ = rx.wait_for(|ph| *ph != seen).await; + }), + )); + } + + if let Some((_, fut)) = adaptive.wait.as_mut() + && fut.as_mut().poll(cx).is_ready() + { + adaptive.wait = None; + continue; + } + + return Poll::Pending; + } + } + + /// Commits the adaptive sampling decision and transitions to `WaitBuildSide`. + fn apply_adaptive_decision(&mut self, decision: Decision) -> Result<()> { + let adaptive = self + .adaptive + .take() + .ok_or_else(|| internal_datafusion_err!("Missing adaptive state"))?; + let filter_released = adaptive.h.is_filter_released(); + let AdaptiveState { + left, + lb, + rb, + on_left, + build_args, + metrics, + .. + } = *adaptive; + + match decision { + Decision::KeepLeft(_) => { + if filter_released { + self.build_report.detach_without_cancel(); + } + let (prefix, left_stream) = lb.into_prefix_and_tail(left); + let left_fut = OnceFut::new(collect_left_input( + self.random_state.clone(), + prefix, + left_stream, + on_left, + self.join_metrics.clone(), + need_produce_result_in_final(self.join_type), + 1, + self.build_report.has_accumulator(), + build_args.config, + self.null_equality, + build_args.array_map_created_count, + )); + self.build_side = BuildSide::Initial(BuildSideInitialState { left_fut }); + + if rb.has_buffered() || rb.eof { + let empty_right = + Box::pin(EmptyRecordBatchStream::new(self.right.schema())); + let right_tail = std::mem::replace(&mut self.right, empty_right); + self.right = Box::pin(ReplayStream::new(rb, right_tail)); + } + } + Decision::SwapRight => { + metrics.build_swapped.add(1); + self.build_report.detach_without_cancel(); + + let swapped_join_type = self.join_type.swap(); + let empty_right_tail: SendableRecordBatchStream = + Box::pin(EmptyRecordBatchStream::new(self.right.schema())); + + let on_build = std::mem::replace(&mut self.on_right, on_left); + + let (prefix, right_build_tail) = + rb.into_prefix_and_tail(empty_right_tail); + let left_fut = OnceFut::new(collect_left_input( + self.random_state.clone(), + prefix, + right_build_tail, + on_build, + self.join_metrics.clone(), + need_produce_result_in_final(swapped_join_type), + 1, + false, + build_args.config, + self.null_equality, + build_args.array_map_created_count, + )); + self.build_side = BuildSide::Initial(BuildSideInitialState { left_fut }); + + self.right = Box::pin(ReplayStream::new(lb, left)); + + self.filter = self.filter.as_ref().map(JoinFilter::swap); + self.join_type = swapped_join_type; + for col_idx in &mut self.column_indices { + col_idx.side = col_idx.side.negate(); + } + self.right_side_ordered = false; + } + } + + self.state = HashJoinStreamState::WaitBuildSide; + Ok(()) } /// Returns the next state after the build side has been fully collected @@ -607,11 +916,23 @@ impl HashJoinStream { } return match self.state { + HashJoinStreamState::AdaptiveSample => { + match ready!(self.poll_adaptive_sample(cx)) { + Ok(state) => handle_state!(Ok(state)), + Err(err) => return self.fail_terminal(err), + } + } HashJoinStreamState::WaitBuildSide => { - handle_state!(ready!(self.collect_build_side(cx))) + match ready!(self.collect_build_side(cx)) { + Ok(state) => handle_state!(Ok(state)), + Err(err) => return self.fail_terminal(err), + } } HashJoinStreamState::WaitPartitionBoundsReport => { - handle_state!(ready!(self.wait_for_partition_bounds_report(cx))) + match ready!(self.wait_for_partition_bounds_report(cx)) { + Ok(state) => handle_state!(Ok(state)), + Err(err) => return self.fail_terminal(err), + } } HashJoinStreamState::FetchProbeBatch => { handle_state!(ready!(self.fetch_probe_batch(cx))) @@ -647,9 +968,11 @@ impl HashJoinStream { cx: &mut std::task::Context<'_>, ) -> Poll>>> { ready!(self.build_report.poll_delivery(cx))?; - let build_side = self.build_side.try_as_ready()?; - self.state = - Self::state_after_build_ready(self.join_type, build_side.left_data.as_ref()); + let next_state = { + let build_side = self.build_side.try_as_ready()?; + Self::state_after_build_ready(self.join_type, build_side.left_data.as_ref()) + }; + self.set_state(next_state); Poll::Ready(Ok(StatefulStreamResult::Continue)) } @@ -674,9 +997,10 @@ impl HashJoinStream { // not the build side (left). The probe-side NULL check happens during process_probe_batch. // The probe_side_has_null flag will be set there if any probe batch contains NULL. - self.state = self.transition_after_build_collected(&left_data); + let next_state = self.transition_after_build_collected(&left_data); self.build_side = BuildSide::Ready(BuildSideReadyState { left_data }); + self.set_state(next_state); Poll::Ready(Ok(StatefulStreamResult::Continue)) } @@ -936,7 +1260,7 @@ impl HashJoinStream { // If limit reached, finish and move to Completed state if push_status == PushBatchStatus::LimitReached { self.output_buffer.finish()?; - self.state = HashJoinStreamState::Completed; + self.set_state(HashJoinStreamState::Completed); return Ok(StatefulStreamResult::Continue); } @@ -962,32 +1286,29 @@ impl HashJoinStream { let timer = self.join_metrics.join_time.timer(); if !need_produce_result_in_final(self.join_type) { - self.state = HashJoinStreamState::Completed; + timer.done(); + self.set_state(HashJoinStreamState::Completed); return Ok(StatefulStreamResult::Continue); } - let build_side = self.build_side.try_as_ready()?; + let left_data = Arc::clone(&self.build_side.try_as_ready()?.left_data); // For null-aware anti join, if probe side had NULL, no rows should be output // Check shared atomic state to get global knowledge across all partitions - if self.null_aware - && build_side - .left_data - .probe_side_has_null - .load(Ordering::Relaxed) - { + if self.null_aware && left_data.probe_side_has_null.load(Ordering::Relaxed) { timer.done(); - self.state = HashJoinStreamState::Completed; + self.set_state(HashJoinStreamState::Completed); return Ok(StatefulStreamResult::Continue); } - if !build_side.left_data.report_probe_completed() { - self.state = HashJoinStreamState::Completed; + if !left_data.report_probe_completed() { + timer.done(); + self.set_state(HashJoinStreamState::Completed); return Ok(StatefulStreamResult::Continue); } // use the global left bitmap to produce the left indices and right indices let (mut left_side, mut right_side) = get_final_indices_from_shared_bitmap( - build_side.left_data.visited_indices_bitmap(), + left_data.visited_indices_bitmap(), self.join_type, true, ); @@ -998,13 +1319,10 @@ impl HashJoinStream { // Use shared atomic state to get global knowledge across all partitions if self.null_aware && self.join_type == JoinType::LeftAnti - && build_side - .left_data - .probe_side_non_empty - .load(Ordering::Relaxed) + && left_data.probe_side_non_empty.load(Ordering::Relaxed) { // Since null_aware validation ensures single column join, we only check the first column - let build_key_column = &build_side.left_data.values()[0]; + let build_key_column = &left_data.values()[0]; // Filter out indices where the key is NULL let filtered_indices: Vec = left_side @@ -1032,14 +1350,14 @@ impl HashJoinStream { timer.done(); - self.state = HashJoinStreamState::Completed; + self.set_state(HashJoinStreamState::Completed); // Push final unmatched indices to output buffer if !left_side.is_empty() { let empty_right_batch = RecordBatch::new_empty(self.right.schema()); let batch = build_batch_from_indices( &self.schema, - build_side.left_data.batch(), + left_data.batch(), &empty_right_batch, &left_side, &right_side, diff --git a/datafusion/sqllogictest/test_files/information_schema.slt b/datafusion/sqllogictest/test_files/information_schema.slt index e651ad1fbfa4b..68e1b1884671a 100644 --- a/datafusion/sqllogictest/test_files/information_schema.slt +++ b/datafusion/sqllogictest/test_files/information_schema.slt @@ -222,6 +222,7 @@ datafusion.execution.enable_file_stream_work_stealing true datafusion.execution.enable_migration_aggregate true datafusion.execution.enable_recursive_ctes true datafusion.execution.enforce_batch_size_in_joins false +datafusion.execution.hash_join_adaptive_build_side_threshold_bytes 0 datafusion.execution.hash_join_buffering_capacity 0 datafusion.execution.keep_partition_by_columns false datafusion.execution.listing_table_factory_infer_partitions true @@ -383,6 +384,7 @@ datafusion.execution.enable_file_stream_work_stealing true When `true` (the defa datafusion.execution.enable_migration_aggregate true Temporary switch for aggregate stream implementations that are being migrated from `GroupedHashAggregateStream`. When set to true, DataFusion tries the migrated implementations when their preconditions are satisfied. When set to false, grouped aggregation falls back to `GroupedHashAggregateStream`. This option will be removed after the migration is finished. See for details. datafusion.execution.enable_recursive_ctes true Should DataFusion support recursive CTEs datafusion.execution.enforce_batch_size_in_joins false Should DataFusion enforce batch size in joins or not. By default, DataFusion will not enforce batch size in joins. Enforcing batch size in joins can reduce memory usage when joining large tables with a highly-selective join filter, but is also slightly slower. +datafusion.execution.hash_join_adaptive_build_side_threshold_bytes 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). datafusion.execution.hash_join_buffering_capacity 0 How many bytes to buffer in the probe side of hash joins while the build side is concurrently being built. Without this, hash joins will wait until the full materialization of the build side before polling the probe side. This is useful in scenarios where the query is not completely CPU bounded, allowing to do some early work concurrently and reducing the latency of the query. Note that when hash join buffering is enabled, the probe side will start eagerly polling data, not giving time for the producer side of dynamic filters to produce any meaningful predicate. Queries with dynamic filters might see performance degradation. Disabled by default, set to a number greater than 0 for enabling it. datafusion.execution.keep_partition_by_columns false Should DataFusion keep the columns used for partition_by in the output RecordBatches datafusion.execution.listing_table_factory_infer_partitions true Should a `ListingTable` created through the `ListingTableFactory` infer table partitions from Hive compliant directories. Defaults to true (partition columns are inferred and will be represented in the table schema). diff --git a/docs/source/user-guide/configs.md b/docs/source/user-guide/configs.md index c0ce8b6806ee0..29fe37e53d5e5 100644 --- a/docs/source/user-guide/configs.md +++ b/docs/source/user-guide/configs.md @@ -145,6 +145,7 @@ The following configuration settings are available: | datafusion.execution.objectstore_writer_buffer_size | 10485760 | Size (bytes) of data buffer DataFusion uses when writing output files. This affects the size of the data chunks that are uploaded to remote object stores (e.g. AWS S3). If very large (>= 100 GiB) output files are being written, it may be necessary to increase this size to avoid errors from the remote end point. | | datafusion.execution.enable_ansi_mode | false | Whether to enable ANSI SQL mode. The flag is experimental and relevant only for DataFusion Spark built-in functions When `enable_ansi_mode` is set to `true`, the query engine follows ANSI SQL semantics for expressions, casting, and error handling. This means: - **Strict type coercion rules:** implicit casts between incompatible types are disallowed. - **Standard SQL arithmetic behavior:** operations such as division by zero, numeric overflow, or invalid casts raise runtime errors rather than returning `NULL` or adjusted values. - **Consistent ANSI behavior** for string concatenation, comparisons, and `NULL` handling. When `enable_ansi_mode` is `false` (the default), the engine uses a more permissive, non-ANSI mode designed for user convenience and backward compatibility. In this mode: - Implicit casts between types are allowed (e.g., string to integer when possible). - Arithmetic operations are more lenient — for example, `abs()` on the minimum representable integer value returns the input value instead of raising overflow. - Division by zero or invalid casts may return `NULL` instead of failing. # Default `false` — ANSI SQL mode is disabled by default. | | datafusion.execution.hash_join_buffering_capacity | 0 | How many bytes to buffer in the probe side of hash joins while the build side is concurrently being built. Without this, hash joins will wait until the full materialization of the build side before polling the probe side. This is useful in scenarios where the query is not completely CPU bounded, allowing to do some early work concurrently and reducing the latency of the query. Note that when hash join buffering is enabled, the probe side will start eagerly polling data, not giving time for the producer side of dynamic filters to produce any meaningful predicate. Queries with dynamic filters might see performance degradation. Disabled by default, set to a number greater than 0 for enabling it. | +| datafusion.execution.hash_join_adaptive_build_side_threshold_bytes | 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). | | datafusion.optimizer.enable_distinct_aggregation_soft_limit | true | When set to true, the optimizer will push a limit operation into grouped aggregations which have no aggregate expressions, as a soft limit, emitting groups once the limit is reached, before all rows in the group are read. | | datafusion.optimizer.enable_round_robin_repartition | true | When set to true, the physical plan optimizer will try to add round robin repartitioning to increase parallelism to leverage more CPU cores | | datafusion.optimizer.enable_topk_aggregation | true | When set to true, the optimizer will attempt to perform limit operations during aggregations, if possible |