Resolve lost wakeup in SpillPoolReader with multiple concurrent SpillPoolWriters#23522
Conversation
That is interesting because I constantly facing the "Too many open files" when there is a heavy spill. I did not know it is a problem and I was thinking it is OK, just used |
| if !shared.current_write_files.is_empty() { | ||
| // Copy and clear `current_write_files` so we can release shared lock before locking files | ||
| let files = shared.current_write_files.clone(); | ||
| shared.current_write_files.clear(); |
There was a problem hiding this comment.
Do we really need to release shared lock before locking files
Does it make sense to take file out from current_write_files consecutively then we could avoid clone?
There was a problem hiding this comment.
Do we really need to release shared lock before locking files
I'm not entirely sure. My assumption was that this was already carefully tuned, so I didn't want to change the lock nesting. If I understood it correctly, the intention is to avoid IO while the shared lock is held. InProgressSpilFile::finish can do IO so the shared lock is released before calling finish.
Does it make sense to take file out from current_write_files consecutively then we could avoid clone?
The clone/clear is actually kind of pointless. Might as well just mem::take the entire VecDequeue here. I've made that change.
There was a problem hiding this comment.
I'm not entirely sure. My assumption was that this was already carefully tuned, so I didn't want to change the lock nesting. If I understood it correctly, the intention is to avoid IO while the shared lock is held. InProgressSpilFile::finish can do IO so the shared lock is released before calling finish.
we also need to be sure we don't have a deadlock due to lock inversion (aka try to take the file/shared locks in different orders across different code paths)
| file_shared.writer_finished = true; | ||
| // Wake reader waiting on this file (it's now finished) | ||
| file_shared.wake(); | ||
| // Don't put back current_write_file - let it rotate |
There was a problem hiding this comment.
| // Don't put back current_write_file - let it rotate | |
| // Don't put back current_write_files - let it rotate |
There was a problem hiding this comment.
Singular is actually correct here, but I'll change the wording a bit to clarify what's being done.
alamb
left a comment
There was a problem hiding this comment.
This looks good to me -- thank you @pepijnve and @jayzhan211 (BTW 👋 it is great to see you again). I think adding some more comments explaining the expected state of the various queues would help make this code easier to understand in the future, but doesn't have to happen as part of this PR
cc @adriangb who added I think added SpillPoolShared in the first place
cc @xanderbailey who added some of this share pool machnery
| use super::spill_manager::SpillManager; | ||
|
|
||
| /// Shared state between the writer and readers of a spill pool. | ||
| /// This contains the queue of files and coordination state. |
There was a problem hiding this comment.
I this these comments would be nice to update to reflect the new design
Specifically note that the current_write_files is a list of files that are currently open but not being acively written to. When a file is being actively written to, active writer count is incremented by one and an entry is removed from current_write_files
There was a problem hiding this comment.
I'll do another pass over the code and update the comments. I didn't pay sufficient attention to those.
|
|
||
| // No files in queue - check if writer is done | ||
| if shared.writer_dropped { | ||
| if shared.active_writer_count == 0 { |
There was a problem hiding this comment.
I wonder (maybe as a follow on PR) if adding some sort of RAAI guard for updating active_writer_count would make the code les error prone.
Or maybe even having a separate list of files being actively written (rather than just a count 🤔 )
There was a problem hiding this comment.
The SpillPoolWriter plays the role of RAAI guard itself, doesn't it? It's incremented when a SpillPoolWriter is cloned, and decremented on drop.
The name active_writer_count is a bit misleading. It does not reflect the number of writers currently writing a batch. It reflects the number of writers that still exist.
| if !shared.current_write_files.is_empty() { | ||
| // Copy and clear `current_write_files` so we can release shared lock before locking files | ||
| let files = shared.current_write_files.clone(); | ||
| shared.current_write_files.clear(); |
There was a problem hiding this comment.
I'm not entirely sure. My assumption was that this was already carefully tuned, so I didn't want to change the lock nesting. If I understood it correctly, the intention is to avoid IO while the shared lock is held. InProgressSpilFile::finish can do IO so the shared lock is released before calling finish.
we also need to be sure we don't have a deadlock due to lock inversion (aka try to take the file/shared locks in different orders across different code paths)
|
I've updated the documentation and code comments for correctness. I've deemphasised FIFO semantics quite a bit. The existing documentation stated that this was always guaranteed, but that was not actually the case. Prior to this PR the following chain of events could happen:
The reader will observe batches in the order This MR assumes that we can take this even further, since the FIFO guarantee already doesn't hold when multiple writers are present. Would be good to get some feedback from @adriangb indeed since the non-FIFO behaviour was already present in the first commit of this code unless I'm completely misreading it. I'm going to try to write a test that demonstrates the behaviour. |
|
I'm worried about dropping the FIFO semantics (even if they were broken). |
I'm probably missing a bit too much context. Could you help me define the exact order guarantee that's being promised by the spill pool? Single writer remains FIFO, but in the presence of multiple concurrent writers, what order can you actually guarantee for the reader? The best you can do I think is guarantee that the relative order of the batches per writer is retained. Is that sufficient? |
|
BTW, I had based myself a bit on this comment in When |
|
That makes sense, I was just checking that and came to the same conclusion. As long as SPSC preserves ordering / FIFO we are good 👍🏻 |
The spill pool's FIFO guarantee only holds for a single writer: with multiple concurrent `SpillPoolWriter` clones the reader can observe batches out of write order. That is fine for non-preserve-order `RepartitionExec` (the output is an unordered multiset), but for `preserve_order = true` the per-(input, output) stream feeds an order-sensitive `StreamingMerge`, so losing FIFO would silently produce wrong (unsorted) results. Previously the "single writer per ordered pool" invariant was upheld only by convention: one `preserve_order` bool drove two independent decisions (channel count vs. writer cloning) in two places, coupled only by comments. A future edit could break one without the other. Encode the invariant in the type system instead: - `channel()` now returns `SpillPoolWriter`, which is **not** `Clone`, so an ordered pool can only ever have one writer (enforced at compile time). It wraps the shared implementation and delegates `push_batch`. - `shared_channel()` returns the `Clone` `SharedSpillPoolWriter` for the multi-producer, per-writer-FIFO case. - `RepartitionExec` selects the topology in one place: `preserve_order` builds one dedicated ordered writer per input (moved, never cloned) via `PartitionSpillWriters::PerInput`; non-preserve builds one shared writer cloned across inputs via `PartitionSpillWriters::Shared`. Now feeding an ordered pool with a shared multi-producer writer simply does not compile. Adds `test_preserve_order_with_spill_file_rotation`, which forces a spill file per batch (`max_spill_file_size_bytes = 1`) and asserts each output partition stays sorted — exercising FIFO across file rotation. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WsjHVeKZtrSHugLwNFURjL
|
I've added a |
Enforce single-writer spill pools for preserve_order via the type system
|
Thanks for the suggestion @adriangb I was thinking of doing something similar as well. I'll handle the merge conflict with |
# Conflicts: # datafusion/physical-plan/src/repartition/mod.rs
…e SpillWriter wrapper type
|
I flipped around the nesting of I've edited the documentation a bit to be less verbose. Claude seemed kind of happy to repeat the fact that indeed SharedSpillPoolWriter is Clone over and over again. |
| match self { | ||
| PartitionSpillWriters::PerInput(writers) => writers[input] | ||
| .take() | ||
| .expect("spill writer for input partition requested more than once"), |
There was a problem hiding this comment.
It looks like this gets called from a fallible function, we could (not saying we should) make this error instead of panic.
| /// A tuple of `(SharedSpillPoolWriter, SendableRecordBatchStream)` that share the same | ||
| /// underlying pool. The reader is returned as a stream for immediate use with | ||
| /// async stream combinators. The writer can be cloned to create additional writers. | ||
| pub fn shared_channel( |
There was a problem hiding this comment.
could this be pub(crate)?
There was a problem hiding this comment.
So... I completely forgot about backwards compatibility for a moment. The spill_pool module, channel function, and SpillPoolWriter type were all public. The changes we're making here are breaking for existing code. Should I reshuffle things a bit to maintain the MPSC capable variant under the original names and introduce new ones for the SPSC only variant instead?
edit: I've gone ahead and done this already. Could use some help on naming these things. Best I could come up with is SpillPoolWriter for the MP version and SpillPoolSink for the non-clonable one. A bit too generic to my liking, but I didn't have anything better right away.
There was a problem hiding this comment.
Technically, yes. If it's not a huge burden lets use new names and deprecate the old methods / names according to the API health guide (https://datafusion.apache.org/contributor-guide/api-health.html).
There was a problem hiding this comment.
I'm fine with renaming and having deprecated aliases. What should the new names be though?
For the factory functions I went for spsc_channel and mpsc_channel. The existing channel is marked deprecated and simply calls mpsc_channel which is what the effective behaviour was before.
The writers is a bit trickier. We originally repurposed SpillPoolWriter to be the SP one and introduced SharedSpillPoolWriter as the MP one. That's not an option since we end up changing the definition of an existing type.
| let mut file_shared = file.lock(); | ||
|
|
||
| // Finish the current writer if it exists | ||
| if let Some(mut writer) = file_shared.writer.take() { |
|
@jayzhan211 is back! 🎉
|
alamb
left a comment
There was a problem hiding this comment.
This PR is looking really nice to me @pepijnve @adriangb and @jayzhan211
However, since the scope has significantly grown since I first reviewed the PR I don't think it would be a good idea to backport this change as is without some "bake time" on main first...
Perhaps we can apply the earlier (smaller) fix for 54?
| /// The set of spill-pool writers for a single output partition, before they are handed to the | ||
| /// per-input tasks. The variant encodes the repartition mode so the wrong writer topology cannot | ||
| /// be constructed for a given mode. | ||
| enum PartitionSpillWriters { |
|
Thank you for opening this pull request! Reviewer note: cargo-semver-checks reported the current version number is not SemVer-compatible with the changes in this pull request (compared against the base branch). Details |
I can go back and redo just the code changes and test additions on a back port branch. Makes sense to keep it as small as possible for a patch. |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #23522 +/- ##
=======================================
Coverage ? 80.65%
=======================================
Files ? 1086
Lines ? 366430
Branches ? 366430
=======================================
Hits ? 295561
Misses ? 53244
Partials ? 17625 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
(I am resolving the CI failures now) |
Does every patch now require 100% coverage of changed lines? |
No! We are sorting through the coverage reports (and they are somewhat useless now b/c there isn't a base to compare against): |
That's a relief. In the meantime I've created the minimal backport PR version of this. |
|
This is a very nice improvement, thanks for working on this! |
#23654) ## Which issue does this PR close? - part of #22547 54.x branch backport of fix for #23447 ## Rationale for this change See main PR #23522 ## What changes are included in this PR? See main PR #23522 ## Are these changes tested? Additional test cases added to verify existing behaviour Fix manually tested with reproduction code from #23447 ## Are there any user-facing changes? No
| /// Maximum size in bytes before rotating to a new file. | ||
| /// Typically set from configuration `datafusion.execution.max_spill_file_size_bytes`. | ||
| max_file_size_bytes: usize, | ||
| /// Shared state with readers (includes current_write_file for coordination) |
There was a problem hiding this comment.
nit:
(includes current_write_file for coordination)
is stale
There was a problem hiding this comment.
Since this branch has been merged already it would be best to make a PR with a fix

Which issue does this PR close?
Rationale for this change
When multiple
SpillPoolWriterclones concurrently push batches to the same channel, more than one non-finishedSpillFilecan be in flight. This happens because eachSpillPoolWriterclone takes thecurrent_write_fileat the start ofpush_batchand puts it back when it's done. When multiplepush_batchcalls happen concurrently, only the first one will be able to take thecurrent_write_fileand the others will all create their own new spill file. Which one gets put back for subsequent use is a race condition.If this occurred and the writers are all dropped before rotation happens in, multiple files in the
filesdeque will be havewriter_finished == false. The last writer drop logic inSpillPoolWriter::droponly finishes whatever file is thecurrent_write_fileas finished.This can lead to a stalled situation when
SpillPoolFile::poll_nextcatches up with the writer and returnsPendingbecausewriter_finished == false. A waker for the file is registered, but since the last writer drop logic only finishes and wakes whatever happens to becurrent_write_file, which may not be the current read file, the waker may end up never being notified.There is a secondary waker that is registered on the spill pool itself, but due to fine grained locking, it is possible for the wake call in the last writer drop logic to be called before the waker registration.
What changes are included in this PR?
writer_droppedfield which was an unnecessary denormalisation ofactive_writer_count == 0An additional benefit of tracking all unfinished write files is that excessive creation of tiny spill files is avoided when many writers are pushing batches concurrently.
Are these changes tested?
Reproduction case from linked issue was used to confirm fix
Are there any user-facing changes?
No