diff --git a/cpp/src/arrow/dataset/dataset_writer.cc b/cpp/src/arrow/dataset/dataset_writer.cc index f5104efb70b1..ecbfde6fe995 100644 --- a/cpp/src/arrow/dataset/dataset_writer.cc +++ b/cpp/src/arrow/dataset/dataset_writer.cc @@ -20,6 +20,7 @@ #include #include #include +#include #include #include @@ -53,9 +54,11 @@ class Throttle { bool Unthrottled() const { return max_value_ <= 0; } + // Returns std::nullopt if the values were acquired and otherwise a future that + // completes when the caller should try again std::optional> Acquire(uint64_t values) { if (Unthrottled()) { - return Future<>::MakeFinished(); + return std::nullopt; } std::lock_guard lg(mutex_); if (current_value_ >= max_value_) { @@ -110,13 +113,15 @@ struct DatasetWriterState { // Control for how many files the dataset writer will open. When this is exceeded // the dataset writer will pause and it will also close the largest open file. Throttle open_files_throttle; - // Control for how many rows the dataset writer will allow to be staged. A row is - // staged if it is waiting for more rows to reach minimum_batch_size. If this is - // exceeded then the largest staged batch is unstaged (no backpressure is applied) + // The total number of rows currently staged across all open files. + // Rows are staged for each open file until min_rows_per_group is reached. std::atomic staged_rows_count; + // Control for how many rows the dataset writer will allow to be staged. // If too many rows get staged we will end up with poor performance and, if more rows - // are staged than max_rows_queued we will end up with deadlock. To avoid this, once - // we have too many staged rows we just ignore min_rows_per_group + // are staged than max_rows_queued we will end up with deadlock. To avoid this, + // once staged_rows_count reaches max_rows_staged the file with the most staged rows + // has its staged rows written out, even if this results in a row group with fewer + // rows than min_rows_per_group (no backpressure is applied). const uint64_t max_rows_staged; // Mutex to guard access to the file visitors in the writer options std::mutex visitors_mutex; @@ -201,35 +206,42 @@ class DatasetWriterFileQueue "DatasetWriter::WriteBatch"sv); } - Result PopAndDeliverStagedBatch() { + Status PopAndDeliverStagedBatch() { ARROW_ASSIGN_OR_RAISE(std::shared_ptr next_batch, PopStagedBatch()); - int64_t rows_popped = next_batch->num_rows(); - rows_currently_staged_ -= next_batch->num_rows(); + uint64_t rows_popped = static_cast(next_batch->num_rows()); + rows_currently_staged_ -= rows_popped; + writer_state_->staged_rows_count -= rows_popped; ScheduleBatch(std::move(next_batch)); - return rows_popped; + return Status::OK(); } // Stage batches, popping and delivering batches if enough data has arrived Status Push(std::shared_ptr batch) { - uint64_t delta_staged = batch->num_rows(); - rows_currently_staged_ += delta_staged; + uint64_t rows_pushed = static_cast(batch->num_rows()); + rows_currently_staged_ += rows_pushed; + writer_state_->staged_rows_count += rows_pushed; staged_batches_.push_back(std::move(batch)); while (!staged_batches_.empty() && - (writer_state_->StagingFull() || - rows_currently_staged_ >= options_.min_rows_per_group)) { - ARROW_ASSIGN_OR_RAISE(int64_t rows_popped, PopAndDeliverStagedBatch()); - delta_staged -= rows_popped; + rows_currently_staged_ >= options_.min_rows_per_group) { + RETURN_NOT_OK(PopAndDeliverStagedBatch()); + } + return Status::OK(); + } + + uint64_t rows_staged() const { return rows_currently_staged_; } + + // Deliver all staged batches even if there are fewer than min_rows_per_group + Status FlushStaged() { + while (!staged_batches_.empty()) { + RETURN_NOT_OK(PopAndDeliverStagedBatch()); } - // Note, delta_staged may be negative if we were able to deliver some data - writer_state_->staged_rows_count += delta_staged; return Status::OK(); } Status Finish() { - writer_state_->staged_rows_count -= rows_currently_staged_; while (!staged_batches_.empty()) { - RETURN_NOT_OK(PopAndDeliverStagedBatch().status().OrElse( - [&](auto&&) { file_tasks_.reset(); })); + RETURN_NOT_OK( + PopAndDeliverStagedBatch().OrElse([&](auto&&) { file_tasks_.reset(); })); } // At this point all write tasks have been added. Because the scheduler // is a 1-task FIFO we know this task will run at the very end and can @@ -377,6 +389,14 @@ class DatasetWriterDirectoryQueue uint64_t rows_written() const { return rows_written_; } + uint64_t rows_staged() const { + return latest_open_file_ ? latest_open_file_->rows_staged() : 0; + } + + Status FlushStaged() { + return latest_open_file_ ? latest_open_file_->FlushStaged() : Status::OK(); + } + void PrepareDirectory() { if (directory_.empty() || !write_options_.create_dir) { return; @@ -494,6 +514,14 @@ Status ValidateOptions(const FileSystemDatasetWriteOptions& options) { return Status::Invalid( "max_rows_per_group must be less than or equal to max_rows_per_file"); } + if (options.max_rows_queued > 0 && + options.max_rows_queued < options.min_rows_per_group) { + // Rows staged to reach min_rows_per_group count as queued rows. If they could + // fill the queue on their own the writer would pause forever. + return Status::Invalid("max_rows_queued (", options.max_rows_queued, + ") must be 0 or at least min_rows_per_group (", + options.min_rows_per_group, ")"); + } return Status::OK(); } @@ -517,11 +545,20 @@ Status EnsureDestinationValid(const FileSystemDatasetWriteOptions& options) { return Status::OK(); } -// Rule of thumb for the max rows to stage. It will grow with max_rows_queued until -// max_rows_queued starts to get too large and then it caps out at 8 million rows. +// Rule of thumb for the max rows to stage. It grows with max_rows_queued so that +// raising max_rows_queued lets more files reach min_rows_per_group at the same time. // Feel free to replace with something more meaningful, this is just a random heuristic. -uint64_t CalculateMaxRowsStaged(uint64_t max_rows_queued) { - return std::min(static_cast(1 << 23), max_rows_queued / 4); +// +// A single file can only reach min_rows_per_group if that many rows can be staged so +// the limit is never smaller than min_rows_per_group. Staged rows count as queued +// rows so the limit must not exceed max_rows_queued or the writer would pause forever; +// ValidateOptions guarantees that min_rows_per_group <= max_rows_queued. +uint64_t CalculateMaxRowsStaged(const FileSystemDatasetWriteOptions& options) { + if (options.max_rows_queued == 0) { + // There is no limit on queued rows so there is no need to limit staged rows + return std::numeric_limits::max(); + } + return std::max(options.max_rows_queued / 4, options.min_rows_per_group); } } // namespace @@ -532,7 +569,7 @@ class DatasetWriter::DatasetWriterImpl { util::AsyncTaskScheduler* scheduler, std::function pause_callback, std::function resume_callback, - std::function finish_callback, uint64_t max_rows_queued) + std::function finish_callback) : scheduler_(scheduler), write_tasks_(util::MakeThrottledAsyncTaskGroup( scheduler_, /*max_concurrent_cost=*/1, /*queue=*/nullptr, @@ -542,8 +579,8 @@ class DatasetWriter::DatasetWriterImpl { })), write_options_(std::move(write_options)), writer_state_(std::make_shared( - max_rows_queued, write_options_.max_open_files, - CalculateMaxRowsStaged(max_rows_queued))), + write_options_.max_rows_queued, write_options_.max_open_files, + CalculateMaxRowsStaged(write_options_))), pause_callback_(std::move(pause_callback)), resume_callback_(std::move(resume_callback)) {} @@ -651,6 +688,44 @@ class DatasetWriter::DatasetWriterImpl { return largest->FinishCurrentFile(); } + // Keep track of how many rows a directory has staged so that the directory with the + // most staged rows can be found without looking at every directory. + void RecordStagedRows(const std::string& key, uint64_t rows_staged) { + auto recorded = staged_rows_by_directory_.find(key); + if (recorded != staged_rows_by_directory_.end()) { + if (recorded->second == rows_staged) { + return; + } + directories_by_staged_rows_.erase({recorded->second, key}); + if (rows_staged == 0) { + staged_rows_by_directory_.erase(recorded); + return; + } + recorded->second = rows_staged; + } else if (rows_staged == 0) { + return; + } else { + staged_rows_by_directory_.emplace(key, rows_staged); + } + directories_by_staged_rows_.emplace(rows_staged, key); + } + + // If too many rows are staged then write out the staged rows of the file that has + // the most of them, repeating until we are back under the limit. This gives the + // largest row groups we can still make. + Status EvictStagedRowsIfNeeded() { + while (writer_state_->StagingFull() && !directories_by_staged_rows_.empty()) { + // Ties are broken on the key so the choice is deterministic. The recorded count + // can be stale if the file was closed in the meantime, in which case there is + // nothing to write and the record is simply dropped. + const std::string key = directories_by_staged_rows_.rbegin()->second; + const auto& dir_queue = directory_queues_.at(key); + RETURN_NOT_OK(dir_queue->FlushStaged()); + RecordStagedRows(key, dir_queue->rows_staged()); + } + return Status::OK(); + } + Future<> DoWriteRecordBatch(std::shared_ptr batch, const std::string& directory, const std::string& prefix) { ARROW_ASSIGN_OR_RAISE( @@ -705,9 +780,12 @@ class DatasetWriter::DatasetWriterImpl { writer_state_->rows_in_flight_throttle.Release(next_chunk->num_rows()); return s; } + RecordStagedRows(dir_queue_itr->first, dir_queue->rows_staged()); + RETURN_NOT_OK(EvictStagedRowsIfNeeded()); batch = std::move(remainder); if (batch) { RETURN_NOT_OK(dir_queue->FinishCurrentFile()); + RecordStagedRows(dir_queue_itr->first, dir_queue->rows_staged()); } } @@ -730,6 +808,9 @@ class DatasetWriter::DatasetWriterImpl { // Map from directory + prefix to the queue for that directory std::unordered_map> directory_queues_; + // The directories that have staged rows, by key and ordered by staged rows + std::unordered_map staged_rows_by_directory_; + std::set> directories_by_staged_rows_; std::mutex mutex_; bool paused_ = false; Status err_; @@ -739,21 +820,20 @@ DatasetWriter::DatasetWriter(FileSystemDatasetWriteOptions write_options, util::AsyncTaskScheduler* scheduler, std::function pause_callback, std::function resume_callback, - std::function finish_callback, - uint64_t max_rows_queued) + std::function finish_callback) : impl_(std::make_unique( std::move(write_options), scheduler, std::move(pause_callback), - std::move(resume_callback), std::move(finish_callback), max_rows_queued)) {} + std::move(resume_callback), std::move(finish_callback))) {} Result> DatasetWriter::Make( FileSystemDatasetWriteOptions write_options, util::AsyncTaskScheduler* scheduler, std::function pause_callback, std::function resume_callback, - std::function finish_callback, uint64_t max_rows_queued) { + std::function finish_callback) { RETURN_NOT_OK(ValidateOptions(write_options)); RETURN_NOT_OK(EnsureDestinationValid(write_options)); - return std::unique_ptr(new DatasetWriter( - std::move(write_options), scheduler, std::move(pause_callback), - std::move(resume_callback), std::move(finish_callback), max_rows_queued)); + return std::unique_ptr( + new DatasetWriter(std::move(write_options), scheduler, std::move(pause_callback), + std::move(resume_callback), std::move(finish_callback))); } DatasetWriter::~DatasetWriter() = default; diff --git a/cpp/src/arrow/dataset/dataset_writer.h b/cpp/src/arrow/dataset/dataset_writer.h index edb1649b5f19..ffa56f944cd5 100644 --- a/cpp/src/arrow/dataset/dataset_writer.h +++ b/cpp/src/arrow/dataset/dataset_writer.h @@ -29,9 +29,6 @@ namespace arrow { namespace dataset { namespace internal { -// This lines up with our other defaults in the scanner and execution plan -constexpr uint64_t kDefaultDatasetWriterMaxRowsQueued = 8 * 1024 * 1024; - /// \brief Utility class that manages a set of writers to different paths /// /// Writers may be closed and reopened (and a new file created) based on the dataset @@ -46,14 +43,13 @@ class ARROW_DS_EXPORT DatasetWriter { /// Will fail if basename_template is invalid or if there is existing data and /// existing_data_behavior is kError /// - /// \param write_options options to control how the data should be written - /// \param max_rows_queued max # of rows allowed to be queued before the dataset_writer - /// will ask for backpressure + /// \param write_options options to control how the data should be written, including + /// max_rows_queued, the maximum number of rows allowed to be + /// queued before the dataset_writer will ask for backpressure static Result> Make( FileSystemDatasetWriteOptions write_options, util::AsyncTaskScheduler* scheduler, std::function pause_callback, std::function resume_callback, - std::function finish_callback, - uint64_t max_rows_queued = kDefaultDatasetWriterMaxRowsQueued); + std::function finish_callback); ~DatasetWriter(); @@ -91,8 +87,7 @@ class ARROW_DS_EXPORT DatasetWriter { DatasetWriter(FileSystemDatasetWriteOptions write_options, util::AsyncTaskScheduler* scheduler, std::function pause_callback, std::function resume_callback, - std::function finish_callback, - uint64_t max_rows_queued = kDefaultDatasetWriterMaxRowsQueued); + std::function finish_callback); class DatasetWriterImpl; std::unique_ptr impl_; diff --git a/cpp/src/arrow/dataset/dataset_writer_test.cc b/cpp/src/arrow/dataset/dataset_writer_test.cc index 45a36deccea6..4953373657c4 100644 --- a/cpp/src/arrow/dataset/dataset_writer_test.cc +++ b/cpp/src/arrow/dataset/dataset_writer_test.cc @@ -104,10 +104,11 @@ class DatasetWriterTestFixture : public testing::Test { std::unique_ptr MakeDatasetWriter( uint64_t max_rows = kDefaultDatasetWriterMaxRowsQueued) { + write_options_.max_rows_queued = max_rows; EXPECT_OK_AND_ASSIGN(auto dataset_writer, DatasetWriter::Make( write_options_, scheduler_, [this] { paused_ = true; }, - [this] { paused_ = false; }, [] {}, max_rows)); + [this] { paused_ = false; }, [] {})); return dataset_writer; } @@ -177,6 +178,25 @@ class DatasetWriterTestFixture : public testing::Test { return batch; } + std::vector ReadBatchSizes(const std::string& filename) { + std::vector batch_sizes; + std::optional file = FindFile(filename); + EXPECT_TRUE(file.has_value()) << "The file " << filename << " was not created"; + if (!file.has_value()) { + return batch_sizes; + } + std::shared_ptr in_stream = + std::make_shared(std::make_shared(file->data)); + EXPECT_OK_AND_ASSIGN(std::shared_ptr reader, + ipc::RecordBatchFileReader::Open(in_stream)); + for (int i = 0; i < reader->num_record_batches(); i++) { + EXPECT_OK_AND_ASSIGN(std::shared_ptr batch, + reader->ReadRecordBatch(i)); + batch_sizes.push_back(batch->num_rows()); + } + return batch_sizes; + } + void AssertFileCreated(const std::optional& maybe_file, const std::string& expected_filename) { ASSERT_TRUE(maybe_file.has_value()) @@ -466,6 +486,92 @@ TEST_F(DatasetWriterTestFixture, MinRowGroupBackpressure) { AssertCreatedData(expected_files); } +TEST_F(DatasetWriterTestFixture, MinRowGroupLargerThanStagingLimit) { + // GH-55642: a single file should reach min_rows_per_group even when that is more + // rows than the dataset writer would otherwise be willing to stage + write_options_.min_rows_per_group = 60; + auto dataset_writer = MakeDatasetWriter(/*max_rows=*/100); + for (int i = 0; i < 12; i++) { + dataset_writer->WriteRecordBatch(MakeBatch(10), ""); + } + EndWriterChecked(dataset_writer.get()); + AssertCreatedData({{"testdir/chunk-0.arrow", 0, 120, 2}}); +} + +TEST_F(DatasetWriterTestFixture, MinRowGroupEvictsLargestStaged) { + // GH-55642: when too many rows are staged the file with the most staged rows should + // be written out, not the file that happened to receive the latest batch + write_options_.min_rows_per_group = 50; + auto dataset_writer = MakeDatasetWriter(/*max_rows=*/100); + dataset_writer->WriteRecordBatch(MakeBatch(0, 30), "a"); + for (int i = 0; i < 4; i++) { + // The last of these reaches the limit of 50 staged rows and evicts "a" + dataset_writer->WriteRecordBatch(MakeBatch(100 + 5 * i, 5), "b"); + } + // Both files keep receiving rows after the eviction, so the 30 rows evicted from + // "a" form a row group smaller than min_rows_per_group that is not the last one + dataset_writer->WriteRecordBatch(MakeBatch(30, 10), "a"); + dataset_writer->WriteRecordBatch(MakeBatch(120, 10), "b"); + EndWriterChecked(dataset_writer.get()); + AssertCreatedData( + {{"testdir/a/chunk-0.arrow", 0, 40, 2}, {"testdir/b/chunk-0.arrow", 100, 30, 1}}); + ASSERT_EQ(ReadBatchSizes("testdir/a/chunk-0.arrow"), (std::vector{30, 10})); + ASSERT_EQ(ReadBatchSizes("testdir/b/chunk-0.arrow"), (std::vector{30})); +} + +TEST_F(DatasetWriterTestFixture, MinRowGroupManyFilesWithRoomToStage) { + // GH-55642: every file should reach min_rows_per_group when max_rows_queued leaves + // enough room to stage min_rows_per_group rows for each of them + write_options_.min_rows_per_group = 50; + write_options_.max_rows_per_group = 50; + // 4 files * 50 rows = 200 rows staged at most, the staging limit is 1000 / 4 + auto dataset_writer = MakeDatasetWriter(/*max_rows=*/1000); + for (int i = 0; i < 30; i++) { + for (int file = 0; file < 4; file++) { + dataset_writer->WriteRecordBatch(MakeBatch(0, 5), std::to_string(file)); + } + } + EndWriterChecked(dataset_writer.get()); + for (int file = 0; file < 4; file++) { + auto written = FindFile("testdir/" + std::to_string(file) + "/chunk-0.arrow"); + ASSERT_TRUE(written.has_value()); + int num_batches = 0; + auto batch = ReadAsBatch(written->data, &num_batches); + ASSERT_EQ(150, batch->num_rows()); + ASSERT_EQ(3, num_batches); + } +} + +TEST_F(DatasetWriterTestFixture, MinRowGroupUnlimitedRowsQueued) { + // GH-55642: with no limit on queued rows there is no limit on staged rows either + write_options_.min_rows_per_group = 50; + write_options_.max_rows_per_group = 50; + auto dataset_writer = MakeDatasetWriter(/*max_rows=*/0); + for (int i = 0; i < 30; i++) { + for (int file = 0; file < 8; file++) { + dataset_writer->WriteRecordBatch(MakeBatch(0, 5), std::to_string(file)); + } + } + EndWriterChecked(dataset_writer.get()); + for (int file = 0; file < 8; file++) { + auto written = FindFile("testdir/" + std::to_string(file) + "/chunk-0.arrow"); + ASSERT_TRUE(written.has_value()); + int num_batches = 0; + auto batch = ReadAsBatch(written->data, &num_batches); + ASSERT_EQ(150, batch->num_rows()); + ASSERT_EQ(3, num_batches); + } +} + +TEST_F(DatasetWriterTestFixture, MinRowGroupLargerThanMaxRowsQueued) { + // GH-55642: rows staged to reach min_rows_per_group count as queued rows so + // max_rows_queued can not be smaller + write_options_.min_rows_per_group = 60; + write_options_.max_rows_queued = 59; + ASSERT_RAISES(Invalid, + DatasetWriter::Make(write_options_, scheduler_, [] {}, [] {}, [] {})); +} + TEST_F(DatasetWriterTestFixture, ConcurrentWritesSameFile) { #ifndef ARROW_ENABLE_THREADING GTEST_SKIP() << "Concurrent writes tests need threads"; diff --git a/cpp/src/arrow/dataset/file_base.h b/cpp/src/arrow/dataset/file_base.h index c628d76f36f4..e54da94e76cb 100644 --- a/cpp/src/arrow/dataset/file_base.h +++ b/cpp/src/arrow/dataset/file_base.h @@ -385,6 +385,11 @@ class ARROW_DS_EXPORT FileWriter { std::optional bytes_written_; }; +/// \brief The default for FileSystemDatasetWriteOptions::max_rows_queued +/// +/// This lines up with our other defaults in the scanner and execution plan +constexpr uint64_t kDefaultDatasetWriterMaxRowsQueued = 8 * 1024 * 1024; + /// \brief Options for writing a dataset. struct ARROW_DS_EXPORT FileSystemDatasetWriteOptions { /// Options for individual fragment writing. @@ -434,6 +439,9 @@ struct ARROW_DS_EXPORT FileSystemDatasetWriteOptions { /// and only write the row groups to the disk when sufficient rows have accumulated. /// The final row group size may be less than this value and other options such as /// `max_open_files` or `max_rows_per_file` lead to smaller row group sizes. + /// Partitioned writes may also result in row groups with fewer rows than this if rows + /// need to be flushed to avoid hitting the limit on the number of staged rows (see + /// `max_rows_queued`). uint64_t min_rows_per_group = 0; /// If greater than 0 then the dataset writer may split up large incoming batches into @@ -442,6 +450,18 @@ struct ARROW_DS_EXPORT FileSystemDatasetWriteOptions { /// group size is just barely larger than this value). uint64_t max_rows_per_group = 1 << 20; + /// The maximum number of rows the dataset writer will hold in memory, either waiting + /// to form a row group or waiting to be written to disk, before it applies + /// backpressure. If 0 then there is no limit, on queued rows or on rows waiting to + /// form a row group. Otherwise this must be at least `min_rows_per_group`. + /// + /// Rows waiting to form a row group are limited, across all files being written, to + /// the larger of a quarter of this value and `min_rows_per_group`. When that limit + /// is reached the file with the most waiting rows has them written out as a smaller + /// row group. Raise this to let a partitioned write reach `min_rows_per_group` in + /// more partitions at the same time, at the cost of memory. + uint64_t max_rows_queued = kDefaultDatasetWriterMaxRowsQueued; + /// Controls what happens if an output directory already exists. ExistingDataBehavior existing_data_behavior = ExistingDataBehavior::kError; diff --git a/docs/source/python/dataset.rst b/docs/source/python/dataset.rst index 0c51458c8e64..0575ca660e14 100644 --- a/docs/source/python/dataset.rst +++ b/docs/source/python/dataset.rst @@ -758,6 +758,17 @@ defined with the ``min_rows_per_group`` parameter of :meth:`write_dataset`. less than this value if other options such as ``max_open_files`` or ``max_rows_per_file`` force smaller row group sizes. + Rows waiting for a row group to fill are held in memory. The writer limits + how many rows it holds this way, across all files being written, to the + larger of ``max_rows_queued / 4`` and ``min_rows_per_group``. When the + limit is reached, the file holding the most waiting rows has them written + out as a smaller row group. A single file therefore always reaches + ``min_rows_per_group``, but a partitioned write may not unless the + ``max_rows_queued`` parameter of :meth:`write_dataset` is 0 (no limit) or + at least 4 times ``min_rows_per_group`` multiplied by the number of + partitions being written at the same time. Raising ``max_rows_queued`` uses + more memory, and it must not be smaller than ``min_rows_per_group``. + The maximum number of rows allowed per group is defined with the ``max_rows_per_group`` parameter of :meth:`write_dataset`. diff --git a/python/pyarrow/_dataset.pyx b/python/pyarrow/_dataset.pyx index 4820027ee821..9f0a79e56903 100644 --- a/python/pyarrow/_dataset.pyx +++ b/python/pyarrow/_dataset.pyx @@ -4144,7 +4144,8 @@ def _filesystemdataset_write( int max_rows_per_file, int min_rows_per_group, int max_rows_per_group, - bool create_dir + bool create_dir, + max_rows_queued=None ): """ CFileSystemDataset.Write wrapper @@ -4164,6 +4165,8 @@ def _filesystemdataset_write( c_options.max_rows_per_file = max_rows_per_file c_options.max_rows_per_group = max_rows_per_group c_options.min_rows_per_group = min_rows_per_group + if max_rows_queued is not None: + c_options.max_rows_queued = max_rows_queued c_options.basename_template = tobytes(basename_template) if existing_data_behavior == 'error': c_options.existing_data_behavior = ExistingDataBehavior_ERROR diff --git a/python/pyarrow/dataset.py b/python/pyarrow/dataset.py index f696d5f03ba5..5a0a92d8fdff 100644 --- a/python/pyarrow/dataset.py +++ b/python/pyarrow/dataset.py @@ -849,7 +849,8 @@ def write_dataset(data, base_dir, *, basename_template=None, format=None, preserve_order=False, max_partitions=None, max_open_files=None, max_rows_per_file=None, min_rows_per_group=None, max_rows_per_group=None, file_visitor=None, - existing_data_behavior='error', create_dir=True): + existing_data_behavior='error', create_dir=True, + max_rows_queued=None): """ Write a dataset to a given format and partitioning. @@ -913,6 +914,9 @@ def write_dataset(data, base_dir, *, basename_template=None, format=None, Minimum number of rows per group. When the value is greater than 0, the dataset writer will batch incoming data and only write the row groups to the disk when sufficient rows have accumulated. + Partitioned writes may result in row groups with fewer rows than + this if rows need to be flushed to avoid hitting internal limits on + the number of staged rows (see ``max_rows_queued``). max_rows_per_group : int, default 1024 * 1024 Maximum number of rows per group. If the value is greater than 0, then the dataset writer may split up large incoming batches into @@ -957,6 +961,16 @@ def file_visitor(written_file): create_dir : bool, default True If False, directories will not be created. This can be useful for filesystems that do not require directories. + max_rows_queued : int, default 8 * 1024 * 1024 + The maximum number of rows the dataset writer will hold in memory, + either waiting to form a row group or waiting to be written to + disk, before it applies backpressure. If 0 there is no limit, on + queued rows or on rows waiting to form a row group. Otherwise it + must be at least min_rows_per_group. Rows waiting to form a row + group are limited, across all files being written, to the larger + of a quarter of this value and min_rows_per_group. Raise this to + let a partitioned write reach min_rows_per_group in more + partitions at the same time, at the cost of memory. """ from pyarrow.fs import _resolve_filesystem_and_path @@ -1036,5 +1050,5 @@ def file_visitor(written_file): scanner, base_dir, basename_template, filesystem, partitioning, preserve_order, file_options, max_partitions, file_visitor, existing_data_behavior, max_open_files, max_rows_per_file, - min_rows_per_group, max_rows_per_group, create_dir + min_rows_per_group, max_rows_per_group, create_dir, max_rows_queued ) diff --git a/python/pyarrow/includes/libarrow_dataset.pxd b/python/pyarrow/includes/libarrow_dataset.pxd index 12cf82733935..eecd29419c10 100644 --- a/python/pyarrow/includes/libarrow_dataset.pxd +++ b/python/pyarrow/includes/libarrow_dataset.pxd @@ -234,6 +234,7 @@ cdef extern from "arrow/dataset/api.h" namespace "arrow::dataset" nogil: uint64_t max_rows_per_file uint64_t min_rows_per_group uint64_t max_rows_per_group + uint64_t max_rows_queued cdef cppclass CFileSystemDataset \ "arrow::dataset::FileSystemDataset"(CDataset): diff --git a/python/pyarrow/tests/test_dataset.py b/python/pyarrow/tests/test_dataset.py index fd5a418aaf2d..94daa689e3e0 100644 --- a/python/pyarrow/tests/test_dataset.py +++ b/python/pyarrow/tests/test_dataset.py @@ -4588,6 +4588,57 @@ def test_write_dataset_min_rows_per_group(tempdir): assert rows_per_batch <= max_rows_per_group +def _row_group_sizes_per_file(base_dir): + return { + pathlib.Path(os.path.relpath(path, base_dir)).as_posix(): [ + md.row_group(i).num_rows for i in range(md.num_row_groups)] + for path in sorted(ds.dataset(base_dir, format="parquet").files) + for md in [pq.ParquetFile(path).metadata] + } + + +@pytest.mark.parquet +def test_write_dataset_min_rows_per_group_single_file(tempdir): + # GH-55642: a single file reaches min_rows_per_group even when that is + # more rows than the writer would otherwise hold back + table = pa.table({"x": pa.array(range(100_000), type=pa.int32())}) + ds.write_dataset(table.to_batches(max_chunksize=1_000), tempdir / "ds", + schema=table.schema, format="parquet", + min_rows_per_group=30_000, max_rows_per_group=30_000, + max_rows_queued=40_000) + assert _row_group_sizes_per_file(tempdir / "ds") == { + "part-0.parquet": [30_000, 30_000, 30_000, 10_000]} + + +@pytest.mark.parquet +def test_write_dataset_min_rows_per_group_partitioned(tempdir): + # GH-55642: every partition reaches min_rows_per_group when + # max_rows_queued leaves room to hold that many rows for each of them + num_rows, num_parts, rows_per_group = 120_000, 4, 10_000 + table = pa.table({ + "x": pa.array(range(num_rows), type=pa.int32()), + "p": pa.array([i % num_parts for i in range(num_rows)], type=pa.int32()), + }) + ds.write_dataset(table.to_batches(max_chunksize=1_000), tempdir / "ds", + schema=table.schema, format="parquet", + partitioning=["p"], partitioning_flavor="hive", + min_rows_per_group=rows_per_group, + max_rows_per_group=rows_per_group, + max_rows_queued=4 * num_parts * rows_per_group, + use_threads=False) + assert _row_group_sizes_per_file(tempdir / "ds") == { + f"p={p}/part-0.parquet": [rows_per_group] * 3 for p in range(num_parts)} + + +def test_write_dataset_max_rows_queued_too_small(tempdir): + # GH-55642: rows held back for min_rows_per_group count as queued rows + table = pa.table({"x": pa.array(range(100), type=pa.int32())}) + with pytest.raises(pa.ArrowInvalid, match="max_rows_queued"): + ds.write_dataset(table, tempdir / "ds", format="ipc", + min_rows_per_group=50, max_rows_per_group=50, + max_rows_queued=49) + + @pytest.mark.parquet def test_write_dataset_max_rows_per_group(tempdir): directory = tempdir / 'ds'