Skip to content
Closed
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
1 change: 1 addition & 0 deletions cpp/src/arrow/dataset/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ endif()
set(ARROW_DATASET_SRCS
dataset.cc
dataset_writer.cc
dataset_writer_cleanup.cc
discovery.cc
file_base.cc
file_ipc.cc
Expand Down
42 changes: 12 additions & 30 deletions cpp/src/arrow/dataset/dataset_writer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ struct DatasetWriterState {
const uint64_t max_rows_staged;
// Mutex to guard access to the file visitors in the writer options
std::mutex visitors_mutex;
DatasetWriteCleanup cleanup;
};

Result<std::shared_ptr<FileWriter>> OpenWriter(
Expand Down Expand Up @@ -382,36 +383,17 @@ class DatasetWriterDirectoryQueue
return;
}
init_future_ = Future<>::Make();
auto create_dir_cb = [this] {
return DeferNotOk(write_options_.filesystem->io_context().executor()->Submit(
[this]() { return write_options_.filesystem->CreateDir(directory_); }));
};
// We need to notify waiters whether the directory succeeded or failed.
auto notify_waiters_cb = [this] { init_future_.MarkFinished(); };
auto notify_waiters_on_err_cb = [this](const Status& err) {
// If there is an error the scheduler will abort but that takes some time
// and we don't want to start writing in the meantime so we send an error to the
// file writing queue and return the error.
init_future_.MarkFinished(err);
return err;
};
std::function<Future<>()> init_task;
if (write_options_.existing_data_behavior ==
ExistingDataBehavior::kDeleteMatchingPartitions) {
init_task = [this, create_dir_cb, notify_waiters_cb, notify_waiters_on_err_cb] {
return write_options_.filesystem
->DeleteDirContentsAsync(directory_,
/*missing_dir_ok=*/true)
.Then(create_dir_cb)
.Then(notify_waiters_cb, notify_waiters_on_err_cb);
};
} else {
init_task = [create_dir_cb, notify_waiters_cb, notify_waiters_on_err_cb] {
return create_dir_cb().Then(notify_waiters_cb, notify_waiters_on_err_cb);
};
}
scheduler_->AddSimpleTask(std::move(init_task),
"DatasetWriter::InitializeDirectory"sv);
scheduler_->AddSimpleTask(
[self = shared_from_this()] {
auto initialized = self->writer_state_->cleanup.Initialize(
self->write_options_, self->directory_, self->prefix_);
initialized.AddCallback(
[ready = self->init_future_](const Status& status) mutable {
ready.MarkFinished(status);
});
return initialized;
},
"DatasetWriter::InitializeDirectory"sv);
}

