You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "2010YOUY01 (via GitHub)" <gi...@apache.org> on 2025/03/03 09:16:55 UTC
[PR] feat: Add one config to limit max disk usage for spilling queries [datafusion]
2010YOUY01 opened a new pull request, #14975:
URL: https://github.com/apache/datafusion/pull/14975
## Which issue does this PR close?
<!--
We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
-->
- Closes #.
## Rationale for this change
<!--
Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.
-->
For memory-limit queries, executors might write temporary results into the disk to reduce memory load. If important to have a configuration option to limit the max disk usage, in case some query would bloat the disk and cause other issues.
DuckDB provides a similar configuration:
```
max_temp_directory_size | The maximum amount of data stored inside the 'temp_directory' (when set) (e.g., 1GB)
```
## What changes are included in this PR?
<!--
There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
-->
This PR is mostly refactoring, the actual change is small. I made one big refactor into a separate commit, so you can only look at the second commit for the related changes.
### Changes
#### 1. Move `metrics` module from `datafusion_physical_plan` crate to `datafusion_execution` crate
Current code organization:
- `datafusion_physical_plan` depends on `datafusion_execution`
- `datafusion_physical_plan` includes physical executors like `SortExec`
- `datafusion_execution` includes memory reservation and disk manager
This PR requires adding metrics tracking ability to `DiskManager`, besides, I believe in the future we can also add more `Metrics` into `MemoryPool` and `DiskManager`, for aggregated statistics across different executors, so this PR first made this refactoring change.
#### 2. Group all spilling-related metrics in executors into a single struct `SpillMetrics`
This way we can ensure the metrics across different operators can be kept consistent.
#### 3. Implement the utility function to spill batches inside `DiskManager`
`try_spill_record_batches` is implemented to replace the old utility function `spill_record_batches`, this way the total spilled file size can be tracked, also the interface for external operators to use is a little simpler.
## Are these changes tested?
Yes, integration test is included for queries exceed/not-exceed the disk limit.
<!--
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?
No. However there is one deprecation, I'll explain separately.
<!--
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] feat: Add one config to limit max disk usage for spilling queries [datafusion]
Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 commented on code in PR #14975:
URL: https://github.com/apache/datafusion/pull/14975#discussion_r1977146593
##########
datafusion/physical-plan/src/spill.rs:
##########
@@ -54,41 +52,13 @@ pub(crate) fn read_spill_as_stream(
Ok(builder.build())
}
-/// Spills in-memory `batches` to disk.
-///
-/// Returns total number of the rows spilled to disk.
-pub(crate) fn spill_record_batches(
- batches: &[RecordBatch],
- path: PathBuf,
- schema: SchemaRef,
-) -> Result<(usize, usize)> {
- let mut writer = IPCStreamWriter::new(path.as_ref(), schema.as_ref())?;
- for batch in batches {
- writer.write(batch)?;
- }
- writer.finish()?;
- debug!(
- "Spilled {} batches of total {} rows to disk, memory released {}",
- writer.num_batches,
- writer.num_rows,
- human_readable_size(writer.num_bytes),
- );
- Ok((writer.num_rows, writer.num_bytes))
-}
-
-fn read_spill(sender: Sender<Result<RecordBatch>>, path: &Path) -> Result<()> {
- let file = BufReader::new(File::open(path)?);
- let reader = StreamReader::try_new(file, None)?;
- for batch in reader {
- sender
- .blocking_send(batch.map_err(Into::into))
- .map_err(|e| exec_datafusion_err!("{e}"))?;
- }
- Ok(())
-}
-
/// Spill the `RecordBatch` to disk as smaller batches
-/// split by `batch_size_rows`
+/// split by `batch_size_rows`.
+#[deprecated(
+ since = "46.0.0",
+ note = "This function is deprecated. Use `datafusion_execution::DiskManager::try_spill_record_batch_by_size` instead. Note this method is mainly used within DataFusion for spilling operators. If you only
+ want the functionality of writing `RecordBatch`es to disk, consider using `arrow::ipc::writer::StreamWriter` instead."
+)]
Review Comment:
This function doesn't have to be public, see `spill_record_batches()` is also non-public.
I believe this utility function is used mainly for tracking temp files and metrics for DataFusion executor's internal use, the major functionality for writing `RecordBatch`es to disk is in `arrow::ipc`, so I guess deprecating it won't cause major issues.
##########
datafusion/core/tests/memory_limit/mod.rs:
##########
@@ -468,6 +470,83 @@ async fn test_stringview_external_sort() {
let _ = df.collect().await.expect("Query execution failed");
}
+// Tests for disk limit (`max_temp_directory_size` in `DiskManager`)
+// ------------------------------------------------------------------
+
+// Create a new `SessionContext` with speicified disk limit and memory pool limit
+async fn setup_context(
+ disk_limit: u64,
+ memory_pool_limit: usize,
+) -> Result<SessionContext> {
+ let disk_manager = DiskManager::try_new_without_arc(DiskManagerConfig::NewOs)?
+ .with_max_temp_directory_size(disk_limit)?;
+
+ let runtime = RuntimeEnvBuilder::new()
Review Comment:
We can't use the builder to specify disk limit for now, because `DiskManagerConfig` is an `enum` instead of `struct`, so now the setup routine is a bit hacky.
Changing it I think will inevitably cause API change, so I prefer to leave it to a separate PR.
--
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] feat: Add config `max_temp_directory_size` to limit max disk usage for spilling queries [datafusion]
Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 commented on PR #14975:
URL: https://github.com/apache/datafusion/pull/14975#issuecomment-2739748374
@alamb Thanks for the review, I agree there are two things we can improve:
1. Create a new struct for spilling related utilities, instead of putting it inside `DiskManager`
2. Easier-to-use builder for `DiskManager` for configuring `max_temp_dicrectory_size` (@Standing-Man already start helping in https://github.com/apache/datafusion/issues/15319, thank you 🙏🏼 )
I also found another limitation in this spill interface, for certain cases we want:
```
let in_progress_temp_file = spiller.create_in_progress_temp_file();
spiller.append(batch);
...
spiller.append(batch);
let temp_file = spiller.finish();
```
Instead of always writing batches to a spill file at once.
I plan to address point 1 and the above-mentioned limitation in another PR, and after that rework this PR to add disk limit feature. So closed this PR for now.
--
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] feat: Add config `max_temp_directory_size` to limit max disk usage for spilling queries [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #14975:
URL: https://github.com/apache/datafusion/pull/14975#discussion_r2004255473
##########
datafusion/core/tests/memory_limit/mod.rs:
##########
@@ -468,6 +470,83 @@ async fn test_stringview_external_sort() {
let _ = df.collect().await.expect("Query execution failed");
}
+// Tests for disk limit (`max_temp_directory_size` in `DiskManager`)
+// ------------------------------------------------------------------
+
+// Create a new `SessionContext` with speicified disk limit and memory pool limit
+async fn setup_context(
+ disk_limit: u64,
+ memory_pool_limit: usize,
+) -> Result<SessionContext> {
+ let disk_manager = DiskManager::try_new_without_arc(DiskManagerConfig::NewOs)?
+ .with_max_temp_directory_size(disk_limit)?;
+
+ let runtime = RuntimeEnvBuilder::new()
Review Comment:
- I filed https://github.com/apache/datafusion/issues/15319 to track
--
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] feat: Add config `max_temp_directory_size` to limit max disk usage for spilling queries [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on PR #14975:
URL: https://github.com/apache/datafusion/pull/14975#issuecomment-2730388364
Sorry, it totally slipped my mind
--
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] feat: Add config `max_temp_directory_size` to limit max disk usage for spilling queries [datafusion]
Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 closed pull request #14975: feat: Add config `max_temp_directory_size` to limit max disk usage for spilling queries
URL: https://github.com/apache/datafusion/pull/14975
--
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] feat: Add one config to limit max disk usage for spilling queries [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on PR #14975:
URL: https://github.com/apache/datafusion/pull/14975#issuecomment-2694847925
Nice PR thanks @2010YOUY01 I'm planning to review it today
--
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] feat: Add config `max_temp_directory_size` to limit max disk usage for spilling queries [datafusion]
Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #14975:
URL: https://github.com/apache/datafusion/pull/14975#issuecomment-2729201199
This makes total sense to me, I’ve certainly wanted this feature!
--
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] feat: Add config `max_temp_directory_size` to limit max disk usage for spilling queries [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #14975:
URL: https://github.com/apache/datafusion/pull/14975#issuecomment-2739766003
> I plan to address point 1 and the above-mentioned limitation in another PR, and after that rework this PR to add disk limit feature. So closed this PR for now.
THank you -- I think consolidating the spilling related utilities and making the interface clear will make it much easier as we go forward to add new features.
Maybe we can take inspiration from comet's spill / shuffle writer code: https://github.com/apache/datafusion-comet/blob/382ac938f2d10666eefc08ec5c1c82025ddf3726/native/core/src/execution/shuffle/shuffle_writer.rs
--
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] feat: Add config `max_temp_directory_size` to limit max disk usage for spilling queries [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #14975:
URL: https://github.com/apache/datafusion/pull/14975#discussion_r2004211990
##########
datafusion/execution/src/disk_manager.rs:
##########
@@ -144,6 +219,94 @@ impl DiskManager {
.map_err(DataFusionError::IoError)?,
})
}
+
+ /// Write record batches to a temporary file, and return the spill file handle.
Review Comment:
I am not sure about putting this method on the `DiskManager` itself -- I think managing the contents of the spill files is something that will likely get more sophisticated (e.g. if we want to explore using mmap and other techniques to speed up reading)
I have been meaning to file tickets about this and I will do so shortly.
What would you think about introducing a new struct that would be responsible for managing the spill files for a particular operation
Something like this perhaps:
```rust
struct SpillFiles {
env: Arc<RuntimeEnv>
files: Vec<RefCountedTempFile>
...
}
...
impl SpillFiles {
pub fn try_spill_record_batches(
&self,
batches: &[RecordBatch],
request_description: &str,
caller_spill_metrics: &mut SpillMetrics,
) -> Result<()> {..}
}
```
##########
datafusion/execution/src/disk_manager.rs:
##########
@@ -93,14 +115,67 @@ impl DiskManager {
);
Ok(Arc::new(Self {
local_dirs: Mutex::new(Some(local_dirs)),
+ max_temp_directory_size: DEFAULT_MAX_TEMP_DIRECTORY_SIZE,
+ used_disk_space: Count::default(),
}))
}
DiskManagerConfig::Disabled => Ok(Arc::new(Self {
local_dirs: Mutex::new(None),
+ max_temp_directory_size: DEFAULT_MAX_TEMP_DIRECTORY_SIZE,
+ used_disk_space: Count::default(),
})),
}
}
+ pub fn try_new_without_arc(config: DiskManagerConfig) -> Result<Self> {
Review Comment:
I don't understand the need for this function and find the name confusing. It seems like the only difference is that it will error if it doesn't have exclusive access to the disk manager. I have an alternate suggestion above
##########
datafusion/core/tests/memory_limit/mod.rs:
##########
@@ -468,6 +470,83 @@ async fn test_stringview_external_sort() {
let _ = df.collect().await.expect("Query execution failed");
}
+// Tests for disk limit (`max_temp_directory_size` in `DiskManager`)
+// ------------------------------------------------------------------
+
+// Create a new `SessionContext` with speicified disk limit and memory pool limit
+async fn setup_context(
+ disk_limit: u64,
+ memory_pool_limit: usize,
+) -> Result<SessionContext> {
+ let disk_manager = DiskManager::try_new_without_arc(DiskManagerConfig::NewOs)?
+ .with_max_temp_directory_size(disk_limit)?;
+
+ let runtime = RuntimeEnvBuilder::new()
Review Comment:
I think you coudl do this iinstead of adding a new function:
```rust
let disk_manager = DiskManager::try_new(DiskManagerConfig::NewOs)?;
let disk_manager = Arc::try_unwrap(disk_manager)
.expect("DiskManager should be unique")
.with_max_temp_directory_size(disk_limit)?;
```
##########
datafusion/execution/src/disk_manager.rs:
##########
@@ -93,14 +115,67 @@ impl DiskManager {
);
Ok(Arc::new(Self {
local_dirs: Mutex::new(Some(local_dirs)),
+ max_temp_directory_size: DEFAULT_MAX_TEMP_DIRECTORY_SIZE,
+ used_disk_space: Count::default(),
}))
}
DiskManagerConfig::Disabled => Ok(Arc::new(Self {
local_dirs: Mutex::new(None),
+ max_temp_directory_size: DEFAULT_MAX_TEMP_DIRECTORY_SIZE,
+ used_disk_space: Count::default(),
})),
}
}
+ pub fn try_new_without_arc(config: DiskManagerConfig) -> Result<Self> {
+ match config {
+ DiskManagerConfig::Existing(manager) => {
+ Arc::try_unwrap(manager).map_err(|_| {
+ DataFusionError::Internal("Failed to unwrap Arc".to_string())
+ })
+ }
+ DiskManagerConfig::NewOs => Ok(Self {
+ local_dirs: Mutex::new(Some(vec![])),
+ max_temp_directory_size: DEFAULT_MAX_TEMP_DIRECTORY_SIZE,
+ used_disk_space: Count::default(),
+ }),
+ DiskManagerConfig::NewSpecified(conf_dirs) => {
+ let local_dirs = create_local_dirs(conf_dirs)?;
+ debug!(
+ "Created local dirs {:?} as DataFusion working directory",
+ local_dirs
+ );
+ Ok(Self {
+ local_dirs: Mutex::new(Some(local_dirs)),
+ max_temp_directory_size: DEFAULT_MAX_TEMP_DIRECTORY_SIZE,
+ used_disk_space: Count::default(),
+ })
+ }
+ DiskManagerConfig::Disabled => Ok(Self {
+ local_dirs: Mutex::new(None),
+ max_temp_directory_size: DEFAULT_MAX_TEMP_DIRECTORY_SIZE,
+ used_disk_space: Count::default(),
+ }),
+ }
+ }
+
+ /// Set the maximum amount of data (in bytes) stored inside the temporary directories.
+ pub fn with_max_temp_directory_size(
Review Comment:
I would expect that this function should be on the `DiskManagerConfig` rather than `DiskManager` 🤔
Then you won't have to add the new `try_uwnrap` either
--
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