You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "saadtajwar (via GitHub)" <gi...@apache.org> on 2026/08/25 23:27:11 UTC

[PR] refactor: NLJ Stream Refactor (Part 1 - Semi/Anti/Mark) DRAFT [datafusion]

saadtajwar opened a new pull request, #24681:
URL: https://github.com/apache/datafusion/pull/24681

   ## Which issue does this PR close?
   
   - Part 1 (of 2) of #24584
   
   ## Rationale for this change
   
   NestedLoopJoin is basically two separate streams currently - one for regular joins and one for semi/anti/mark (SAM) joins. We would like to both split these out to separate streams, and make both of the streams simpler by using the async generator pattern to remove the polling and state machinery 
   
   ## What changes are included in this PR?
   
   - Moved SAM joins to a separate stream
   - Stream for SAM joins now using the async generator pattern without the polling & state machinery
   - Created a shared file for helpers that are being used by both streams (`JoinLeftData` & associated methods, `SpillState` & associated methods, utility functions)
   - Moved
   
   
   ## Are these changes tested?
   
   <!--
   We typically require tests for all PRs in order to:
   1. Prevent the code from being accidentally broken by subsequent changes
   2. Serve as another way to document the expected behavior of the code
   
   If tests are not included in your PR, please explain why (for example, are they covered by existing tests)?
   -->
   
   ## Are there any user-facing changes?
   
   <!--
   If there are user-facing changes then we may require documentation to be updated before approving the PR.
   
   If there are any breaking changes to public APIs, please add the `api change` label.
   -->
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] refactor: NLJ Stream Refactor (Part 1 - Semi/Anti/Mark) [datafusion]

Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 commented on code in PR #24681:
URL: https://github.com/apache/datafusion/pull/24681#discussion_r3888952107


