martin-g commented on code in PR #21742:
URL: https://github.com/apache/datafusion/pull/21742#discussion_r3110199407


##########
datafusion/physical-plan/src/spill/replayable_spill_input.rs:
##########
@@ -0,0 +1,372 @@
+// 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.
+
+//! Utility for replaying a one-shot input `RecourdBatchStream` through spill.

Review Comment:
   ```suggestion
   //! Utility for replaying a one-shot input `RecordBatchStream` through spill.
   ```



##########
datafusion/physical-plan/src/spill/replayable_spill_input.rs:
##########
@@ -0,0 +1,372 @@
+// 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.
+
+//! Utility for replaying a one-shot input `RecourdBatchStream` through spill.
+//!
+//! See comments in [`ReplayableStreamSource`] for details.
+
+use std::pin::Pin;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicU32, Ordering};
+use std::task::{Context, Poll};
+
+use arrow::datatypes::SchemaRef;
+use arrow::record_batch::RecordBatch;
+use datafusion_common::{Result, internal_err};
+use datafusion_execution::RecordBatchStream;
+use datafusion_execution::SendableRecordBatchStream;
+use datafusion_execution::disk_manager::RefCountedTempFile;
+use futures::Stream;
+use parking_lot::Mutex;
+
+use crate::EmptyRecordBatchStream;
+use crate::spill::in_progress_spill_file::InProgressSpillFile;
+use crate::spill::spill_manager::SpillManager;
+
+const FIRST_PASS_ACTIVE_EPOCH: u32 = 1;
+const POISONED_EPOCH: u32 = u32::MAX;
+
+/// Spill-backed replayable stream source.
+///
+/// [`ReplayableStreamSource`] is constructed from an input stream, usually 
produced
+/// by executing an input `ExecutionPlan`.
+///
+/// - On the first pass, it evaluates the input stream, produces 
`RecordBatch`es,
+///   caches those batches to a local spill file, and also forwards them to the
+///   output.
+/// - On subsequent passes, it reads directly from the spill file.
+///
+/// ```text
+/// first pass:
+///
+/// RecordBatch stream
+///     |
+///     v
+///   [batch] -> output
+///     |
+///     +----> spill file
+///
+///
+/// later passes:
+///
+/// spill file
+///     |
+///     v
+///   [batch] -> output
+/// ```
+///
+/// This is useful when an input stream must be replayed and:
+/// - Re-evaluation is expensive because the input stream may come from a long
+///   and complex pipeline.
+/// - The parent operator is under memory pressure and cannot cache the input 
in
+///   memory for replay.
+pub(crate) struct ReplayableStreamSource {
+    schema: SchemaRef,
+    input: Option<SendableRecordBatchStream>,
+    spill_manager: SpillManager,
+    request_description: String,
+    /// 0 = unopened, 1 = first pass active, 2 = replayable/empty, MAX = 
poisoned
+    /// on execution errors.
+    epoch: Arc<AtomicU32>,
+    spill_file: Arc<Mutex<Option<RefCountedTempFile>>>,
+}
+
+impl ReplayableStreamSource {
+    /// Creates a replayable stream producer over a one-shot input stream.
+    ///
+    /// It caches the input into a local spill file on the first pass, then
+    /// reads directly from that spill file on subsequent passes.
+    pub(crate) fn new(
+        input: SendableRecordBatchStream,
+        spill_manager: SpillManager,
+        request_description: impl Into<String>,
+    ) -> Self {
+        let schema = input.schema();
+        Self {
+            schema,
+            input: Some(input),
+            spill_manager,
+            request_description: request_description.into(),
+            epoch: Arc::new(AtomicU32::new(0)),
+            spill_file: Arc::new(Mutex::new(None)),
+        }
+    }
+
+    /// Opens the next pass over this input.
+    ///
+    /// The first call returns a stream that forwards upstream batches while
+    /// caching them to spill. Later calls return streams that read directly
+    /// from the completed spill file.
+    ///
+    /// # Note
+    /// Subsequent passes MUST be opened only after the initial pass is fully
+    /// consumed; otherwise, an error is returned.
+    pub(crate) fn open_pass(&mut self) -> Result<SendableRecordBatchStream> {
+        match self.epoch.load(Ordering::Relaxed) {

Review Comment:
   Is `Relaxed` enough here?
   Acquire/Release would guarantee the ordering of the operations if more than 
1 threads try to read this atomic integer.
   The code below uses pattern like:
   ```rust
   epoch_state.load(Relaxed);
   ...
   *spill_file_state.lock() = spill_file;
   epoch_state.store(epoch.saturating_add(1), Ordering::Relaxed);
   ```
   The problem here is that the MutexGuard does not live long enough to cover 
the `epoch_state.store()` call and there is a chance another thread to be 
executed between the update of the Mutex and the `.store()` call.
   You may want to store the MutexGuard in a local variable.



##########
datafusion/physical-plan/src/spill/replayable_spill_input.rs:
##########
@@ -0,0 +1,372 @@
+// 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.
+
+//! Utility for replaying a one-shot input `RecourdBatchStream` through spill.
+//!
+//! See comments in [`ReplayableStreamSource`] for details.
+
+use std::pin::Pin;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicU32, Ordering};
+use std::task::{Context, Poll};
+
+use arrow::datatypes::SchemaRef;
+use arrow::record_batch::RecordBatch;
+use datafusion_common::{Result, internal_err};
+use datafusion_execution::RecordBatchStream;
+use datafusion_execution::SendableRecordBatchStream;
+use datafusion_execution::disk_manager::RefCountedTempFile;
+use futures::Stream;
+use parking_lot::Mutex;
+
+use crate::EmptyRecordBatchStream;
+use crate::spill::in_progress_spill_file::InProgressSpillFile;
+use crate::spill::spill_manager::SpillManager;
+
+const FIRST_PASS_ACTIVE_EPOCH: u32 = 1;
+const POISONED_EPOCH: u32 = u32::MAX;
+
+/// Spill-backed replayable stream source.
+///
+/// [`ReplayableStreamSource`] is constructed from an input stream, usually 
produced
+/// by executing an input `ExecutionPlan`.
+///
+/// - On the first pass, it evaluates the input stream, produces 
`RecordBatch`es,
+///   caches those batches to a local spill file, and also forwards them to the
+///   output.
+/// - On subsequent passes, it reads directly from the spill file.
+///
+/// ```text
+/// first pass:
+///
+/// RecordBatch stream
+///     |
+///     v
+///   [batch] -> output
+///     |
+///     +----> spill file
+///
+///
+/// later passes:
+///
+/// spill file
+///     |
+///     v
+///   [batch] -> output
+/// ```
+///
+/// This is useful when an input stream must be replayed and:
+/// - Re-evaluation is expensive because the input stream may come from a long
+///   and complex pipeline.
+/// - The parent operator is under memory pressure and cannot cache the input 
in
+///   memory for replay.
+pub(crate) struct ReplayableStreamSource {
+    schema: SchemaRef,
+    input: Option<SendableRecordBatchStream>,
+    spill_manager: SpillManager,
+    request_description: String,
+    /// 0 = unopened, 1 = first pass active, 2 = replayable/empty, MAX = 
poisoned
+    /// on execution errors.
+    epoch: Arc<AtomicU32>,
+    spill_file: Arc<Mutex<Option<RefCountedTempFile>>>,
+}
+
+impl ReplayableStreamSource {
+    /// Creates a replayable stream producer over a one-shot input stream.
+    ///
+    /// It caches the input into a local spill file on the first pass, then
+    /// reads directly from that spill file on subsequent passes.
+    pub(crate) fn new(
+        input: SendableRecordBatchStream,
+        spill_manager: SpillManager,
+        request_description: impl Into<String>,
+    ) -> Self {
+        let schema = input.schema();
+        Self {
+            schema,
+            input: Some(input),
+            spill_manager,
+            request_description: request_description.into(),
+            epoch: Arc::new(AtomicU32::new(0)),
+            spill_file: Arc::new(Mutex::new(None)),
+        }
+    }
+
+    /// Opens the next pass over this input.
+    ///
+    /// The first call returns a stream that forwards upstream batches while
+    /// caching them to spill. Later calls return streams that read directly
+    /// from the completed spill file.
+    ///
+    /// # Note
+    /// Subsequent passes MUST be opened only after the initial pass is fully
+    /// consumed; otherwise, an error is returned.
+    pub(crate) fn open_pass(&mut self) -> Result<SendableRecordBatchStream> {
+        match self.epoch.load(Ordering::Relaxed) {
+            0 => {
+                let Some(input) = self.input.take() else {

Review Comment:
   ```suggestion
                   if self.input.is_none() {
   ```
   postpone the Option::take() until `spill_manager.create_in_progress_file()` 
finishes successfully.
   Otherwise the `input` might be consumed/taken and the `epoch` still `0`.



##########
datafusion/physical-plan/src/joins/nested_loop_join.rs:
##########


Review Comment:
   The docstring is obsolete. The spill logic has been moved to 
replayable_spill_input.rs



##########
datafusion/physical-plan/src/spill/replayable_spill_input.rs:
##########
@@ -0,0 +1,372 @@
+// 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.
+
+//! Utility for replaying a one-shot input `RecourdBatchStream` through spill.
+//!
+//! See comments in [`ReplayableStreamSource`] for details.
+
+use std::pin::Pin;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicU32, Ordering};
+use std::task::{Context, Poll};
+
+use arrow::datatypes::SchemaRef;
+use arrow::record_batch::RecordBatch;
+use datafusion_common::{Result, internal_err};
+use datafusion_execution::RecordBatchStream;
+use datafusion_execution::SendableRecordBatchStream;
+use datafusion_execution::disk_manager::RefCountedTempFile;
+use futures::Stream;
+use parking_lot::Mutex;
+
+use crate::EmptyRecordBatchStream;
+use crate::spill::in_progress_spill_file::InProgressSpillFile;
+use crate::spill::spill_manager::SpillManager;
+
+const FIRST_PASS_ACTIVE_EPOCH: u32 = 1;
+const POISONED_EPOCH: u32 = u32::MAX;
+
+/// Spill-backed replayable stream source.
+///
+/// [`ReplayableStreamSource`] is constructed from an input stream, usually 
produced
+/// by executing an input `ExecutionPlan`.
+///
+/// - On the first pass, it evaluates the input stream, produces 
`RecordBatch`es,
+///   caches those batches to a local spill file, and also forwards them to the
+///   output.
+/// - On subsequent passes, it reads directly from the spill file.
+///
+/// ```text
+/// first pass:
+///
+/// RecordBatch stream
+///     |
+///     v
+///   [batch] -> output
+///     |
+///     +----> spill file
+///
+///
+/// later passes:
+///
+/// spill file
+///     |
+///     v
+///   [batch] -> output
+/// ```
+///
+/// This is useful when an input stream must be replayed and:
+/// - Re-evaluation is expensive because the input stream may come from a long
+///   and complex pipeline.
+/// - The parent operator is under memory pressure and cannot cache the input 
in
+///   memory for replay.
+pub(crate) struct ReplayableStreamSource {
+    schema: SchemaRef,
+    input: Option<SendableRecordBatchStream>,
+    spill_manager: SpillManager,
+    request_description: String,
+    /// 0 = unopened, 1 = first pass active, 2 = replayable/empty, MAX = 
poisoned
+    /// on execution errors.
+    epoch: Arc<AtomicU32>,
+    spill_file: Arc<Mutex<Option<RefCountedTempFile>>>,
+}
+
+impl ReplayableStreamSource {
+    /// Creates a replayable stream producer over a one-shot input stream.
+    ///
+    /// It caches the input into a local spill file on the first pass, then
+    /// reads directly from that spill file on subsequent passes.
+    pub(crate) fn new(
+        input: SendableRecordBatchStream,
+        spill_manager: SpillManager,
+        request_description: impl Into<String>,
+    ) -> Self {
+        let schema = input.schema();
+        Self {
+            schema,
+            input: Some(input),
+            spill_manager,
+            request_description: request_description.into(),
+            epoch: Arc::new(AtomicU32::new(0)),
+            spill_file: Arc::new(Mutex::new(None)),
+        }
+    }
+
+    /// Opens the next pass over this input.
+    ///
+    /// The first call returns a stream that forwards upstream batches while
+    /// caching them to spill. Later calls return streams that read directly
+    /// from the completed spill file.
+    ///
+    /// # Note
+    /// Subsequent passes MUST be opened only after the initial pass is fully
+    /// consumed; otherwise, an error is returned.
+    pub(crate) fn open_pass(&mut self) -> Result<SendableRecordBatchStream> {
+        match self.epoch.load(Ordering::Relaxed) {
+            0 => {
+                let Some(input) = self.input.take() else {
+                    return internal_err!(
+                        "ReplayableStreamSource missing first-pass input"
+                    );
+                };
+                let spill_file = self
+                    .spill_manager
+                    .create_in_progress_file(&self.request_description)?;
+                *self.spill_file.lock() = None;

Review Comment:
   the second part of 
https://github.com/apache/datafusion/pull/21742/changes#r3110298802
   ```suggestion
                   let input = self
                       .input
                       .take()
                       .expect("input was checked before creating the spill 
file");
                   *self.spill_file.lock() = None;
   ```



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to