Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
150 changes: 115 additions & 35 deletions cpp/src/arrow/dataset/dataset_writer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
#include <deque>
#include <memory>
#include <mutex>
#include <set>
#include <unordered_map>
#include <unordered_set>

Expand Down Expand Up @@ -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<Future<>> Acquire(uint64_t values) {
if (Unthrottled()) {
return Future<>::MakeFinished();
return std::nullopt;
}
std::lock_guard<std::mutex> lg(mutex_);
if (current_value_ >= max_value_) {
Expand Down Expand Up @@ -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<uint64_t> 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;
Expand Down Expand Up @@ -201,35 +206,42 @@ class DatasetWriterFileQueue
"DatasetWriter::WriteBatch"sv);
}

Result<int64_t> PopAndDeliverStagedBatch() {
Status PopAndDeliverStagedBatch() {
ARROW_ASSIGN_OR_RAISE(std::shared_ptr<RecordBatch> next_batch, PopStagedBatch());
int64_t rows_popped = next_batch->num_rows();
rows_currently_staged_ -= next_batch->num_rows();
uint64_t rows_popped = static_cast<uint64_t>(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<RecordBatch> batch) {
uint64_t delta_staged = batch->num_rows();
rows_currently_staged_ += delta_staged;
uint64_t rows_pushed = static_cast<uint64_t>(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
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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();
}

Expand All @@ -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<uint64_t>(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<uint64_t>::max();
}
return std::max(options.max_rows_queued / 4, options.min_rows_per_group);
}

} // namespace
Expand All @@ -532,7 +569,7 @@ class DatasetWriter::DatasetWriterImpl {
util::AsyncTaskScheduler* scheduler,
std::function<void()> pause_callback,
std::function<void()> resume_callback,
std::function<void()> finish_callback, uint64_t max_rows_queued)
std::function<void()> finish_callback)
: scheduler_(scheduler),
write_tasks_(util::MakeThrottledAsyncTaskGroup(
scheduler_, /*max_concurrent_cost=*/1, /*queue=*/nullptr,
Expand All @@ -542,8 +579,8 @@ class DatasetWriter::DatasetWriterImpl {
})),
write_options_(std::move(write_options)),
writer_state_(std::make_shared<DatasetWriterState>(
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)) {}

Expand Down Expand Up @@ -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<RecordBatch> batch,
const std::string& directory, const std::string& prefix) {
ARROW_ASSIGN_OR_RAISE(
Expand Down Expand Up @@ -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());
}
}

Expand All @@ -730,6 +808,9 @@ class DatasetWriter::DatasetWriterImpl {
// Map from directory + prefix to the queue for that directory
std::unordered_map<std::string, std::shared_ptr<DatasetWriterDirectoryQueue>>
directory_queues_;
// The directories that have staged rows, by key and ordered by staged rows
std::unordered_map<std::string, uint64_t> staged_rows_by_directory_;
std::set<std::pair<uint64_t, std::string>> directories_by_staged_rows_;
std::mutex mutex_;
bool paused_ = false;
Status err_;
Expand All @@ -739,21 +820,20 @@ DatasetWriter::DatasetWriter(FileSystemDatasetWriteOptions write_options,
util::AsyncTaskScheduler* scheduler,
std::function<void()> pause_callback,
std::function<void()> resume_callback,
std::function<void()> finish_callback,
uint64_t max_rows_queued)
std::function<void()> finish_callback)
: impl_(std::make_unique<DatasetWriterImpl>(
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<std::unique_ptr<DatasetWriter>> DatasetWriter::Make(
FileSystemDatasetWriteOptions write_options, util::AsyncTaskScheduler* scheduler,
std::function<void()> pause_callback, std::function<void()> resume_callback,
std::function<void()> finish_callback, uint64_t max_rows_queued) {
std::function<void()> finish_callback) {
RETURN_NOT_OK(ValidateOptions(write_options));
RETURN_NOT_OK(EnsureDestinationValid(write_options));
return std::unique_ptr<DatasetWriter>(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<DatasetWriter>(
new DatasetWriter(std::move(write_options), scheduler, std::move(pause_callback),
std::move(resume_callback), std::move(finish_callback)));
}

DatasetWriter::~DatasetWriter() = default;
Expand Down
15 changes: 5 additions & 10 deletions cpp/src/arrow/dataset/dataset_writer.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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<std::unique_ptr<DatasetWriter>> Make(
FileSystemDatasetWriteOptions write_options, util::AsyncTaskScheduler* scheduler,
std::function<void()> pause_callback, std::function<void()> resume_callback,
std::function<void()> finish_callback,
uint64_t max_rows_queued = kDefaultDatasetWriterMaxRowsQueued);
std::function<void()> finish_callback);

~DatasetWriter();

Expand Down Expand Up @@ -91,8 +87,7 @@ class ARROW_DS_EXPORT DatasetWriter {
DatasetWriter(FileSystemDatasetWriteOptions write_options,
util::AsyncTaskScheduler* scheduler, std::function<void()> pause_callback,
std::function<void()> resume_callback,
std::function<void()> finish_callback,
uint64_t max_rows_queued = kDefaultDatasetWriterMaxRowsQueued);
std::function<void()> finish_callback);

class DatasetWriterImpl;
std::unique_ptr<DatasetWriterImpl> impl_;
Expand Down
Loading
Loading