##########
datafusion/physical-plan/src/joins/nested_loop_join/semi_anti_mark_stream.rs:
##########
@@ -0,0 +1,674 @@
+// 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.
+
+//! Nested loop join stream specifically for semi, anti, and mark joins
+//! Instantiated by [`NestedLoopJoinExec`](crate::joins::nested_loop_join::NestedLoopJoinExec)
+//! when the join type is `LeftSemi`, `LeftAnti`, `RightSemi`, `RightAnti`,
+//! `LeftMark`, or `RightMark`.
+//!
+//! # Algorithm
+//!
+//! For each buffered left chunk:
+//! ```text
+//! for right_batch in right_side:
+//!     for left_row in left_chunk:          // bitmap-only probing
+//!         update left/right match bitmaps
+//!     emit/accumulate right-side SAM result
+//! report_probe_completed() once
+//! emit left-side SAM result (emitter partition only)
+//! ```
+//!
+//! In memory-limited mode, left chunks are loaded incrementally and right-side
+//! match bitmaps are accumulated globally; after all chunks, the right input
+//! is replayed from spill for final right-side emission.
+
+use std::future::poll_fn;
+use std::sync::Arc;
+
+use super::shared::{
+    JoinLeftData, LeftBufferBatchDecision, NestedLoopJoinMetrics, SpillState,
+    apply_filter_to_row_join_batch, buffer_left_batch_in_chunk,
+    build_global_right_result_batch, build_unmatched_batch, finalize_buffered_left_chunk,
+    initiate_spill_fallback, probe_sam_left_range, update_sam_matched_bitmaps,
+};
+use crate::SendableRecordBatchStream;
+use crate::joins::utils::{ColumnIndex, JoinFilter, OnceFut};
+use crate::stream::{ObservedStream, RecordBatchStreamAdapter};
+
+use arrow::array::BooleanArray;
+use arrow::buffer::BooleanBuffer;
+use arrow::compute::BatchCoalescer;
+use arrow::datatypes::{Schema, SchemaRef};
+use arrow::record_batch::RecordBatch;
+use datafusion_common::instant::Instant;
+use datafusion_common::{DataFusionError, JoinSide, Result, internal_datafusion_err};
+use datafusion_execution::{TryEmitter, async_try_stream};
+use datafusion_expr::JoinType;
+use futures::StreamExt;
+use log::debug;
+
+/// Nested loop join stream for Semi/Anti/Mark joins.
+///
+/// Evaluates the join predicate for every relevant left/right combination but
+/// does not emit `(left, right)` pairs. Instead it accumulates a Boolean value
+/// for each row on the output side to check for any match.
+pub(super) struct SemiAntiMarkNestedLoopJoinStream {
+    /// Output schema after applying the join projection.
+    output_schema: Arc<Schema>,
+    /// Optional non-equality join predicate.
+    join_filter: Option<JoinFilter>,
+    /// Semi, anti, or mark join type handled by this stream.
+    join_type: JoinType,
+    /// Side whose rows are produced by the join.
+    join_side: JoinSide,
+    /// Current probe-side input. Replaced by each replay pass after spilling.
+    right_data: Option<SendableRecordBatchStream>,
+    /// Shared future that collects the build side for the standard path.
+    left_data: OnceFut<JoinLeftData>,
+    /// Projection used to construct output columns from the input sides.
+    column_indices: Vec<ColumnIndex>,
+    /// Join, spill, and selectivity metrics.
+    metrics: NestedLoopJoinMetrics,
+    /// Target output batch size and probe range size.
+    batch_size: usize,
+    /// Coalesces result batches before yielding them to the consumer.
+    output_buffer: Box<BatchCoalescer>,
+    /// Disabled, pending, or active memory-limited spill execution.
+    spill_state: SpillState,
+    /// Start of the current join-time interval; `None` while paused.
+    join_time_start: Option<Instant>,
+    /// Number of right-side passes opened for buffered left chunks.
+    right_pass_count: usize,
+    /// Whether this stream has emitted at least one output row.
+    emitted_rows: bool,
+}
+
+impl SemiAntiMarkNestedLoopJoinStream {
+    /// Create the SAM stream and wrap its generator with baseline observation.
+    #[expect(clippy::too_many_arguments)]
+    pub(super) fn try_new(
+        schema: SchemaRef,
+        filter: Option<JoinFilter>,
+        join_type: JoinType,
+        right_data: SendableRecordBatchStream,
+        left_data: OnceFut<JoinLeftData>,
+        column_indices: Vec<ColumnIndex>,
+        metrics: NestedLoopJoinMetrics,
+        batch_size: usize,
+        spill_state: SpillState,
+    ) -> Result<SendableRecordBatchStream> {
+        debug_assert!(
+            matches!(
+                join_type,
+                JoinType::LeftSemi
+                    | JoinType::LeftAnti
+                    | JoinType::RightSemi
+                    | JoinType::RightAnti
+                    | JoinType::LeftMark
+                    | JoinType::RightMark
+            ),
+            "SemiAntiMarkNestedLoopJoinStream does not handle {join_type:?}"
+        );
+
+        let join_side = match join_type {
+            JoinType::LeftSemi | JoinType::LeftAnti | JoinType::LeftMark => {
+                JoinSide::Left
+            }
+            _ => JoinSide::Right,
+        };
+
+        let baseline_metrics = metrics.join_metrics.baseline.clone();
+
+        let mut state = Self {
+            output_schema: Arc::clone(&schema),
+            join_filter: filter,
+            join_type,
+            join_side,
+            right_data: Some(right_data),
+            column_indices,
+            left_data,
+            metrics,
+            output_buffer: Box::new(BatchCoalescer::new(Arc::clone(&schema), batch_size)),
+            batch_size,
+            spill_state,
+            join_time_start: None,
+            right_pass_count: 0,
+            emitted_rows: false,
+        };
+
+        let stream = async_try_stream(|mut emitter| async move {
+            state.start_join_time();
+            let result = state.join(&mut emitter).await;

Review Comment:
   I'll give it a try for hash join shortly, to see if it's doable.
   - https://github.com/apache/datafusion/issues/24791



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] refactor: NLJ Stream Refactor (Part 1 - Semi/Anti/Mark) DRAFT [datafusion]

Posted by "saadtajwar (via GitHub)" <gi...@apache.org>.
saadtajwar commented on PR #24681:
URL: https://github.com/apache/datafusion/pull/24681#issuecomment-5418413905

   NOTE: I know that this diff looks HUGE - important note that the **vast** majority of the diff in this PR is from the new organization of NLJ. The only new additions are in the SAM NLJ stream variant - the `exec.rs` is almost exactly copied & pasted besides choosing the SAM NLJ stream based on join type, the `materializing_stream` is almost the exact same besides using helpers that were moved out to `shared.rs`, etc.
   
   I definitely don't feel great asking someone to review this huge diff 😓 so if we think this is too big and needs to be organized into more, smaller PRs then I'm definitely happy to do so - if we think this is fine though, then once we get this in the PR2 for the regular join stream will hopefully be much much smaller :) 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] refactor: NLJ Stream Refactor (Part 1 - Semi/Anti/Mark) [datafusion]

Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 commented on code in PR #24681:
URL: https://github.com/apache/datafusion/pull/24681#discussion_r3888265615


##########
datafusion/physical-plan/src/joins/nested_loop_join/semi_anti_mark_stream.rs:
##########
@@ -0,0 +1,674 @@
+// 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.
+
+//! Nested loop join stream specifically for semi, anti, and mark joins
+//! Instantiated by [`NestedLoopJoinExec`](crate::joins::nested_loop_join::NestedLoopJoinExec)
+//! when the join type is `LeftSemi`, `LeftAnti`, `RightSemi`, `RightAnti`,
+//! `LeftMark`, or `RightMark`.
+//!
+//! # Algorithm
+//!
+//! For each buffered left chunk:
+//! ```text
+//! for right_batch in right_side:
+//!     for left_row in left_chunk:          // bitmap-only probing
+//!         update left/right match bitmaps
+//!     emit/accumulate right-side SAM result
+//! report_probe_completed() once
+//! emit left-side SAM result (emitter partition only)
+//! ```
+//!
+//! In memory-limited mode, left chunks are loaded incrementally and right-side
+//! match bitmaps are accumulated globally; after all chunks, the right input
+//! is replayed from spill for final right-side emission.
+
+use std::future::poll_fn;
+use std::sync::Arc;
+
+use super::shared::{
+    JoinLeftData, LeftBufferBatchDecision, NestedLoopJoinMetrics, SpillState,
+    apply_filter_to_row_join_batch, buffer_left_batch_in_chunk,
+    build_global_right_result_batch, build_unmatched_batch, finalize_buffered_left_chunk,
+    initiate_spill_fallback, probe_sam_left_range, update_sam_matched_bitmaps,
+};
+use crate::SendableRecordBatchStream;
+use crate::joins::utils::{ColumnIndex, JoinFilter, OnceFut};
+use crate::stream::{ObservedStream, RecordBatchStreamAdapter};
+
+use arrow::array::BooleanArray;
+use arrow::buffer::BooleanBuffer;
+use arrow::compute::BatchCoalescer;
+use arrow::datatypes::{Schema, SchemaRef};
+use arrow::record_batch::RecordBatch;
+use datafusion_common::instant::Instant;
+use datafusion_common::{DataFusionError, JoinSide, Result, internal_datafusion_err};
+use datafusion_execution::{TryEmitter, async_try_stream};
+use datafusion_expr::JoinType;
+use futures::StreamExt;
+use log::debug;
+
+/// Nested loop join stream for Semi/Anti/Mark joins.
+///
+/// Evaluates the join predicate for every relevant left/right combination but
+/// does not emit `(left, right)` pairs. Instead it accumulates a Boolean value
+/// for each row on the output side to check for any match.
+pub(super) struct SemiAntiMarkNestedLoopJoinStream {
+    /// Output schema after applying the join projection.
+    output_schema: Arc<Schema>,
+    /// Optional non-equality join predicate.
+    join_filter: Option<JoinFilter>,
+    /// Semi, anti, or mark join type handled by this stream.
+    join_type: JoinType,
+    /// Side whose rows are produced by the join.
+    join_side: JoinSide,
+    /// Current probe-side input. Replaced by each replay pass after spilling.
+    right_data: Option<SendableRecordBatchStream>,
+    /// Shared future that collects the build side for the standard path.
+    left_data: OnceFut<JoinLeftData>,
+    /// Projection used to construct output columns from the input sides.
+    column_indices: Vec<ColumnIndex>,
+    /// Join, spill, and selectivity metrics.
+    metrics: NestedLoopJoinMetrics,
+    /// Target output batch size and probe range size.
+    batch_size: usize,
+    /// Coalesces result batches before yielding them to the consumer.
+    output_buffer: Box<BatchCoalescer>,
+    /// Disabled, pending, or active memory-limited spill execution.
+    spill_state: SpillState,
+    /// Start of the current join-time interval; `None` while paused.
+    join_time_start: Option<Instant>,
+    /// Number of right-side passes opened for buffered left chunks.
+    right_pass_count: usize,
+    /// Whether this stream has emitted at least one output row.
+    emitted_rows: bool,
+}
+
+impl SemiAntiMarkNestedLoopJoinStream {
+    /// Create the SAM stream and wrap its generator with baseline observation.
+    #[expect(clippy::too_many_arguments)]
+    pub(super) fn try_new(
+        schema: SchemaRef,
+        filter: Option<JoinFilter>,
+        join_type: JoinType,
+        right_data: SendableRecordBatchStream,
+        left_data: OnceFut<JoinLeftData>,
+        column_indices: Vec<ColumnIndex>,
+        metrics: NestedLoopJoinMetrics,
+        batch_size: usize,
+        spill_state: SpillState,
+    ) -> Result<SendableRecordBatchStream> {
+        debug_assert!(
+            matches!(
+                join_type,
+                JoinType::LeftSemi
+                    | JoinType::LeftAnti
+                    | JoinType::RightSemi
+                    | JoinType::RightAnti
+                    | JoinType::LeftMark
+                    | JoinType::RightMark
+            ),
+            "SemiAntiMarkNestedLoopJoinStream does not handle {join_type:?}"
+        );
+
+        let join_side = match join_type {
+            JoinType::LeftSemi | JoinType::LeftAnti | JoinType::LeftMark => {
+                JoinSide::Left
+            }
+            _ => JoinSide::Right,
+        };
+
+        let baseline_metrics = metrics.join_metrics.baseline.clone();
+
+        let mut state = Self {
+            output_schema: Arc::clone(&schema),
+            join_filter: filter,
+            join_type,
+            join_side,
+            right_data: Some(right_data),
+            column_indices,
+            left_data,
+            metrics,
+            output_buffer: Box::new(BatchCoalescer::new(Arc::clone(&schema), batch_size)),
+            batch_size,
+            spill_state,
+            join_time_start: None,
+            right_pass_count: 0,
+            emitted_rows: false,
+        };
+
+        let stream = async_try_stream(|mut emitter| async move {
+            state.start_join_time();
+            let result = state.join(&mut emitter).await;

Review Comment:
   Is it possible to use the explicit states here like
   https://github.com/apache/datafusion/blob/61bf6b96cc07d6a0518014dec7fe86fbef76576e/datafusion/physical-plan/src/aggregates/hash_stream.rs#L175-L202
   
   I think the rule to follow is: if we have to draw a state transition graph to understand a operator, then implement it with the explicit state representation.
   - For CrossJoin, its logic is simple, so explicit states are not necessary
   - For NLJ, we do have to draw state machine graph to understand it, so the `enum` state can make it easier to understand and maintain.
   
   The emitter pattern doesn't seem to be mutual exclusive with explicit state representation, and its purpose is make the control flow implementation less verbose.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] refactor: NLJ Stream Refactor (Part 1 - Semi/Anti/Mark) DRAFT [datafusion]

Posted by "codecov-commenter (via GitHub)" <gi...@apache.org>.
codecov-commenter commented on PR #24681:
URL: https://github.com/apache/datafusion/pull/24681#issuecomment-5418725025

   ## [Codecov](https://app.codecov.io/gh/apache/datafusion/pull/24681?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `86.40331%` with `296 lines` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 81.45%. Comparing base ([`c699996`](https://app.codecov.io/gh/apache/datafusion/commit/c6999963455dae90f11130031ce8ee7d6add2c32?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`e1f1ce6`](https://app.codecov.io/gh/apache/datafusion/commit/e1f1ce638674d98af7330e5d4a216518370cc734?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   :warning: Report is 12 commits behind head on main.
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/datafusion/pull/24681?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [...src/joins/nested\_loop\_join/materializing\_stream.rs](https://app.codecov.io/gh/apache/datafusion/pull/24681?src=pr&el=tree&filepath=datafusion%2Fphysical-plan%2Fsrc%2Fjoins%2Fnested_loop_join%2Fmaterializing_stream.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZGF0YWZ1c2lvbi9waHlzaWNhbC1wbGFuL3NyYy9qb2lucy9uZXN0ZWRfbG9vcF9qb2luL21hdGVyaWFsaXppbmdfc3RyZWFtLnJz) | 85.77% | [54 Missing and 40 partials :warning: ](https://app.codecov.io/gh/apache/datafusion/pull/24681?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [...n/physical-plan/src/joins/nested\_loop\_join/exec.rs](https://app.codecov.io/gh/apache/datafusion/pull/24681?src=pr&el=tree&filepath=datafusion%2Fphysical-plan%2Fsrc%2Fjoins%2Fnested_loop_join%2Fexec.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZGF0YWZ1c2lvbi9waHlzaWNhbC1wbGFuL3NyYy9qb2lucy9uZXN0ZWRfbG9vcF9qb2luL2V4ZWMucnM=) | 86.66% | [49 Missing and 19 partials :warning: ](https://app.codecov.io/gh/apache/datafusion/pull/24681?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [...physical-plan/src/joins/nested\_loop\_join/shared.rs](https://app.codecov.io/gh/apache/datafusion/pull/24681?src=pr&el=tree&filepath=datafusion%2Fphysical-plan%2Fsrc%2Fjoins%2Fnested_loop_join%2Fshared.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZGF0YWZ1c2lvbi9waHlzaWNhbC1wbGFuL3NyYy9qb2lucy9uZXN0ZWRfbG9vcF9qb2luL3NoYXJlZC5ycw==) | 88.74% | [39 Missing and 29 partials :warning: ](https://app.codecov.io/gh/apache/datafusion/pull/24681?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [...rc/joins/nested\_loop\_join/semi\_anti\_mark\_stream.rs](https://app.codecov.io/gh/apache/datafusion/pull/24681?src=pr&el=tree&filepath=datafusion%2Fphysical-plan%2Fsrc%2Fjoins%2Fnested_loop_join%2Fsemi_anti_mark_stream.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZGF0YWZ1c2lvbi9waHlzaWNhbC1wbGFuL3NyYy9qb2lucy9uZXN0ZWRfbG9vcF9qb2luL3NlbWlfYW50aV9tYXJrX3N0cmVhbS5ycw==) | 83.58% | [36 Missing and 30 partials :warning: ](https://app.codecov.io/gh/apache/datafusion/pull/24681?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@            Coverage Diff             @@
   ##             main   #24681      +/-   ##
   ==========================================
   + Coverage   81.43%   81.45%   +0.01%     
   ==========================================
     Files        1118     1121       +3     
     Lines      399414   399749     +335     
     Branches   399414   399749     +335     
   ==========================================
   + Hits       325281   325609     +328     
   + Misses      55142    55132      -10     
   - Partials    18991    19008      +17     
   ```
   </details>
   
   [:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/datafusion/pull/24681?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] refactor: NLJ Stream Refactor (Part 1 - Semi/Anti/Mark) [datafusion]

Posted by "saadtajwar (via GitHub)" <gi...@apache.org>.
saadtajwar commented on PR #24681:
URL: https://github.com/apache/datafusion/pull/24681#issuecomment-5419058975

   @2010YOUY01 & @rluvaton - please let me know your thoughts! Thanks!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] refactor: NLJ Stream Refactor (Part 1 - Semi/Anti/Mark) [datafusion]

Posted by "saadtajwar (via GitHub)" <gi...@apache.org>.
saadtajwar commented on code in PR #24681:
URL: https://github.com/apache/datafusion/pull/24681#discussion_r3894864165


##########
datafusion/physical-plan/src/joins/nested_loop_join/semi_anti_mark_stream.rs:
##########
@@ -0,0 +1,674 @@
+// 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.
+
+//! Nested loop join stream specifically for semi, anti, and mark joins
+//! Instantiated by [`NestedLoopJoinExec`](crate::joins::nested_loop_join::NestedLoopJoinExec)
+//! when the join type is `LeftSemi`, `LeftAnti`, `RightSemi`, `RightAnti`,
+//! `LeftMark`, or `RightMark`.
+//!
+//! # Algorithm
+//!
+//! For each buffered left chunk:
+//! ```text
+//! for right_batch in right_side:
+//!     for left_row in left_chunk:          // bitmap-only probing
+//!         update left/right match bitmaps
+//!     emit/accumulate right-side SAM result
+//! report_probe_completed() once
+//! emit left-side SAM result (emitter partition only)
+//! ```
+//!
+//! In memory-limited mode, left chunks are loaded incrementally and right-side
+//! match bitmaps are accumulated globally; after all chunks, the right input
+//! is replayed from spill for final right-side emission.
+
+use std::future::poll_fn;
+use std::sync::Arc;
+
+use super::shared::{
+    JoinLeftData, LeftBufferBatchDecision, NestedLoopJoinMetrics, SpillState,
+    apply_filter_to_row_join_batch, buffer_left_batch_in_chunk,
+    build_global_right_result_batch, build_unmatched_batch, finalize_buffered_left_chunk,
+    initiate_spill_fallback, probe_sam_left_range, update_sam_matched_bitmaps,
+};
+use crate::SendableRecordBatchStream;
+use crate::joins::utils::{ColumnIndex, JoinFilter, OnceFut};
+use crate::stream::{ObservedStream, RecordBatchStreamAdapter};
+
+use arrow::array::BooleanArray;
+use arrow::buffer::BooleanBuffer;
+use arrow::compute::BatchCoalescer;
+use arrow::datatypes::{Schema, SchemaRef};
+use arrow::record_batch::RecordBatch;
+use datafusion_common::instant::Instant;
+use datafusion_common::{DataFusionError, JoinSide, Result, internal_datafusion_err};
+use datafusion_execution::{TryEmitter, async_try_stream};
+use datafusion_expr::JoinType;
+use futures::StreamExt;
+use log::debug;
+
+/// Nested loop join stream for Semi/Anti/Mark joins.
+///
+/// Evaluates the join predicate for every relevant left/right combination but
+/// does not emit `(left, right)` pairs. Instead it accumulates a Boolean value
+/// for each row on the output side to check for any match.
+pub(super) struct SemiAntiMarkNestedLoopJoinStream {
+    /// Output schema after applying the join projection.
+    output_schema: Arc<Schema>,
+    /// Optional non-equality join predicate.
+    join_filter: Option<JoinFilter>,
+    /// Semi, anti, or mark join type handled by this stream.
+    join_type: JoinType,
+    /// Side whose rows are produced by the join.
+    join_side: JoinSide,
+    /// Current probe-side input. Replaced by each replay pass after spilling.
+    right_data: Option<SendableRecordBatchStream>,
+    /// Shared future that collects the build side for the standard path.
+    left_data: OnceFut<JoinLeftData>,
+    /// Projection used to construct output columns from the input sides.
+    column_indices: Vec<ColumnIndex>,
+    /// Join, spill, and selectivity metrics.
+    metrics: NestedLoopJoinMetrics,
+    /// Target output batch size and probe range size.
+    batch_size: usize,
+    /// Coalesces result batches before yielding them to the consumer.
+    output_buffer: Box<BatchCoalescer>,
+    /// Disabled, pending, or active memory-limited spill execution.
+    spill_state: SpillState,
+    /// Start of the current join-time interval; `None` while paused.
+    join_time_start: Option<Instant>,
+    /// Number of right-side passes opened for buffered left chunks.
+    right_pass_count: usize,
+    /// Whether this stream has emitted at least one output row.
+    emitted_rows: bool,
+}
+
+impl SemiAntiMarkNestedLoopJoinStream {
+    /// Create the SAM stream and wrap its generator with baseline observation.
+    #[expect(clippy::too_many_arguments)]
+    pub(super) fn try_new(
+        schema: SchemaRef,
+        filter: Option<JoinFilter>,
+        join_type: JoinType,
+        right_data: SendableRecordBatchStream,
+        left_data: OnceFut<JoinLeftData>,
+        column_indices: Vec<ColumnIndex>,
+        metrics: NestedLoopJoinMetrics,
+        batch_size: usize,
+        spill_state: SpillState,
+    ) -> Result<SendableRecordBatchStream> {
+        debug_assert!(
+            matches!(
+                join_type,
+                JoinType::LeftSemi
+                    | JoinType::LeftAnti
+                    | JoinType::RightSemi
+                    | JoinType::RightAnti
+                    | JoinType::LeftMark
+                    | JoinType::RightMark
+            ),
+            "SemiAntiMarkNestedLoopJoinStream does not handle {join_type:?}"
+        );
+
+        let join_side = match join_type {
+            JoinType::LeftSemi | JoinType::LeftAnti | JoinType::LeftMark => {
+                JoinSide::Left
+            }
+            _ => JoinSide::Right,
+        };
+
+        let baseline_metrics = metrics.join_metrics.baseline.clone();
+
+        let mut state = Self {
+            output_schema: Arc::clone(&schema),
+            join_filter: filter,
+            join_type,
+            join_side,
+            right_data: Some(right_data),
+            column_indices,
+            left_data,
+            metrics,
+            output_buffer: Box::new(BatchCoalescer::new(Arc::clone(&schema), batch_size)),
+            batch_size,
+            spill_state,
+            join_time_start: None,
+            right_pass_count: 0,
+            emitted_rows: false,
+        };
+
+        let stream = async_try_stream(|mut emitter| async move {
+            state.start_join_time();
+            let result = state.join(&mut emitter).await;

Review Comment:
   Ah yes thats fair - I'll take a stab at refactoring this to use the explicit states. Thanks!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org