static Result<std::shared_ptr<DatasetWriterDirectoryQueue>> Make(
Expand Down
19 changes: 19 additions & 0 deletions cpp/src/arrow/dataset/dataset_writer.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@

#pragma once

#include <mutex>
#include <string>
#include <unordered_map>

#include "arrow/dataset/file_base.h"
#include "arrow/record_batch.h"
Expand All @@ -32,6 +34,23 @@ namespace internal {
// This lines up with our other defaults in the scanner and execution plan
constexpr uint64_t kDefaultDatasetWriterMaxRowsQueued = 8 * 1024 * 1024;

// Prepares partition destinations and shares the filename-partition snapshot.
class DatasetWriteCleanup {
public:
Future<> Initialize(const FileSystemDatasetWriteOptions& options,
const std::string& directory, const std::string& prefix);

private:
using FilesByPrefix = std::unordered_map<std::string, fs::FileInfoVector>;

Future<> DeleteFilenamePartition(const FileSystemDatasetWriteOptions& options,
const std::string& directory,
const std::string& prefix);

std::once_flag list_files_;
Future<FilesByPrefix> existing_files_;
};

/// \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 Down
99 changes: 99 additions & 0 deletions cpp/src/arrow/dataset/dataset_writer_cleanup.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
// 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.

#include "arrow/dataset/dataset_writer.h"

#include <memory>
#include <utility>

#include "arrow/compute/expression.h"
#include "arrow/dataset/partition.h"
#include "arrow/util/async_generator.h"

namespace arrow::dataset::internal {

Future<> DatasetWriteCleanup::Initialize(const FileSystemDatasetWriteOptions& options,
const std::string& directory,
const std::string& prefix) {
const auto& filesystem = options.filesystem;
auto create_directory = [filesystem, directory] {
return DeferNotOk(filesystem->io_context().executor()->Submit(
[filesystem, directory] { return filesystem->CreateDir(directory); }));
};
if (options.existing_data_behavior != ExistingDataBehavior::kDeleteMatchingPartitions) {
return create_directory();
}
if (directory != options.base_dir ||
dynamic_cast<const FilenamePartitioning*>(options.partitioning.get()) == nullptr) {
return filesystem->DeleteDirContentsAsync(directory, /*missing_dir_ok=*/true)
.Then(create_directory);
}
return DeleteFilenamePartition(options, directory, prefix).Then(create_directory);
}

Future<> DatasetWriteCleanup::DeleteFilenamePartition(
const FileSystemDatasetWriteOptions& options, const std::string& directory,
const std::string& prefix) {
const auto& filesystem = options.filesystem;
std::call_once(list_files_, [&] {
// Filename partitions share a directory. Read the old file list before
// releasing any partition to write new files into it.
fs::FileSelector selector;
selector.base_dir = directory;
selector.allow_not_found = true;
auto files = std::make_shared<FilesByPrefix>();
auto collect = [files, partitioning =
options.partitioning](const fs::FileInfoVector& entries) {
for (const auto& info : entries) {
if (info.type() != fs::FileType::File) continue;
auto expression = partitioning->Parse(info.path());
if (!expression.ok() || (partitioning->schema()->num_fields() > 0 &&
*expression == compute::literal(true))) {
continue;
}
auto path = partitioning->Format(*expression);
if (path.ok()) {
(*files)[path->filename].push_back(info);
}
}
return Status::OK();
};
existing_files_ = VisitAsyncGenerator(filesystem->GetFileInfoGenerator(selector),
std::move(collect))
.Then([files] { return std::move(*files); });
});

return existing_files_.Then(
[filesystem, format = options.format(), prefix](const FilesByPrefix& files) {
auto matching = files.find(prefix);
if (matching == files.end()) {
return Future<>::MakeFinished();
}
return DeferNotOk(filesystem->io_context().executor()->Submit(
[filesystem, format, entries = matching->second] {
std::vector<std::string> paths;
for (const auto& info : entries) {
ARROW_ASSIGN_OR_RAISE(bool supported,
format->IsSupported(FileSource(info, filesystem)));
if (supported) paths.push_back(info.path());
}
return filesystem->DeleteFiles(paths);
}));
});
}

} // namespace arrow::dataset::internal
4 changes: 3 additions & 1 deletion cpp/src/arrow/dataset/type_fwd.h
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ class WriteNodeOptions;
/// \brief Controls what happens if files exist in an output directory during a dataset
/// write
enum class ExistingDataBehavior : int8_t {
/// Deletes all files in a directory the first time that directory is encountered
/// Replaces each written partition. For directory partitioning, delete the
/// partition directory contents. For filename partitioning, delete files of
/// the selected format whose parsed keys match the partition.
kDeleteMatchingPartitions,
/// Ignores existing files, overwriting any that happen to have the same name as an
/// output file
Expand Down
136 changes: 136 additions & 0 deletions cpp/src/arrow/dataset/write_node_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,31 @@

#include "arrow/acero/exec_plan.h"
#include "arrow/acero/options.h"
#include "arrow/compute/api_vector.h"
#include "arrow/dataset/discovery.h"
#include "arrow/dataset/file_base.h"
#include "arrow/dataset/file_ipc.h"
#include "arrow/dataset/partition.h"
#include "arrow/dataset/plan.h"
#include "arrow/filesystem/filesystem.h"
#include "arrow/filesystem/localfs.h"
#include "arrow/filesystem/mockfs.h"
#include "arrow/filesystem/path_util.h"
#include "arrow/io/interfaces.h"
#include "arrow/ipc/reader.h"
#include "arrow/testing/generator.h"
#include "arrow/testing/gtest_util.h"
#include "arrow/testing/matchers.h"

#include "arrow/table.h"
#include "arrow/util/config.h"
#include "arrow/util/io_util.h"
#include "arrow/util/key_value_metadata.h"

#ifdef ARROW_PARQUET
# include "arrow/dataset/file_parquet.h"
#endif

namespace arrow {

namespace dataset {
Expand All @@ -55,10 +65,136 @@ class SimpleWriteNodeTest : public ::testing::Test {
fs_write_options_.partitioning = dataset::Partitioning::Default();
}

static Status WriteTable(const FileSystemDatasetWriteOptions& options,
const std::shared_ptr<Table>& table) {
auto dataset = std::make_shared<InMemoryDataset>(table);
ARROW_ASSIGN_OR_RAISE(auto builder, dataset->NewScan());
ARROW_ASSIGN_OR_RAISE(auto scanner, builder->Finish());
return FileSystemDataset::Write(options, scanner);
}

std::shared_ptr<fs::internal::MockFileSystem> mock_fs_;
dataset::FileSystemDatasetWriteOptions fs_write_options_;
};

#ifdef ARROW_PARQUET
TEST_F(SimpleWriteNodeTest, DeleteMatchingPartitions) {
const auto data_schema = schema({field("year", int32()), field("value", int32())});
const auto partition_schema = schema({data_schema->field(0)});
auto original = TableFromJSON(data_schema, {R"([[2019, -1], [20190, -2]])"});
auto updates = TableFromJSON(data_schema, {R"([[2019, 1], [2020, 2], [2021, 3]])",
R"([[2019, 4], [2021, 5], [2022, 6]])"});
auto expected = TableFromJSON(data_schema, {R"([
[20190, -2], [2019, 1], [2020, 2], [2021, 3], [2019, 4], [2021, 5],
[2022, 6]
])"});
auto filesystem = std::make_shared<fs::LocalFileSystem>();
auto format = std::make_shared<ParquetFileFormat>();

for (const auto& partitioning : std::vector<std::shared_ptr<Partitioning>>{
std::make_shared<DirectoryPartitioning>(partition_schema),
std::make_shared<FilenamePartitioning>(partition_schema)}) {
SCOPED_TRACE(partitioning->type_name());
ASSERT_OK_AND_ASSIGN(auto tempdir,
::arrow::internal::TemporaryDir::Make("delete-matching-"));
ASSERT_OK_AND_ASSIGN(auto path, tempdir->path().Join("data"));
auto options = fs_write_options_;
options.filesystem = filesystem;
options.base_dir = path.ToString();
options.file_write_options = format->DefaultWriteOptions();
options.partitioning = partitioning;
options.basename_template = "old_{i}.parquet";
options.existing_data_behavior = ExistingDataBehavior::kDeleteMatchingPartitions;
ASSERT_OK(WriteTable(options, original->Slice(0, 1)));
options.existing_data_behavior = ExistingDataBehavior::kOverwriteOrIgnore;
ASSERT_OK(WriteTable(options, original->Slice(1, 1)));

const bool filenames = partitioning->type_name() == "filename";
const auto join = [&](std::string_view part) {
return fs::internal::ConcatAbstractPath(options.base_dir, part);
};
const auto old_match = join(filenames ? "2019_old_0.parquet" : "2019/old_0.parquet");
const auto alias = join("02019_older.parquet");
const auto notes = join("2019_notes.txt");
const auto unpartitioned = join(".unpartitioned.parquet");
if (filenames) {
ASSERT_OK(filesystem->Move(old_match, alias));
ASSERT_OK(filesystem->CopyFile(alias, unpartitioned));
ASSERT_OK_AND_ASSIGN(auto stream, filesystem->OpenOutputStream(notes));
ASSERT_OK(stream->Write("Notes independent of this Parquet dataset"));
ASSERT_OK(stream->Close());
}

options.basename_template = "part{i}.parquet";
options.existing_data_behavior = ExistingDataBehavior::kDeleteMatchingPartitions;
options.max_rows_per_file = options.max_rows_per_group = 1;
ASSERT_OK(WriteTable(options, updates));

ASSERT_OK_AND_ASSIGN(auto stale,
filesystem->GetFileInfo(filenames ? alias : old_match));
EXPECT_EQ(stale.type(), fs::FileType::NotFound);
if (filenames) {
ASSERT_OK_AND_ASSIGN(auto info, filesystem->GetFileInfo(notes));
EXPECT_EQ(info.type(), fs::FileType::File);
ASSERT_OK_AND_ASSIGN(auto unpartitioned_info,
filesystem->GetFileInfo(unpartitioned));
EXPECT_EQ(unpartitioned_info.type(), fs::FileType::File);
}

fs::FileSelector selector;
selector.base_dir = options.base_dir;
selector.recursive = true;
FileSystemFactoryOptions factory_options;
factory_options.partitioning = partitioning;
factory_options.partition_base_dir = options.base_dir;
factory_options.exclude_invalid_files = true;
ASSERT_OK_AND_ASSIGN(
auto factory,
FileSystemDatasetFactory::Make(filesystem, selector, format, factory_options));
ASSERT_OK_AND_ASSIGN(auto dataset, factory->Finish());
ASSERT_OK_AND_ASSIGN(auto builder, dataset->NewScan());
ASSERT_OK(builder->Project({"year", "value"}));
ASSERT_OK_AND_ASSIGN(auto scanner, builder->Finish());
ASSERT_OK_AND_ASSIGN(auto readback, scanner->ToTable());
ASSERT_OK_AND_ASSIGN(
auto indices, compute::SortIndices(
readback, compute::SortOptions({compute::SortKey("value")})));
ASSERT_OK_AND_ASSIGN(auto sorted, compute::Take(readback, indices));
AssertTablesEqual(*expected, *sorted.table(), /*same_chunk_layout=*/false);
}
}

TEST_F(SimpleWriteNodeTest, DeleteMatchingEmptyFilenamePartition) {
auto data_schema = schema({field("value", int32())});
auto old = TableFromJSON(data_schema, {R"([[-1]])"});
auto updated = TableFromJSON(data_schema, {R"([[1], [2]])"});
auto format = std::make_shared<ParquetFileFormat>();
auto partitioning = std::make_shared<FilenamePartitioning>(schema({}));

auto options = fs_write_options_;
options.partitioning = partitioning;
options.file_write_options = format->DefaultWriteOptions();
options.existing_data_behavior = ExistingDataBehavior::kDeleteMatchingPartitions;
options.basename_template = "old{i}.parquet";
ASSERT_OK(WriteTable(options, old));
options.basename_template = "updated{i}.parquet";
ASSERT_OK(WriteTable(options, updated));

fs::FileSelector selector;
selector.base_dir = options.base_dir;
FileSystemFactoryOptions factory_options;
factory_options.partitioning = partitioning;
factory_options.selector_ignore_prefixes.clear();
ASSERT_OK_AND_ASSIGN(auto factory, FileSystemDatasetFactory::Make(
mock_fs_, selector, format, factory_options));
ASSERT_OK_AND_ASSIGN(auto dataset, factory->Finish());
ASSERT_OK_AND_ASSIGN(auto builder, dataset->NewScan());
ASSERT_OK_AND_ASSIGN(auto scanner, builder->Finish());
ASSERT_OK_AND_ASSIGN(auto readback, scanner->ToTable());
AssertTablesEqual(*updated, *readback, /*same_chunk_layout=*/false);
}
#endif

TEST_F(SimpleWriteNodeTest, CustomNullability) {
// Create an input table with a nullable and a non-nullable type
ExecBatch batch = gen::Gen({gen::Step()})->FailOnError()->ExecBatch(/*num_rows=*/1);
Expand Down
7 changes: 3 additions & 4 deletions python/pyarrow/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -950,10 +950,9 @@ def file_visitor(written_file):
with a unique basename_template for each write, will allow for
an append workflow.

'delete_matching' is useful when you are writing a partitioned
dataset. The first time each partition directory is encountered
the entire directory will be deleted. This allows you to overwrite
old partitions completely.
'delete_matching' replaces each written partition. It clears
partition directories, or deletes matching files of the selected
format for filename partitioning. Use a dedicated dataset directory.
create_dir : bool, default True
If False, directories will not be created. This can be useful for
filesystems that do not require directories.
Expand Down