diff --git a/src/iceberg/CMakeLists.txt b/src/iceberg/CMakeLists.txt index f9604e2575..621ebb1305 100644 --- a/src/iceberg/CMakeLists.txt +++ b/src/iceberg/CMakeLists.txt @@ -27,6 +27,7 @@ set(ICEBERG_SOURCES catalog/session_catalog.cc catalog/session_context.cc data_table_scan.cc + compaction_planner.cc delete_file_index.cc deletes/dv_util.cc deletes/dv_writer.cc @@ -257,6 +258,8 @@ if(MSVC_TOOLCHAIN) endif() set(ICEBERG_DATA_SOURCES + action/compaction_executor.cc + action/position_delete_action.cc data/arrow_batch_sizer.cc data/data_writer.cc data/delete_filter.cc @@ -264,6 +267,7 @@ set(ICEBERG_DATA_SOURCES data/equality_delete_writer.cc data/file_scan_task_reader.cc data/parallel_scan_reader.cc + data/position_deletes.cc data/position_delete_writer.cc data/writer.cc) @@ -306,6 +310,7 @@ iceberg_install_all_headers(iceberg) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/version.h" DESTINATION "${ICEBERG_INSTALL_INCLUDEDIR}/iceberg") +add_subdirectory(action) add_subdirectory(catalog) add_subdirectory(compat) add_subdirectory(data) diff --git a/src/iceberg/action/CMakeLists.txt b/src/iceberg/action/CMakeLists.txt new file mode 100644 index 0000000000..1ac6ab7245 --- /dev/null +++ b/src/iceberg/action/CMakeLists.txt @@ -0,0 +1,18 @@ +# 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. + +iceberg_install_all_headers(iceberg/action) diff --git a/src/iceberg/action/compaction_executor.cc b/src/iceberg/action/compaction_executor.cc new file mode 100644 index 0000000000..a0abac2a9f --- /dev/null +++ b/src/iceberg/action/compaction_executor.cc @@ -0,0 +1,295 @@ +/* + * 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 "iceberg/action/compaction_executor.h" + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "iceberg/arrow_c_data_guard_internal.h" +#include "iceberg/compaction_planner.h" +#include "iceberg/data/data_writer.h" +#include "iceberg/data/file_scan_task_reader.h" +#include "iceberg/data/output_file_cleanup_internal.h" +#include "iceberg/file_format.h" +#include "iceberg/file_io.h" +#include "iceberg/location_provider.h" +#include "iceberg/manifest/manifest_entry.h" +#include "iceberg/metadata_columns.h" +#include "iceberg/partition_spec.h" +#include "iceberg/schema.h" +#include "iceberg/snapshot.h" +#include "iceberg/table.h" +#include "iceberg/table_metadata.h" +#include "iceberg/table_properties.h" +#include "iceberg/table_scan.h" +#include "iceberg/update/rewrite_files.h" +#include "iceberg/util/content_file_util.h" +#include "iceberg/util/data_file_set.h" +#include "iceberg/util/macros.h" +#include "iceberg/util/struct_like_set.h" +#include "iceberg/util/uuid.h" + +namespace iceberg { +namespace { + +Result> Next(ArrowArrayStream& stream) { + ArrowArray batch{}; + if (stream.get_next(&stream, &batch) != 0) { + const char* detail = + stream.get_last_error == nullptr ? nullptr : stream.get_last_error(&stream); + return IOError("Failed to read compaction input: {}", + detail == nullptr ? "unknown stream error" : detail); + } + if (batch.release == nullptr) { + return std::nullopt; + } + return batch; +} + +Result> RewriteSchema(const Table& table) { + ICEBERG_ASSIGN_OR_RAISE(auto table_schema, table.schema()); + if (table.metadata()->format_version < 3) { + return table_schema; + } + + std::vector fields(table_schema->fields().begin(), + table_schema->fields().end()); + fields.push_back(MetadataColumns::kRowId); + fields.push_back(MetadataColumns::kLastUpdatedSequenceNumber); + ICEBERG_ASSIGN_OR_RAISE(auto schema, + Schema::Make(std::move(fields), table_schema->schema_id(), + table_schema->IdentifierFieldIds())); + return std::shared_ptr(std::move(schema)); +} + +} // namespace + +class CompactionExecutor::Impl { + public: + explicit Impl(std::shared_ptr table) : table_(std::move(table)) {} + + Status Execute(const CompactionPlan& plan) { + ICEBERG_PRECHECK(!terminal_, "Compaction executor is no longer usable"); + ICEBERG_RETURN_UNEXPECTED(Cleanup()); + if (plan.groups.empty()) return {}; + auto status = ExecutePlan(plan); + if (!status.has_value()) { + if (status.error().kind != ErrorKind::kCommitStateUnknown) { + return internal::FailWithOutputCleanup(std::move(status.error()), *table_->io(), + output_paths_); + } + terminal_ = true; + } + output_paths_.clear(); + return status; + } + + Status Cleanup() { return internal::CleanupOutputFiles(*table_->io(), output_paths_); } + + private: + Status ExecutePlan(const CompactionPlan& plan) { + ICEBERG_ASSIGN_OR_RAISE(auto inputs, ValidatePlan(plan)); + + ICEBERG_RETURN_UNEXPECTED(table_->Refresh()); + ICEBERG_ASSIGN_OR_RAISE(auto snapshot, table_->current_snapshot()); + if (snapshot->snapshot_id != plan.source_snapshot_id) { + return ValidationFailed( + "Compaction plan snapshot {} is stale; current snapshot is {}", + plan.source_snapshot_id, snapshot->snapshot_id); + } + ICEBERG_ASSIGN_OR_RAISE(auto table_schema, table_->schema()); + ICEBERG_ASSIGN_OR_RAISE(auto rewrite_schema, RewriteSchema(*table_)); + ICEBERG_ASSIGN_OR_RAISE( + auto format, FileFormatTypeFromString( + table_->properties().Get(TableProperties::kDefaultFileFormat))); + ICEBERG_PRECHECK(format != FileFormatType::kPuffin, + "Puffin is not a data file format"); + ICEBERG_ASSIGN_OR_RAISE(auto location_provider, table_->location_provider()); + + std::vector> schemas(table_->metadata()->schemas.begin(), + table_->metadata()->schemas.end()); + ICEBERG_ASSIGN_OR_RAISE(auto reader, FileScanTaskReader::Make({ + .io = table_->io(), + .table_schema = std::move(table_schema), + .schemas = std::move(schemas), + .projected_schema = rewrite_schema, + .properties = table_->properties().configs(), + })); + + std::vector> added_files; + for (size_t group_index = 0; group_index < plan.groups.size(); ++group_index) { + ICEBERG_ASSIGN_OR_RAISE(auto file, + RewriteGroup(plan.groups[group_index], group_index, format, + rewrite_schema, *reader, *location_provider)); + if (file != nullptr) added_files.push_back(std::move(file)); + } + + ICEBERG_ASSIGN_OR_RAISE(auto rewrite, table_->NewRewriteFiles()); + rewrite->ValidateFromSnapshot(plan.source_snapshot_id) + .SetDataSequenceNumber(snapshot->sequence_number) + .Rewrite(inputs.data_files, inputs.delete_files, added_files, {}); + + return rewrite->Commit(); + } + + struct PlanInputs { + std::vector> data_files; + std::vector> delete_files; + }; + + Result ValidatePlan(const CompactionPlan& plan) { + ICEBERG_PRECHECK(plan.source_snapshot_id >= 0, + "Compaction plan snapshot ID must be non-negative"); + + DataFileSet data_files; + DeleteFileSet delete_files; + for (const auto& group : plan.groups) { + ICEBERG_PRECHECK(!group.files.empty(), "Compaction group must contain a file"); + for (const auto& compaction_file : group.files) { + ICEBERG_PRECHECK(compaction_file.scan_task != nullptr, + "Compaction file is missing its scan task"); + const auto& data_file = compaction_file.scan_task->data_file(); + ICEBERG_PRECHECK(data_file != nullptr, + "Compaction scan task is missing data file"); + ICEBERG_PRECHECK(data_file->content == DataFile::Content::kData, + "Compaction input is not a data file: {}", data_file->file_path); + ICEBERG_ASSIGN_OR_RAISE(auto partitions_match, + StructLikeEqual(data_file->partition, group.partition)); + ICEBERG_PRECHECK( + data_file->partition_spec_id == group.partition_spec_id && partitions_match, + "Compaction input does not match its group: {}", data_file->file_path); + ICEBERG_PRECHECK(data_files.insert(data_file).second, + "Duplicate compaction input data file: {}", + data_file->file_path); + + for (const auto& delete_file : compaction_file.scan_task->delete_files()) { + ICEBERG_PRECHECK(delete_file != nullptr, + "Compaction scan task contains a null delete file"); + if (delete_file->content != DataFile::Content::kPositionDeletes) { + continue; + } + ICEBERG_ASSIGN_OR_RAISE(auto referenced_file, + ContentFileUtil::ReferencedDataFile(*delete_file)); + if (referenced_file == data_file->file_path) { + delete_files.insert(delete_file); + } + } + } + } + + return PlanInputs{ + .data_files = + std::vector>(data_files.begin(), data_files.end()), + .delete_files = std::vector>(delete_files.begin(), + delete_files.end()), + }; + } + + Result> RewriteGroup( + const CompactionGroup& group, size_t group_index, FileFormatType format, + const std::shared_ptr& rewrite_schema, FileScanTaskReader& reader, + LocationProvider& location_provider) { + ICEBERG_ASSIGN_OR_RAISE( + auto spec, table_->metadata()->PartitionSpecById(group.partition_spec_id)); + + std::unique_ptr writer; + for (const auto& compaction_file : group.files) { + const auto& data_file = compaction_file.scan_task->data_file(); + FileScanTask task(data_file, compaction_file.scan_task->delete_files(), + /*filter=*/nullptr, spec); + ICEBERG_ASSIGN_OR_RAISE(auto stream, reader.Open(task)); + nanoarrow::UniqueArrayStream stream_guard; + ArrowArrayStreamMove(&stream, stream_guard.get()); + while (true) { + ICEBERG_ASSIGN_OR_RAISE(auto batch, Next(*stream_guard.get())); + if (!batch.has_value()) { + break; + } + + internal::ArrowArrayGuard batch_guard(&batch.value()); + if (batch->length == 0) { + continue; + } + if (writer == nullptr) { + const auto filename = + std::format("compacted-{}-{}.{}", Uuid::GenerateV7().ToString(), + group_index, ToString(format)); + ICEBERG_ASSIGN_OR_RAISE( + auto output_path, + location_provider.NewDataLocation(*spec, group.partition, filename)); + output_paths_.insert(output_path); + ICEBERG_ASSIGN_OR_RAISE(writer, + DataWriter::Make({ + .path = output_path, + .schema = rewrite_schema, + .spec = spec, + .partition = group.partition, + .format = format, + .io = table_->io(), + .properties = table_->properties().configs(), + })); + } + batch_guard.Release(); + ICEBERG_RETURN_UNEXPECTED(writer->Write(&batch.value())); + } + } + + if (writer != nullptr) { + ICEBERG_RETURN_UNEXPECTED(writer->Close()); + ICEBERG_ASSIGN_OR_RAISE(auto metadata, writer->Metadata()); + ICEBERG_PRECHECK(metadata.data_files.size() == 1, + "Compaction writer produced {} data files", + metadata.data_files.size()); + return std::move(metadata.data_files.front()); + } + return nullptr; + } + + std::shared_ptr
table_; + std::set output_paths_; + bool terminal_ = false; +}; + +CompactionExecutor::CompactionExecutor(std::unique_ptr impl) + : impl_(std::move(impl)) {} + +CompactionExecutor::~CompactionExecutor() = default; + +Result> CompactionExecutor::Make( + std::shared_ptr
table) { + ICEBERG_PRECHECK(table != nullptr, "Cannot create compaction executor without table"); + return std::unique_ptr( + new CompactionExecutor(std::make_unique(std::move(table)))); +} + +Status CompactionExecutor::Execute(const CompactionPlan& plan) { + return impl_->Execute(plan); +} + +Status CompactionExecutor::Cleanup() { return impl_->Cleanup(); } + +} // namespace iceberg diff --git a/src/iceberg/action/compaction_executor.h b/src/iceberg/action/compaction_executor.h new file mode 100644 index 0000000000..90babd4c8f --- /dev/null +++ b/src/iceberg/action/compaction_executor.h @@ -0,0 +1,82 @@ +/* + * 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. + */ + +#pragma once + +/// \file iceberg/action/compaction_executor.h +/// Execute planned data-file compaction. + +#include + +#include "iceberg/iceberg_data_export.h" +#include "iceberg/result.h" +#include "iceberg/type_fwd.h" + +namespace iceberg { + +struct CompactionPlan; + +/// \brief Executes a snapshot-bound data-file compaction plan. +/// +/// The executor reads every planned source file through the delete-aware scan reader, +/// writes replacement data files, and commits all data and file-scoped position-delete +/// replacements in one table update. Generated files remain owned by the executor until +/// commit succeeds, commit state becomes unknown, or cleanup deletes them. +class ICEBERG_DATA_EXPORT CompactionExecutor { + public: + /// \brief Destroy the executor. + ~CompactionExecutor(); + + /// \brief Create an executor for a table. + /// + /// \param table Table whose files and metadata will be rewritten. + /// \return A new executor, or an error if table is null. + static Result> Make(std::shared_ptr
table); + + /// \brief Rewrite and atomically commit a snapshot-bound compaction plan. + /// + /// An empty plan is a no-op without writing or committing. + /// Execution refreshes the table and rejects non-empty plans whose snapshot is no + /// longer current before writing. Commit validation also rejects deletes added after + /// the plan snapshot. A definite failure attempts to clean generated files; cleanup + /// failures are appended to the original error and undeleted files remain owned by + /// this executor. + /// + /// \param plan Planner output containing the source snapshot and compaction groups. + /// \return Success after commit, or the original planning, IO, validation, or commit + /// error, including cleanup details when cleanup also fails. + Status Execute(const CompactionPlan& plan); + + /// \brief Retry deletion of uncommitted output files owned by this executor. + /// + /// Successfully deleted or absent paths are released. Paths whose deletion fails + /// remain owned and may be retried by calling Cleanup again. + /// + /// \return Success when every owned output is deleted, otherwise the first cleanup + /// error. + Status Cleanup(); + + private: + class Impl; + std::unique_ptr impl_; + + explicit CompactionExecutor(std::unique_ptr impl); +}; + +} // namespace iceberg diff --git a/src/iceberg/action/position_delete_action.cc b/src/iceberg/action/position_delete_action.cc new file mode 100644 index 0000000000..d9ffaaaa5a --- /dev/null +++ b/src/iceberg/action/position_delete_action.cc @@ -0,0 +1,55 @@ +/* + * 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 +#include +#include + +#include "iceberg/action/position_delete_action_internal.h" +#include "iceberg/data/output_file_cleanup_internal.h" +#include "iceberg/table.h" +#include "iceberg/update/row_delta.h" + +namespace iceberg::internal { + +Status CommitPositionDeletes(const Table& table, RowDelta& delta, + int64_t scan_snapshot_id, + const std::shared_ptr& scan_io, + std::vector files) { + std::set outputs; + auto written = WritePositionDeletes(table, scan_io, std::move(files), outputs); + if (!written) { + return FailWithOutputCleanup(std::move(written.error()), *table.io(), outputs); + } + if (written->data_files.empty()) return {}; + + delta.ValidateFromSnapshot(scan_snapshot_id) + .ValidateDataFilesExist(written->referenced_data_files) + .ValidateDeletedFiles(); + for (const auto& file : written->data_files) delta.AddDeletes(file); + for (const auto& file : written->rewritten_delete_files) delta.RemoveDeletes(file); + + auto status = delta.Commit(); + if (!status && status.error().kind != ErrorKind::kCommitStateUnknown) { + return FailWithOutputCleanup(std::move(status.error()), *table.io(), outputs); + } + return status; +} + +} // namespace iceberg::internal diff --git a/src/iceberg/action/position_delete_action_internal.h b/src/iceberg/action/position_delete_action_internal.h new file mode 100644 index 0000000000..281009e8d6 --- /dev/null +++ b/src/iceberg/action/position_delete_action_internal.h @@ -0,0 +1,37 @@ +/* + * 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. + */ + +#pragma once + +#include +#include +#include + +#include "iceberg/data/position_deletes_internal.h" + +namespace iceberg::internal { + +// Write positions from the original scan and commit them through a fresh RowDelta. +// The caller may configure conflict detection on the delta before invoking the action. +ICEBERG_DATA_EXPORT Status CommitPositionDeletes(const Table& table, RowDelta& delta, + int64_t scan_snapshot_id, + const std::shared_ptr& scan_io, + std::vector files); + +} // namespace iceberg::internal diff --git a/src/iceberg/arrow/arrow_io.cc b/src/iceberg/arrow/arrow_io.cc index 998f8c5ce8..a04693d127 100644 --- a/src/iceberg/arrow/arrow_io.cc +++ b/src/iceberg/arrow/arrow_io.cc @@ -18,6 +18,7 @@ */ #include +#include #include #include #include @@ -30,6 +31,7 @@ #include #include #include +#include #include #include "iceberg/arrow/arrow_io_internal.h" @@ -448,6 +450,20 @@ class ArrowInputFile : public InputFile { std::optional file_size_; }; +// Hierarchical filesystems require the partition directory to exist. Keep the +// ordinary write path to one open, including for object stores with virtual directories. +::arrow::Result> OpenOutputWithParent( + ::arrow::fs::FileSystem& fs, const std::string& path) { + auto output = fs.OpenOutputStream(path); + if (output.ok()) return output; + const auto parent = ::arrow::fs::FileInfo(path).dir_name(); + if (parent.empty()) return output; + auto info = fs.GetFileInfo(parent); + if (!info.ok() || info->type() != ::arrow::fs::FileType::NotFound) return output; + ARROW_RETURN_NOT_OK(fs.CreateDir(parent)); + return fs.OpenOutputStream(path); +} + class ArrowOutputFile : public OutputFile { public: ArrowOutputFile(std::shared_ptr<::arrow::fs::FileSystem> fs, std::string location, @@ -472,7 +488,7 @@ class ArrowOutputFile : public OutputFile { return AlreadyExists("File already exists: {}", location_); } } - ICEBERG_ARROW_ASSIGN_OR_RETURN(auto output, fs_->OpenOutputStream(path_)); + ICEBERG_ARROW_ASSIGN_OR_RETURN(auto output, OpenOutputWithParent(*fs_, path_)); return std::make_unique(std::move(output)); } @@ -551,8 +567,8 @@ Result> OpenArrowOutputStream( return AlreadyExists("File already exists: {}", path); } } - ICEBERG_ARROW_ASSIGN_OR_RETURN(auto output, - arrow_io->arrow_fs_->OpenOutputStream(resolved_path)); + ICEBERG_ARROW_ASSIGN_OR_RETURN( + auto output, OpenOutputWithParent(*arrow_io->arrow_fs_, resolved_path)); return output; } @@ -591,7 +607,11 @@ Result> ArrowFileSystemFileIO::NewOutputFile( /// \brief Delete a file at the given location. Status ArrowFileSystemFileIO::DeleteFile(const std::string& file_location) { ICEBERG_ASSIGN_OR_RAISE(auto path, ResolvePath(file_location)); - ICEBERG_ARROW_RETURN_NOT_OK(arrow_fs_->DeleteFile(path)); + auto status = arrow_fs_->DeleteFile(path); + if (::arrow::internal::ErrnoFromStatus(status) == ENOENT) { + return {}; + } + ICEBERG_ARROW_RETURN_NOT_OK(status); return {}; } diff --git a/src/iceberg/compaction_planner.cc b/src/iceberg/compaction_planner.cc new file mode 100644 index 0000000000..7039fb0c37 --- /dev/null +++ b/src/iceberg/compaction_planner.cc @@ -0,0 +1,310 @@ +/* + * 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 "iceberg/compaction_planner.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "iceberg/expression/literal.h" +#include "iceberg/manifest/manifest_entry.h" +#include "iceberg/table_scan.h" +#include "iceberg/util/content_file_util.h" +#include "iceberg/util/data_file_set.h" +#include "iceberg/util/macros.h" + +namespace iceberg { +namespace { + +struct CanonicalPartitionKey { + int32_t spec_id; + std::string values; + + auto operator<=>(const CanonicalPartitionKey&) const = default; +}; + +struct Candidate { + CompactionFile file; + bool has_delete_pressure; +}; + +struct PartitionCandidates { + int32_t spec_id; + std::vector files; +}; + +Status ValidateConfig(const CompactionPlannerConfig& config) { + ICEBERG_PRECHECK(config.target_file_size_bytes > 0, + "target_file_size_bytes must be greater than zero"); + ICEBERG_PRECHECK(std::isfinite(config.min_file_size_ratio) && + config.min_file_size_ratio >= 0 && config.min_file_size_ratio <= 1, + "min_file_size_ratio must be finite and in [0, 1]"); + ICEBERG_PRECHECK(config.min_input_files > 0, + "min_input_files must be greater than zero"); + ICEBERG_PRECHECK(config.delete_file_threshold >= 0, + "delete_file_threshold must not be negative"); + ICEBERG_PRECHECK(std::isfinite(config.delete_ratio_threshold) && + config.delete_ratio_threshold >= 0 && + config.delete_ratio_threshold <= 1, + "delete_ratio_threshold must be finite and in [0, 1]"); + return {}; +} + +Result CheckedAddNonNegative(int64_t lhs, int64_t rhs, + std::string_view description) { + ICEBERG_PRECHECK(lhs >= 0 && rhs >= 0, "{} must not be negative", description); + ICEBERG_PRECHECK(lhs <= std::numeric_limits::max() - rhs, "{} overflow", + description); + return lhs + rhs; +} + +void AppendFramed(std::string& output, std::string_view value) { + output.append(std::to_string(value.size())); + output.push_back(':'); + output.append(value); +} + +Result MakePartitionKey(const DataFile& data_file) { + ICEBERG_PRECHECK(data_file.partition_spec_id.has_value(), + "Data file '{}' is missing partition_spec_id", data_file.file_path); + + std::string encoded; + encoded.append(std::to_string(data_file.partition.num_fields())); + encoded.push_back(':'); + for (const auto& literal : data_file.partition.values()) { + AppendFramed(encoded, literal.type()->ToString()); + if (literal.IsNull()) { + encoded.push_back('N'); + continue; + } + + encoded.push_back('V'); + if (literal.IsNaN()) { + encoded.push_back('N'); + continue; + } + + encoded.push_back('B'); + ICEBERG_ASSIGN_OR_RAISE(auto bytes, literal.Serialize()); + std::string_view serialized; + if (!bytes.empty()) { + serialized = + std::string_view(reinterpret_cast(bytes.data()), bytes.size()); + } + AppendFramed(encoded, serialized); + } + return CanonicalPartitionKey{.spec_id = *data_file.partition_spec_id, + .values = std::move(encoded)}; +} + +Result BuildCompactionFile( + const std::shared_ptr& scan_task) { + CompactionFile result{.scan_task = scan_task}; + const auto& data_file = scan_task->data_file(); + ICEBERG_PRECHECK(data_file->record_count >= 0, + "Data file '{}' has negative record count", data_file->file_path); + ICEBERG_PRECHECK(data_file->file_size_in_bytes >= 0, + "Data file '{}' has negative file size", data_file->file_path); + + DeleteFileSet applicable_deletes; + for (const auto& delete_file : scan_task->delete_files()) { + ICEBERG_PRECHECK(delete_file != nullptr, "Data file '{}' has a null delete file", + data_file->file_path); + if (delete_file->content != DataFile::Content::kPositionDeletes) { + continue; + } + + ICEBERG_ASSIGN_OR_RAISE(auto referenced_file, + ContentFileUtil::ReferencedDataFile(*delete_file)); + if (!referenced_file.has_value() || *referenced_file != data_file->file_path) { + continue; + } + + if (!applicable_deletes.insert(delete_file).second) { + continue; + } + + ICEBERG_PRECHECK(delete_file->record_count >= 0, + "Delete file '{}' has negative record count", + delete_file->file_path); + if (delete_file->IsDeletionVector()) { + ICEBERG_PRECHECK( + delete_file->record_count <= data_file->record_count, + "Deletion vector '{}' cardinality {} exceeds data file '{}' record count {}", + delete_file->file_path, delete_file->record_count, data_file->file_path, + data_file->record_count); + } + + ++result.file_scoped_delete_count; + ICEBERG_ASSIGN_OR_RAISE(result.file_scoped_delete_record_count, + CheckedAddNonNegative(result.file_scoped_delete_record_count, + delete_file->record_count, + "File-scoped delete-record count")); + } + + result.file_scoped_delete_record_count = + std::min(result.file_scoped_delete_record_count, data_file->record_count); + return result; +} + +bool CompactionFileLess(const CompactionFile& lhs, const CompactionFile& rhs) { + return lhs.scan_task->data_file()->file_path < rhs.scan_task->data_file()->file_path; +} + +bool CandidateLess(const Candidate& lhs, const Candidate& rhs) { + return CompactionFileLess(lhs.file, rhs.file); +} + +bool PackingCandidateLess(const Candidate& lhs, const Candidate& rhs) { + const int64_t lhs_size = lhs.file.scan_task->data_file()->file_size_in_bytes; + const int64_t rhs_size = rhs.file.scan_task->data_file()->file_size_in_bytes; + return lhs_size != rhs_size ? lhs_size > rhs_size : CandidateLess(lhs, rhs); +} + +Result AddToGroup(CompactionGroup& group, Candidate candidate, + bool& has_delete_pressure) { + const auto& data_file = *candidate.file.scan_task->data_file(); + // Packing only adds files that fit, except for a single oversized file. + group.data_file_size_bytes += data_file.file_size_in_bytes; + ICEBERG_ASSIGN_OR_RAISE( + group.file_scoped_delete_record_count, + CheckedAddNonNegative(group.file_scoped_delete_record_count, + candidate.file.file_scoped_delete_record_count, + "Compaction group delete-record count")); + has_delete_pressure |= candidate.has_delete_pressure; + group.files.push_back(std::move(candidate.file)); + return {}; +} + +struct PendingGroup { + CompactionGroup group; + bool has_delete_pressure = false; +}; + +Result> PackPartition( + PartitionCandidates partition, const CompactionPlannerConfig& config) { + const auto representative = std::ranges::min_element(partition.files, CandidateLess) + ->file.scan_task->data_file() + ->partition; + std::ranges::sort(partition.files, PackingCandidateLess); + + std::vector bins; + // Smallest sufficient capacity first; bin index breaks ties deterministically. + std::set> available_bins; + for (auto& candidate : partition.files) { + const int64_t file_size = candidate.file.scan_task->data_file()->file_size_in_bytes; + size_t best_bin = bins.size(); + auto bin = available_bins.lower_bound({file_size, 0}); + if (bin != available_bins.end()) { + best_bin = bin->second; + available_bins.erase(bin); + } + + if (best_bin == bins.size()) { + bins.push_back(PendingGroup{ + .group = CompactionGroup{.partition_spec_id = partition.spec_id, + .partition = representative}, + }); + best_bin = bins.size() - 1; + } + ICEBERG_RETURN_UNEXPECTED(AddToGroup(bins[best_bin].group, std::move(candidate), + bins[best_bin].has_delete_pressure)); + const int64_t bin_size = bins[best_bin].group.data_file_size_bytes; + if (bin_size <= config.target_file_size_bytes) { + available_bins.emplace(config.target_file_size_bytes - bin_size, best_bin); + } + } + + std::vector groups; + for (auto& bin : bins) { + if (!bin.has_delete_pressure && bin.group.files.size() < config.min_input_files) { + continue; + } + std::ranges::sort(bin.group.files, CompactionFileLess); + groups.push_back(std::move(bin.group)); + } + std::ranges::sort(groups, [](const CompactionGroup& lhs, const CompactionGroup& rhs) { + return CompactionFileLess(lhs.files.front(), rhs.files.front()); + }); + return groups; +} + +} // namespace + +Result CompactionPlanner::Plan( + int64_t source_snapshot_id, std::span> scan_tasks, + const CompactionPlannerConfig& config) { + ICEBERG_PRECHECK(source_snapshot_id >= 0, "source_snapshot_id must not be negative"); + ICEBERG_RETURN_UNEXPECTED(ValidateConfig(config)); + std::map partitions; + DataFileSet seen_data_files; + + for (const auto& scan_task : scan_tasks) { + ICEBERG_PRECHECK(scan_task != nullptr, "File scan task must not be null"); + ICEBERG_PRECHECK(scan_task->data_file() != nullptr, + "File scan task data file must not be null"); + const auto& data_file = *scan_task->data_file(); + ICEBERG_PRECHECK(seen_data_files.insert(scan_task->data_file()).second, + "Duplicate scan task for data file '{}'", data_file.file_path); + ICEBERG_ASSIGN_OR_RAISE(auto partition_key, MakePartitionKey(data_file)); + ICEBERG_ASSIGN_OR_RAISE(auto file, BuildCompactionFile(scan_task)); + + const bool is_small = + static_cast(data_file.file_size_in_bytes) < + static_cast(config.target_file_size_bytes) * config.min_file_size_ratio; + const bool has_many_delete_files = + config.delete_file_threshold > 0 && + file.file_scoped_delete_count >= config.delete_file_threshold; + const bool has_high_delete_ratio = + config.delete_ratio_threshold > 0 && data_file.record_count > 0 && + static_cast(file.file_scoped_delete_record_count) / + static_cast(data_file.record_count) >= + config.delete_ratio_threshold; + const bool has_delete_pressure = has_many_delete_files || has_high_delete_ratio; + if (!is_small && !has_delete_pressure) { + continue; + } + + auto partition = + partitions + .try_emplace(std::move(partition_key), + PartitionCandidates{.spec_id = *data_file.partition_spec_id}) + .first; + partition->second.files.push_back( + Candidate{.file = std::move(file), .has_delete_pressure = has_delete_pressure}); + } + + CompactionPlan plan{.source_snapshot_id = source_snapshot_id}; + for (auto& [_, partition] : partitions) { + ICEBERG_ASSIGN_OR_RAISE(auto groups, PackPartition(std::move(partition), config)); + plan.groups.insert(plan.groups.end(), std::make_move_iterator(groups.begin()), + std::make_move_iterator(groups.end())); + } + return plan; +} + +} // namespace iceberg diff --git a/src/iceberg/compaction_planner.h b/src/iceberg/compaction_planner.h new file mode 100644 index 0000000000..ac71fdf46d --- /dev/null +++ b/src/iceberg/compaction_planner.h @@ -0,0 +1,121 @@ +/* + * 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. + */ + +#pragma once + +/// \file iceberg/compaction_planner.h +/// Plan data-file compaction without executing rewrites. + +#include +#include +#include +#include +#include + +#include "iceberg/iceberg_export.h" +#include "iceberg/result.h" +#include "iceberg/row/partition_values.h" +#include "iceberg/type_fwd.h" + +namespace iceberg { + +/// \brief Thresholds used to select data files for compaction. +/// Ratio thresholds use double-precision heuristic comparisons. +struct ICEBERG_EXPORT CompactionPlannerConfig { + /// Desired aggregate data-file size for each compaction group. + /// + /// A single selected file may exceed this size. + int64_t target_file_size_bytes = int64_t{512} * 1024 * 1024; + + /// Files smaller than this ratio of the target size are small-file candidates. + double min_file_size_ratio = 0.75; + + /// Minimum number of files required for a group containing only small-file candidates. + size_t min_input_files = 5; + + /// Minimum number of applicable file-scoped position delete files. + /// + /// A value of zero disables this selection criterion. + int64_t delete_file_threshold = 2; + + /// Minimum ratio of deleted records to data-file records. + /// + /// A value of zero disables this selection criterion. + double delete_ratio_threshold = 0.3; +}; + +/// \brief A selected data file and its file-scoped delete pressure. +struct ICEBERG_EXPORT CompactionFile { + /// Scan task for the selected data file and its applicable delete files. + std::shared_ptr scan_task; + + /// Number of distinct applicable file-scoped position delete files. + int64_t file_scoped_delete_count = 0; + + /// Number of deleted records, capped at the data file's record count. + int64_t file_scoped_delete_record_count = 0; +}; + +/// \brief Selected files from one partition that can be rewritten together. +struct ICEBERG_EXPORT CompactionGroup { + /// Partition spec ID shared by every file in this group. + int32_t partition_spec_id; + + /// Partition tuple shared by every file in this group. + PartitionValues partition; + + /// Selected files in canonical file-path order. + std::vector files; + + /// Aggregate size of the selected data files. + int64_t data_file_size_bytes = 0; + + /// Aggregate file-scoped deleted-record count. + int64_t file_scoped_delete_record_count = 0; +}; + +/// \brief Result of compaction planning. +struct ICEBERG_EXPORT CompactionPlan { + /// Snapshot whose scan tasks were used to produce this plan. + /// + /// An executor must verify this snapshot is still valid before rewriting files. + int64_t source_snapshot_id; + + /// Compaction groups in canonical partition and file order. + std::vector groups; +}; + +/// \brief Select and group scan tasks for data-file compaction. +class ICEBERG_EXPORT CompactionPlanner { + public: + /// \brief Plan deterministic, partition-isolated compaction groups. + /// + /// \param source_snapshot_id Non-negative snapshot whose scan tasks are being planned. + /// \param scan_tasks Data-file scan tasks with applicable delete files. + /// \param config Candidate selection and group sizing thresholds. + /// \return A metadata-only compaction plan, or an error for invalid configuration, + /// snapshot ID, duplicate data-file tasks, metadata, partition keys, delete + /// cardinality, or aggregate overflow. + static Result Plan( + int64_t source_snapshot_id, + std::span> scan_tasks, + const CompactionPlannerConfig& config = {}); +}; + +} // namespace iceberg diff --git a/src/iceberg/cpp20_compatibility_internal.h b/src/iceberg/cpp20_compatibility_internal.h index 93d716e950..b8f24d4006 100644 --- a/src/iceberg/cpp20_compatibility_internal.h +++ b/src/iceberg/cpp20_compatibility_internal.h @@ -24,12 +24,14 @@ #pragma once +#include "iceberg/action/compaction_executor.h" #include "iceberg/arrow_c_data.h" #include "iceberg/catalog.h" #include "iceberg/catalog/catalog_util.h" #include "iceberg/catalog/memory/in_memory_catalog.h" #include "iceberg/catalog/session_catalog.h" #include "iceberg/catalog/session_context.h" +#include "iceberg/compaction_planner.h" #include "iceberg/compat/byte_swap.h" #include "iceberg/compat/compiler.h" #include "iceberg/compat/expected.h" diff --git a/src/iceberg/data/output_file_cleanup_internal.h b/src/iceberg/data/output_file_cleanup_internal.h new file mode 100644 index 0000000000..e1c0db16f0 --- /dev/null +++ b/src/iceberg/data/output_file_cleanup_internal.h @@ -0,0 +1,56 @@ +/* + * 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. + */ + +#pragma once + +#include +#include +#include + +#include "iceberg/file_io.h" +#include "iceberg/result.h" + +namespace iceberg::internal { + +// Try every owned output, keeping failed paths for a subsequent cleanup attempt. +inline Status CleanupOutputFiles(FileIO& io, std::set& paths) { + Status first_error; + for (auto it = paths.begin(); it != paths.end();) { + auto status = io.DeleteFile(*it); + if (status.has_value()) { + it = paths.erase(it); + } else { + if (first_error.has_value()) first_error = std::move(status); + ++it; + } + } + return first_error; +} + +// Preserve the operation's error kind while reporting a cleanup failure, if any. +inline Status FailWithOutputCleanup(Error error, FileIO& io, + std::set& paths) { + auto cleanup = CleanupOutputFiles(io, paths); + if (!cleanup.has_value()) { + error.message += "; output cleanup failed: " + cleanup.error().message; + } + return iceberg::unexpected(std::move(error)); +} + +} // namespace iceberg::internal diff --git a/src/iceberg/data/position_deletes.cc b/src/iceberg/data/position_deletes.cc new file mode 100644 index 0000000000..0b6945e4d2 --- /dev/null +++ b/src/iceberg/data/position_deletes.cc @@ -0,0 +1,170 @@ +/* + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "iceberg/data/delete_loader.h" +#include "iceberg/data/position_delete_writer.h" +#include "iceberg/data/position_deletes_internal.h" +#include "iceberg/deletes/dv_writer.h" +#include "iceberg/file_format.h" +#include "iceberg/file_io.h" +#include "iceberg/location_provider.h" +#include "iceberg/manifest/manifest_entry.h" +#include "iceberg/partition_spec.h" +#include "iceberg/schema.h" +#include "iceberg/table.h" +#include "iceberg/table_metadata.h" +#include "iceberg/table_properties.h" +#include "iceberg/table_scan.h" +#include "iceberg/util/macros.h" +#include "iceberg/util/uuid.h" + +namespace iceberg::internal { +namespace { + +Result WriteParquetDeletes(const Table& table, + std::vector& files, + std::set& output_paths) { + ICEBERG_ASSIGN_OR_RAISE(auto location_provider, table.location_provider()); + ICEBERG_ASSIGN_OR_RAISE(auto schema, table.schema()); + + DeleteWriteResult result; + result.data_files.reserve(files.size()); + result.referenced_data_files.reserve(files.size()); + auto properties = table.properties().configs(); + properties[TableProperties::kParquetCompression.key()] = + table.properties().Get(TableProperties::kDeleteParquetCompression); + properties[TableProperties::kParquetCompressionLevel.key()] = + table.properties().Get(TableProperties::kDeleteParquetCompressionLevel); + const auto write_uuid = Uuid::GenerateV7().ToString(); + size_t file_number = 0; + + for (auto& [task, positions] : files) { + const auto& data_file = *task->data_file(); + const auto& path = data_file.file_path; + std::ranges::sort(positions); + + ICEBERG_ASSIGN_OR_RAISE(auto spec, table.metadata()->PartitionSpecById( + data_file.partition_spec_id.value())); + const auto filename = + std::format("position-deletes-{}-{}.parquet", write_uuid, file_number++); + auto output_path = location_provider->NewDataLocation(filename); + output_paths.insert(output_path); + + ICEBERG_ASSIGN_OR_RAISE(auto writer, + PositionDeleteWriter::Make(PositionDeleteWriterOptions{ + .path = output_path, + .schema = schema, + .spec = spec, + .partition = data_file.partition, + .format = FileFormatType::kParquet, + .io = table.io(), + .properties = properties, + })); + for (int64_t pos : positions) { + ICEBERG_RETURN_UNEXPECTED(writer->WriteDelete(path, pos)); + } + ICEBERG_RETURN_UNEXPECTED(writer->Close()); + ICEBERG_ASSIGN_OR_RAISE(auto metadata, writer->Metadata()); + result.data_files.insert(result.data_files.end(), + std::make_move_iterator(metadata.data_files.begin()), + std::make_move_iterator(metadata.data_files.end())); + result.referenced_data_files.push_back(path); + } + return result; +} + +Result WriteDeletionVectors( + const Table& table, const std::shared_ptr& scan_io, + const std::vector& files, std::set& output_paths) { + ICEBERG_ASSIGN_OR_RAISE(auto locations, table.location_provider()); + auto path = locations->NewDataLocation( + std::format("position-deletes-{}.puffin", Uuid::GenerateV7().ToString())); + output_paths.insert(path); + std::unordered_map>> previous; + for (const auto& file : files) { + for (const auto& entry : file.task->delete_files()) { + if (entry->content == DataFile::Content::kPositionDeletes) { + previous[file.task->data_file()->file_path].push_back(entry); + } + } + } + DeleteLoader loader(scan_io); + ICEBERG_ASSIGN_OR_RAISE( + auto writer, + DVWriter::Make({.path = path, + .io = table.io(), + .load_previous_deletes = [&](std::string_view target) + -> Result> { + auto it = previous.find(target); + if (it == previous.end()) return std::nullopt; + ICEBERG_ASSIGN_OR_RAISE( + auto index, loader.LoadPositionDeletes(it->second, target)); + return std::optional(std::move(index)); + }})); + for (const auto& [task, positions] : files) { + const auto& file = *task->data_file(); + ICEBERG_ASSIGN_OR_RAISE( + auto spec, table.metadata()->PartitionSpecById(file.partition_spec_id.value())); + for (int64_t pos : positions) { + ICEBERG_RETURN_UNEXPECTED( + writer->Delete(file.file_path, pos, spec, file.partition)); + } + } + ICEBERG_RETURN_UNEXPECTED(writer->Close()); + return writer->Metadata(); +} + +} // namespace + +Result WritePositionDeletes(const Table& table, + const std::shared_ptr& scan_io, + std::vector files, + std::set& output_paths) { + const auto version = table.metadata()->format_version; + ICEBERG_PRECHECK(version >= 2, + "Position deletes require table format version 2 or later"); + std::erase_if(files, [](const auto& file) { return file.positions.empty(); }); + if (files.empty()) return DeleteWriteResult{}; + for (const auto& [task, positions] : files) { + const auto& file = *task->data_file(); + ICEBERG_PRECHECK(file.partition_spec_id.has_value(), + "Missing partition spec ID for {}", file.file_path); + for (int64_t pos : positions) { + ICEBERG_PRECHECK(pos >= 0 && pos < file.record_count, + "Invalid position {} for {} ({} rows)", pos, file.file_path, + file.record_count); + } + } + return version >= 3 ? WriteDeletionVectors(table, scan_io, files, output_paths) + : WriteParquetDeletes(table, files, output_paths); +} + +} // namespace iceberg::internal diff --git a/src/iceberg/data/position_deletes_internal.h b/src/iceberg/data/position_deletes_internal.h new file mode 100644 index 0000000000..d11dd2fa5d --- /dev/null +++ b/src/iceberg/data/position_deletes_internal.h @@ -0,0 +1,46 @@ +/* + * 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. + */ + +#pragma once + +#include +#include +#include +#include +#include + +#include "iceberg/deletes/dv_writer.h" +#include "iceberg/iceberg_data_export.h" + +namespace iceberg::internal { + +// Group absolute row positions by data file using a task from the original scan. +struct FilePositionDeletes { + std::shared_ptr task; + std::vector positions; +}; + +// Write one group per target file. Read previous deletes with the planned scan's +// FileIO and write new outputs with the table's FileIO. The caller owns output_paths +// until commit and validates its RowDelta against the snapshot used for planning. +ICEBERG_DATA_EXPORT Result WritePositionDeletes( + const Table& table, const std::shared_ptr& scan_io, + std::vector files, std::set& output_paths); + +} // namespace iceberg::internal diff --git a/src/iceberg/file_io.h b/src/iceberg/file_io.h index 79faaacbb8..b7caa4c1d6 100644 --- a/src/iceberg/file_io.h +++ b/src/iceberg/file_io.h @@ -164,6 +164,9 @@ class ICEBERG_EXPORT FileIO { /// \brief Delete a file at the given location. /// + /// Deletion is idempotent: implementations must return success when the file does + /// not exist. + /// /// \param file_location The location of the file to delete. /// \return Status indicating success, or an error if the delete failed. virtual Status DeleteFile(const std::string& /*file_location*/) { diff --git a/src/iceberg/row/partition_values.cc b/src/iceberg/row/partition_values.cc index edf55a7725..63d47af766 100644 --- a/src/iceberg/row/partition_values.cc +++ b/src/iceberg/row/partition_values.cc @@ -19,10 +19,6 @@ #include "iceberg/row/partition_values.h" -#include - -#include "iceberg/util/uuid.h" - namespace iceberg { PartitionValues& PartitionValues::operator=(const PartitionValues& other) { @@ -43,52 +39,7 @@ Result PartitionValues::GetField(size_t pos) const { values_.size()); } - const auto& literal = values_[pos]; - - // Handle null values - if (literal.IsNull()) { - return Scalar{std::monostate{}}; - } - - // Convert Literal to Scalar based on type - switch (literal.type()->type_id()) { - case TypeId::kBoolean: - return Scalar{std::get(literal.value())}; - case TypeId::kInt: - case TypeId::kDate: - return Scalar{std::get(literal.value())}; - case TypeId::kLong: - case TypeId::kTime: - case TypeId::kTimestamp: - case TypeId::kTimestampTz: - case TypeId::kTimestampNs: - case TypeId::kTimestampTzNs: - return Scalar{std::get(literal.value())}; - case TypeId::kFloat: - return Scalar{std::get(literal.value())}; - case TypeId::kDouble: - return Scalar{std::get(literal.value())}; - case TypeId::kString: { - const auto& str = std::get(literal.value()); - return Scalar{std::string_view(str)}; - } - case TypeId::kBinary: - case TypeId::kFixed: { - const auto& bytes = std::get>(literal.value()); - return Scalar{ - std::string_view(reinterpret_cast(bytes.data()), bytes.size())}; - } - case TypeId::kUuid: { - const auto bytes = std::get(literal.value()).bytes(); - return Scalar{ - std::string_view(reinterpret_cast(bytes.data()), bytes.size())}; - } - case TypeId::kDecimal: - return Scalar{std::get(literal.value())}; - default: - return NotSupported("Cannot convert literal of type {} to Scalar", - literal.type()->ToString()); - } + return LiteralToScalar(values_[pos]); } Result> PartitionValues::ValueAt(size_t pos) const { diff --git a/src/iceberg/test/CMakeLists.txt b/src/iceberg/test/CMakeLists.txt index 125ba128a3..89de75fb43 100644 --- a/src/iceberg/test/CMakeLists.txt +++ b/src/iceberg/test/CMakeLists.txt @@ -212,6 +212,8 @@ add_iceberg_test(puffin_test puffin_json_test.cc puffin_reader_writer_test.cc) +add_iceberg_test(compaction_planner_test SOURCES compaction_planner_test.cc) + if(ICEBERG_BUILD_BUNDLE) add_iceberg_test(avro_test USE_BUNDLE @@ -339,12 +341,14 @@ if(ICEBERG_BUILD_BUNDLE) SOURCES arrow_c_data_util_test.cc arrow_row_builder_test.cc + compaction_executor_test.cc data_writer_test.cc default_value_test.cc delete_filter_test.cc delete_loader_test.cc dv_writer_test.cc file_scan_task_reader_test.cc + position_delete_update_test.cc literal_util_test.cc) endif() diff --git a/src/iceberg/test/arrow_io_test.cc b/src/iceberg/test/arrow_io_test.cc index 7bc9ebba53..6b3f6e4dd4 100644 --- a/src/iceberg/test/arrow_io_test.cc +++ b/src/iceberg/test/arrow_io_test.cc @@ -364,8 +364,7 @@ TEST_F(LocalFileIOTest, DeleteFile) { EXPECT_THAT(del_res, IsOk()); del_res = file_io_->DeleteFile(temp_filepath_); - EXPECT_THAT(del_res, IsError(ErrorKind::kIOError)); - EXPECT_THAT(del_res, HasErrorMessage("Cannot delete file")); + EXPECT_THAT(del_res, IsOk()); } TEST_F(LocalFileIOTest, DeleteFiles) { @@ -414,6 +413,13 @@ TEST_F(LocalFileIOTest, StdReadFullyReadsFromAbsolutePosition) { VerifyReadFullyReadsFromAbsolutePosition(file_io, temp_filepath_)); } +TEST_F(LocalFileIOTest, StdDeleteFileIsIdempotent) { + auto file_io = std::make_shared(); + ASSERT_THAT(file_io->WriteFile(temp_filepath_, "abc"), IsOk()); + EXPECT_THAT(file_io->DeleteFile(temp_filepath_), IsOk()); + EXPECT_THAT(file_io->DeleteFile(temp_filepath_), IsOk()); +} + TEST_F(LocalFileIOTest, StdReadKeepsPositionAvailableAtEof) { auto file_io = std::make_shared(); ASSERT_THAT(file_io->WriteFile(temp_filepath_, "abc"), IsOk()); diff --git a/src/iceberg/test/compaction_executor_test.cc b/src/iceberg/test/compaction_executor_test.cc new file mode 100644 index 0000000000..8f0ee2fa3b --- /dev/null +++ b/src/iceberg/test/compaction_executor_test.cc @@ -0,0 +1,757 @@ +/* + * 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 "iceberg/action/compaction_executor.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "iceberg/action/position_delete_action_internal.h" +#include "iceberg/arrow/arrow_io_internal.h" +#include "iceberg/avro/avro_register.h" +#include "iceberg/compaction_planner.h" +#include "iceberg/data/data_writer.h" +#include "iceberg/data/file_scan_task_reader.h" +#include "iceberg/data_table_scan.h" +#include "iceberg/file_writer.h" +#include "iceberg/manifest/manifest_entry.h" +#include "iceberg/manifest/manifest_reader.h" +#include "iceberg/metadata_columns.h" +#include "iceberg/parquet/parquet_register.h" +#include "iceberg/partition_spec.h" +#include "iceberg/schema.h" +#include "iceberg/schema_internal.h" +#include "iceberg/snapshot.h" +#include "iceberg/table.h" +#include "iceberg/table_metadata.h" +#include "iceberg/table_properties.h" +#include "iceberg/test/matchers.h" +#include "iceberg/test/mock_catalog.h" +#include "iceberg/test/update_test_base.h" +#include "iceberg/update/fast_append.h" +#include "iceberg/update/row_delta.h" +#include "iceberg/update/update_properties.h" +#include "iceberg/update/update_schema.h" +#include "iceberg/util/macros.h" + +namespace iceberg { +namespace { + +using Row = std::array; + +enum class FailurePoint { kAfterCreate, kDelete }; + +class FailingFileIO : public FileIO { + public: + FailingFileIO(std::shared_ptr delegate, FailurePoint point) + : delegate_(std::move(delegate)), + failure_(std::make_shared>(point)) {} + + Result> NewInputFile(std::string path) override { + return delegate_->NewInputFile(std::move(path)); + } + Result> NewInputFile(std::string path, + size_t length) override { + return delegate_->NewInputFile(std::move(path), length); + } + Result> NewOutputFile(std::string path) override { + ICEBERG_ASSIGN_OR_RAISE(auto output, delegate_->NewOutputFile(path)); + if (!IsCompacted(path) || *failure_ == FailurePoint::kDelete) return output; + return std::unique_ptr( + new FailingOutputFile(std::move(output), failure_)); + } + Status DeleteFile(const std::string& path) override { + if (IsCompacted(path) && *failure_ == FailurePoint::kDelete) { + return IOError("injected cleanup failure: {}", path); + } + return delegate_->DeleteFile(path); + } + void DisableFailure() { failure_->reset(); } + + private: + class FailingOutputFile : public OutputFile { + public: + FailingOutputFile(std::unique_ptr delegate, + std::shared_ptr> failure) + : delegate_(std::move(delegate)), failure_(std::move(failure)) {} + std::string_view location() const override { return delegate_->location(); } + Result> Create() override { + return Open(false); + } + Result> CreateOrOverwrite() override { + return Open(true); + } + + private: + Result> Open(bool overwrite) { + ICEBERG_ASSIGN_OR_RAISE( + auto stream, overwrite ? delegate_->CreateOrOverwrite() : delegate_->Create()); + if (*failure_ == FailurePoint::kAfterCreate) { + failure_->reset(); + return IOError("injected output failure after creation"); + } + return stream; + } + std::unique_ptr delegate_; + std::shared_ptr> failure_; + }; + static bool IsCompacted(std::string_view path) { + return path.find("compacted-") != std::string_view::npos; + } + std::shared_ptr delegate_; + std::shared_ptr> failure_; +}; + +class CompactionExecutorTest : public MinimalUpdateTestBase { + protected: + static void SetUpTestSuite() { + avro::RegisterAll(); + parquet::RegisterAll(); + } + + int8_t format_version() const override { return 3; } + + void SetUp() override { + MinimalUpdateTestBase::SetUp(); + ICEBERG_UNWRAP_OR_FAIL(auto properties, table_->NewUpdateProperties()); + properties->Set(TableProperties::kParquetCompression.key(), "uncompressed") + .Set(TableProperties::kDeleteParquetCompression.key(), "uncompressed") + .Set(TableProperties::kCommitNumRetries.key(), "0"); + ASSERT_THAT(properties->Commit(), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(schema_, table_->schema()); + ICEBERG_UNWRAP_OR_FAIL(spec_, table_->spec()); + } + + Result> WriteDataFile( + std::string_view name, std::string_view json, std::optional partition = 10, + std::shared_ptr file_schema = nullptr) { + if (!file_schema) file_schema = schema_; + const auto path = std::format("{}/data/{}", table_location_, name); + ICEBERG_ASSIGN_OR_RAISE( + auto writer, + DataWriter::Make({ + .path = path, + .schema = file_schema, + .spec = spec_, + .partition = PartitionValues( + {partition ? Literal::Long(*partition) : Literal::Null(int64())}), + .format = FileFormatType::kParquet, + .io = file_io_, + .properties = {{"write.parquet.compression-codec", "uncompressed"}}, + })); + + ArrowSchema c_schema{}; + ICEBERG_RETURN_UNEXPECTED(ToArrowSchema(*file_schema, &c_schema)); + auto arrow_type = ::arrow::ImportType(&c_schema); + if (!arrow_type.ok()) { + return UnknownError(arrow_type.status().ToString()); + } + auto array = ::arrow::json::ArrayFromJSONString( + ::arrow::struct_(arrow_type.ValueOrDie()->fields()), std::string(json)); + if (!array.ok()) { + return UnknownError(array.status().ToString()); + } + + ArrowArray c_array{}; + auto export_status = ::arrow::ExportArray(*array.ValueOrDie(), &c_array); + if (!export_status.ok()) { + return UnknownError(export_status.ToString()); + } + ICEBERG_RETURN_UNEXPECTED(writer->Write(&c_array)); + ICEBERG_RETURN_UNEXPECTED(writer->Close()); + ICEBERG_ASSIGN_OR_RAISE(auto metadata, writer->Metadata()); + ICEBERG_CHECK(metadata.data_files.size() == 1, "Expected one data file, found {}", + metadata.data_files.size()); + return metadata.data_files.front(); + } + + Status Append(const std::vector>& files) { + ICEBERG_ASSIGN_OR_RAISE(auto append, table_->NewFastAppend()); + for (const auto& file : files) { + append->AppendFile(file); + } + ICEBERG_RETURN_UNEXPECTED(append->Commit()); + return table_->Refresh(); + } + + Result>> Tasks( + const std::shared_ptr
& table) { + ICEBERG_ASSIGN_OR_RAISE(auto builder, table->NewScan()); + ICEBERG_ASSIGN_OR_RAISE(auto scan, builder->Build()); + return scan->PlanFiles(); + } + + Status DeletePositions(const std::map& positions) { + const auto snapshot_id = table_->metadata()->current_snapshot_id; + ICEBERG_ASSIGN_OR_RAISE(auto builder, table_->NewScan()); + builder->UseSnapshot(snapshot_id); + ICEBERG_ASSIGN_OR_RAISE(auto scan, builder->Build()); + ICEBERG_ASSIGN_OR_RAISE(auto tasks, scan->PlanFiles()); + std::vector files; + for (const auto& task : tasks) { + auto pos = positions.find(task->data_file()->file_path); + if (pos != positions.end()) files.push_back({task, {pos->second}}); + } + ICEBERG_CHECK(files.size() == positions.size(), + "Expected every target file in the scan"); + ICEBERG_ASSIGN_OR_RAISE(auto delta, table_->NewRowDelta()); + return internal::CommitPositionDeletes(*table_, *delta, snapshot_id, scan->io(), + std::move(files)); + } + + Result Plan(const std::vector>& tasks) { + ICEBERG_ASSIGN_OR_RAISE(auto snapshot, table_->current_snapshot()); + ICEBERG_ASSIGN_OR_RAISE( + auto plan, CompactionPlanner::Plan(snapshot->snapshot_id, tasks, + CompactionPlannerConfig{ + .target_file_size_bytes = 1024 * 1024, + .min_file_size_ratio = 1, + .min_input_files = 1, + })); + return plan; + } + + std::shared_ptr LineageProjection() { + std::vector fields(schema_->fields().begin(), schema_->fields().end()); + fields.push_back(MetadataColumns::kRowId); + fields.push_back(MetadataColumns::kLastUpdatedSequenceNumber); + return std::make_shared(std::move(fields), schema_->schema_id()); + } + + Result> ReadRows(const FileScanTask& task) { + ICEBERG_ASSIGN_OR_RAISE(auto reader, FileScanTaskReader::Make({ + .io = file_io_, + .table_schema = schema_, + .schemas = table_->metadata()->schemas, + .projected_schema = LineageProjection(), + })); + ICEBERG_ASSIGN_OR_RAISE(auto stream, reader->Open(task)); + auto batch_reader = ::arrow::ImportRecordBatchReader(&stream); + if (!batch_reader.ok()) { + return UnknownError(batch_reader.status().ToString()); + } + + std::vector rows; + while (true) { + auto batch_result = batch_reader.ValueOrDie()->Next(); + if (!batch_result.ok()) { + return UnknownError(batch_result.status().ToString()); + } + auto batch = batch_result.ValueOrDie(); + if (batch == nullptr) { + break; + } + ICEBERG_CHECK(batch->num_columns() == 5, "Expected five projected columns"); + std::array, 5> columns; + for (size_t i = 0; i < columns.size(); ++i) { + columns[i] = std::static_pointer_cast<::arrow::Int64Array>(batch->column(i)); + } + for (int64_t row = 0; row < batch->num_rows(); ++row) { + Row values; + for (size_t column = 0; column < columns.size(); ++column) { + ICEBERG_CHECK(!columns[column]->IsNull(row), + "Compaction row lineage column is null"); + values[column] = columns[column]->Value(row); + } + rows.push_back(values); + } + } + return rows; + } + + Result> LiveDeleteEntries() { + ICEBERG_ASSIGN_OR_RAISE(auto snapshot, table_->current_snapshot()); + SnapshotReader cache(snapshot.get()); + ICEBERG_ASSIGN_OR_RAISE(auto manifests, cache.DeleteManifests(file_io_)); + std::vector result; + for (const auto& manifest : manifests) { + ICEBERG_ASSIGN_OR_RAISE( + auto spec, table_->metadata()->PartitionSpecById(manifest.partition_spec_id)); + ICEBERG_ASSIGN_OR_RAISE( + auto reader, + ManifestReader::Make(manifest, file_io_, schema_, std::move(spec))); + ICEBERG_ASSIGN_OR_RAISE(auto entries, reader->LiveEntries()); + result.insert(result.end(), std::make_move_iterator(entries.begin()), + std::make_move_iterator(entries.end())); + } + return result; + } + + Result> FailingCommitTable( + iceberg::unexpected failure, std::shared_ptr io = nullptr) { + auto mock = std::make_shared<::testing::NiceMock>(); + ON_CALL(*mock, LoadTable(::testing::_)) + .WillByDefault([catalog = catalog_](const TableIdentifier& name) { + return catalog->LoadTable(name); + }); + EXPECT_CALL(*mock, UpdateTable(::testing::_, ::testing::_, ::testing::_)) + .Times(1) + .WillOnce(::testing::Return(std::move(failure))); + return Table::Make(table_->name(), table_->metadata(), + std::string(table_->metadata_file_location()), + io ? std::move(io) : table_->io(), std::move(mock)); + } + + std::vector CompactedFiles() { + auto arrow_io = std::dynamic_pointer_cast(file_io_); + EXPECT_NE(arrow_io, nullptr); + ::arrow::fs::FileSelector selector; + selector.base_dir = table_location_ + "/data"; + selector.recursive = true; + auto infos = arrow_io->fs()->GetFileInfo(selector); + EXPECT_TRUE(infos.ok()) << infos.status().ToString(); + std::vector result; + if (!infos.ok()) { + return result; + } + for (const auto& info : *infos) { + if (info.path().find("compacted-") != std::string::npos) { + result.push_back(info.path()); + } + } + return result; + } + + std::shared_ptr schema_; + std::shared_ptr spec_; +}; + +class CompactionExecutorV2UpgradeTest : public CompactionExecutorTest { + protected: + int8_t format_version() const override { return 2; } +}; + +TEST_F(CompactionExecutorTest, AppliesDeletesAndPreservesRowLineage) { + // Imported files may store the identity column x only in the partition tuple. + ICEBERG_UNWRAP_OR_FAIL(auto physical_schema, + schema_->Select(std::vector{"y", "z"})); + ICEBERG_UNWRAP_OR_FAIL( + auto data_file, + WriteDataFile("input.parquet", R"([[100, 1000], [200, 2000], [300, 3000]])", 10, + std::move(physical_schema))); + ASSERT_THAT(Append({data_file}), IsOk()); + + ASSERT_THAT(DeletePositions({{data_file->file_path, 1}}), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + + ICEBERG_UNWRAP_OR_FAIL(auto tasks, Tasks(table_)); + ASSERT_EQ(tasks.size(), 1); + ICEBERG_UNWRAP_OR_FAIL(auto expected_rows, ReadRows(*tasks.front())); + ICEBERG_UNWRAP_OR_FAIL(auto base_snapshot, table_->current_snapshot()); + ICEBERG_UNWRAP_OR_FAIL(auto plan, Plan(tasks)); + + ICEBERG_UNWRAP_OR_FAIL(auto executor, CompactionExecutor::Make(table_)); + ASSERT_THAT(executor->Execute(plan), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + + ICEBERG_UNWRAP_OR_FAIL(auto rewritten_tasks, Tasks(table_)); + ASSERT_EQ(rewritten_tasks.size(), 1); + const auto& rewritten = rewritten_tasks.front(); + EXPECT_NE(rewritten->data_file()->file_path, data_file->file_path); + EXPECT_EQ(rewritten->data_file()->record_count, 2); + EXPECT_EQ(rewritten->data_file()->data_sequence_number, base_snapshot->sequence_number); + EXPECT_TRUE(rewritten->delete_files().empty()); + ICEBERG_UNWRAP_OR_FAIL(auto actual_rows, ReadRows(*rewritten)); + EXPECT_EQ(actual_rows, expected_rows); + ICEBERG_UNWRAP_OR_FAIL(auto live_deletes, LiveDeleteEntries()); + EXPECT_TRUE(live_deletes.empty()); +} + +TEST_F(CompactionExecutorTest, CompactsNullPartition) { + ICEBERG_UNWRAP_OR_FAIL(auto schema_update, table_->NewUpdateSchema()); + schema_update->MakeColumnOptional("x"); + ASSERT_THAT(schema_update->Commit(), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(schema_, table_->schema()); + ICEBERG_UNWRAP_OR_FAIL( + auto file, + WriteDataFile("null.parquet", R"([[null, 100, 1000], [null, 200, 2000]])", + std::nullopt)); + ASSERT_THAT(Append({file}), IsOk()); + ASSERT_THAT(DeletePositions({{file->file_path, 0}}), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto tasks, Tasks(table_)); + ICEBERG_UNWRAP_OR_FAIL(auto plan, Plan(tasks)); + ICEBERG_UNWRAP_OR_FAIL(auto executor, CompactionExecutor::Make(table_)); + ASSERT_THAT(executor->Execute(plan), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto rewritten, Tasks(table_)); + ASSERT_EQ(rewritten.size(), 1); + EXPECT_EQ(rewritten.front()->data_file()->record_count, 1); + EXPECT_TRUE(rewritten.front()->data_file()->partition.values().front().IsNull()); + EXPECT_TRUE(rewritten.front()->delete_files().empty()); + + ICEBERG_UNWRAP_OR_FAIL(auto reader, FileScanTaskReader::Make({ + .io = file_io_, + .table_schema = schema_, + .schemas = table_->metadata()->schemas, + .projected_schema = schema_, + })); + ICEBERG_UNWRAP_OR_FAIL(auto stream, reader->Open(*rewritten.front())); + auto batches = ::arrow::ImportRecordBatchReader(&stream).ValueOrDie(); + auto batch = batches->Next().ValueOrDie(); + ASSERT_NE(batch, nullptr); + ASSERT_EQ(batch->num_rows(), 1); + EXPECT_TRUE(batch->column(0)->IsNull(0)); + EXPECT_EQ(std::static_pointer_cast<::arrow::Int64Array>(batch->column(1))->Value(0), + 200); +} + +TEST_F(CompactionExecutorTest, EmptyPlannerResultDoesNotCommit) { + ICEBERG_UNWRAP_OR_FAIL(auto file, + WriteDataFile("input.parquet", R"([[10, 100, 1000]])")); + ASSERT_THAT(Append({file}), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto snapshot, table_->current_snapshot()); + ICEBERG_UNWRAP_OR_FAIL(auto tasks, Tasks(table_)); + ICEBERG_UNWRAP_OR_FAIL( + auto plan, + CompactionPlanner::Plan(snapshot->snapshot_id, tasks, + {.target_file_size_bytes = file->file_size_in_bytes})); + ASSERT_TRUE(plan.groups.empty()); + ICEBERG_UNWRAP_OR_FAIL(auto executor, CompactionExecutor::Make(table_)); + ASSERT_THAT(executor->Execute(plan), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto after, table_->current_snapshot()); + EXPECT_EQ(after->snapshot_id, snapshot->snapshot_id); + EXPECT_TRUE(CompactedFiles().empty()); +} + +TEST_F(CompactionExecutorTest, CombinesFilesAndRemovesFullyDeletedGroup) { + ICEBERG_UNWRAP_OR_FAIL( + auto first, + WriteDataFile("first.parquet", R"([[10, 100, 1000], [10, 200, 2000]])")); + ICEBERG_UNWRAP_OR_FAIL( + auto second, + WriteDataFile("second.parquet", R"([[10, 300, 3000], [10, 400, 4000]])")); + ICEBERG_UNWRAP_OR_FAIL(auto third, + WriteDataFile("third.parquet", R"([[20, 500, 5000]])", 20)); + ASSERT_THAT(Append({first, second, third}), IsOk()); + ASSERT_THAT(DeletePositions({{first->file_path, 0}, {third->file_path, 0}}), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto tasks, Tasks(table_)); + std::vector expected; + for (const auto& task : tasks) { + ICEBERG_UNWRAP_OR_FAIL(auto rows, ReadRows(*task)); + expected.insert(expected.end(), rows.begin(), rows.end()); + } + std::ranges::sort(expected); + ASSERT_EQ(expected.size(), 3); + ICEBERG_UNWRAP_OR_FAIL(auto plan, Plan(tasks)); + ASSERT_EQ(plan.groups.size(), 2); + ASSERT_EQ(plan.groups.front().files.size(), 2); + ICEBERG_UNWRAP_OR_FAIL(auto executor, CompactionExecutor::Make(table_)); + ASSERT_THAT(executor->Execute(plan), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto rewritten, Tasks(table_)); + ASSERT_EQ(rewritten.size(), 1); + EXPECT_TRUE(rewritten.front()->delete_files().empty()); + ICEBERG_UNWRAP_OR_FAIL(auto actual, ReadRows(*rewritten.front())); + std::ranges::sort(actual); + EXPECT_EQ(actual, expected); + ICEBERG_UNWRAP_OR_FAIL(auto live_deletes, LiveDeleteEntries()); + EXPECT_TRUE(live_deletes.empty()); +} + +TEST_F(CompactionExecutorTest, KeepsSharedPuffinForUncompactedDataFile) { + ICEBERG_UNWRAP_OR_FAIL( + auto first, + WriteDataFile("first.parquet", R"([[10, 100, 1000], [10, 200, 2000]])")); + ICEBERG_UNWRAP_OR_FAIL( + auto second, + WriteDataFile("second.parquet", R"([[10, 300, 3000], [10, 400, 4000]])")); + ASSERT_THAT(Append({first, second}), IsOk()); + + ASSERT_THAT(DeletePositions({{first->file_path, 0}, {second->file_path, 1}}), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + + ICEBERG_UNWRAP_OR_FAIL(auto tasks, Tasks(table_)); + auto first_task = std::ranges::find_if(tasks, [&](const auto& task) { + return task->data_file()->file_path == first->file_path; + }); + auto second_task = std::ranges::find_if(tasks, [&](const auto& task) { + return task->data_file()->file_path == second->file_path; + }); + ASSERT_NE(first_task, tasks.end()); + ASSERT_NE(second_task, tasks.end()); + ASSERT_EQ((*first_task)->delete_files().size(), 1); + ASSERT_EQ((*second_task)->delete_files().size(), 1); + const auto shared_puffin = (*first_task)->delete_files().front()->file_path; + ASSERT_EQ(shared_puffin, (*second_task)->delete_files().front()->file_path); + + ICEBERG_UNWRAP_OR_FAIL(auto plan, + Plan(std::vector>{*first_task})); + ICEBERG_UNWRAP_OR_FAIL(auto executor, CompactionExecutor::Make(table_)); + ASSERT_THAT(executor->Execute(plan), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + + ICEBERG_UNWRAP_OR_FAIL(auto rewritten_tasks, Tasks(table_)); + auto remaining = std::ranges::find_if(rewritten_tasks, [&](const auto& task) { + return task->data_file()->file_path == second->file_path; + }); + ASSERT_NE(remaining, rewritten_tasks.end()); + ASSERT_EQ((*remaining)->delete_files().size(), 1); + EXPECT_EQ((*remaining)->delete_files().front()->file_path, shared_puffin); + auto arrow_io = std::dynamic_pointer_cast(file_io_); + ASSERT_NE(arrow_io, nullptr); + auto info = arrow_io->fs()->GetFileInfo(shared_puffin); + ASSERT_TRUE(info.ok()) << info.status().ToString(); + EXPECT_EQ(info->type(), ::arrow::fs::FileType::File); + + ICEBERG_UNWRAP_OR_FAIL(auto live_deletes, LiveDeleteEntries()); + ASSERT_EQ(live_deletes.size(), 1); + EXPECT_EQ(live_deletes.front().data_file->referenced_data_file, second->file_path); +} + +TEST_F(CompactionExecutorTest, CommitStateUnknownRelinquishesOutputOwnership) { + ICEBERG_UNWRAP_OR_FAIL( + auto data_file, + WriteDataFile("input.parquet", R"([[10, 100, 1000], [10, 200, 2000]])")); + ASSERT_THAT(Append({data_file}), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto tasks, Tasks(table_)); + ICEBERG_UNWRAP_OR_FAIL(auto plan, Plan(tasks)); + + ICEBERG_UNWRAP_OR_FAIL( + auto mock_table, FailingCommitTable(CommitStateUnknown("injected unknown state"))); + + ICEBERG_UNWRAP_OR_FAIL(auto executor, CompactionExecutor::Make(mock_table)); + EXPECT_THAT(executor->Execute(plan), IsError(ErrorKind::kCommitStateUnknown)); + ASSERT_EQ(CompactedFiles().size(), 1); + + EXPECT_THAT(executor->Execute(plan), IsError(ErrorKind::kInvalidArgument)); + EXPECT_EQ(CompactedFiles().size(), 1); +} + +TEST_F(CompactionExecutorTest, RejectsDuplicateSourceFilesBeforeWriting) { + ICEBERG_UNWRAP_OR_FAIL( + auto data_file, + WriteDataFile("input.parquet", R"([[10, 100, 1000], [10, 200, 2000]])")); + ASSERT_THAT(Append({data_file}), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto tasks, Tasks(table_)); + ICEBERG_UNWRAP_OR_FAIL(auto plan, Plan(tasks)); + ASSERT_EQ(plan.groups.size(), 1); + ASSERT_EQ(plan.groups.front().files.size(), 1); + + auto within_group = plan; + within_group.groups.front().files.push_back(within_group.groups.front().files.front()); + ICEBERG_UNWRAP_OR_FAIL(auto executor, CompactionExecutor::Make(table_)); + EXPECT_THAT(executor->Execute(within_group), IsError(ErrorKind::kInvalidArgument)); + EXPECT_TRUE(CompactedFiles().empty()); + + auto across_groups = plan; + across_groups.groups.push_back(across_groups.groups.front()); + EXPECT_THAT(executor->Execute(across_groups), IsError(ErrorKind::kInvalidArgument)); + EXPECT_TRUE(CompactedFiles().empty()); +} + +TEST_F(CompactionExecutorTest, RejectsPlanAfterNewDeleteSnapshot) { + ICEBERG_UNWRAP_OR_FAIL( + auto data_file, + WriteDataFile("input.parquet", + R"([[10, 100, 1000], [10, 200, 2000], [10, 300, 3000]])")); + ASSERT_THAT(Append({data_file}), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto tasks, Tasks(table_)); + ICEBERG_UNWRAP_OR_FAIL(auto plan, Plan(tasks)); + + ASSERT_THAT(DeletePositions({{data_file->file_path, 1}}), IsOk()); + + ICEBERG_UNWRAP_OR_FAIL(auto executor, CompactionExecutor::Make(table_)); + EXPECT_THAT(executor->Execute(plan), IsError(ErrorKind::kValidationFailed)); + EXPECT_TRUE(CompactedFiles().empty()); + + ASSERT_THAT(table_->Refresh(), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto current_tasks, Tasks(table_)); + ASSERT_EQ(current_tasks.size(), 1); + ASSERT_EQ(current_tasks.front()->delete_files().size(), 1); + ICEBERG_UNWRAP_OR_FAIL(auto rows, ReadRows(*current_tasks.front())); + EXPECT_EQ(rows.size(), 2); +} + +TEST_F(CompactionExecutorTest, MultiFileMultiGroupCommitIsAtomicOnFailure) { + ICEBERG_UNWRAP_OR_FAIL( + auto first, + WriteDataFile("first.parquet", R"([[10, 100, 1000], [10, 200, 2000]])")); + ICEBERG_UNWRAP_OR_FAIL( + auto second, + WriteDataFile("second.parquet", R"([[10, 300, 3000], [10, 400, 4000]])")); + ICEBERG_UNWRAP_OR_FAIL( + auto third, + WriteDataFile("third.parquet", R"([[20, 500, 5000], [20, 600, 6000]])", 20)); + ASSERT_THAT(Append({first, second, third}), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto tasks, Tasks(table_)); + ICEBERG_UNWRAP_OR_FAIL(auto plan, Plan(tasks)); + ASSERT_EQ(plan.groups.size(), 2); + ASSERT_EQ(plan.groups.front().files.size(), 2); + + ICEBERG_UNWRAP_OR_FAIL(auto mock_table, + FailingCommitTable(CommitFailed("injected failure"))); + + ICEBERG_UNWRAP_OR_FAIL(auto executor, CompactionExecutor::Make(mock_table)); + EXPECT_THAT(executor->Execute(plan), IsError(ErrorKind::kCommitFailed)); + EXPECT_TRUE(CompactedFiles().empty()); + + ICEBERG_UNWRAP_OR_FAIL(auto current_tasks, Tasks(table_)); + EXPECT_EQ(current_tasks.size(), 3); +} + +TEST_F(CompactionExecutorTest, CleanupFailureRetainsOutputForExplicitRetry) { + ICEBERG_UNWRAP_OR_FAIL( + auto data_file, + WriteDataFile("input.parquet", R"([[10, 100, 1000], [10, 200, 2000]])")); + ASSERT_THAT(Append({data_file}), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto tasks, Tasks(table_)); + ICEBERG_UNWRAP_OR_FAIL(auto plan, Plan(tasks)); + + auto failing_io = std::make_shared(table_->io(), FailurePoint::kDelete); + ICEBERG_UNWRAP_OR_FAIL( + auto mock_table, + FailingCommitTable(CommitFailed("injected commit failure"), failing_io)); + + ICEBERG_UNWRAP_OR_FAIL(auto executor, CompactionExecutor::Make(mock_table)); + auto status = executor->Execute(plan); + EXPECT_THAT(status, IsError(ErrorKind::kCommitFailed)); + EXPECT_THAT(status, HasErrorMessage("injected commit failure")); + EXPECT_THAT(status, HasErrorMessage("injected cleanup failure")); + ASSERT_EQ(CompactedFiles().size(), 1); + + failing_io->DisableFailure(); + EXPECT_THAT(executor->Cleanup(), IsOk()); + EXPECT_TRUE(CompactedFiles().empty()); +} + +TEST_F(CompactionExecutorTest, WriterFailureBeforeFileCreationLeavesExecutorReusable) { + ICEBERG_UNWRAP_OR_FAIL( + auto data_file, + WriteDataFile("input.parquet", R"([[10, 100, 1000], [10, 200, 2000]])")); + ASSERT_THAT(Append({data_file}), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto tasks, Tasks(table_)); + ICEBERG_UNWRAP_OR_FAIL(auto plan, Plan(tasks)); + + ICEBERG_UNWRAP_OR_FAIL(auto invalid_properties, table_->NewUpdateProperties()); + invalid_properties->Set(WriterProperties::kParquetMaxRowGroupRows.key(), "0"); + ASSERT_THAT(invalid_properties->Commit(), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + + ICEBERG_UNWRAP_OR_FAIL(auto executor, CompactionExecutor::Make(table_)); + auto status = executor->Execute(plan); + EXPECT_THAT(status, IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(status, HasErrorMessage("Parquet max row group rows")); + EXPECT_TRUE(CompactedFiles().empty()); + EXPECT_THAT(executor->Cleanup(), IsOk()); + + ICEBERG_UNWRAP_OR_FAIL(auto valid_properties, table_->NewUpdateProperties()); + valid_properties->Set(WriterProperties::kParquetMaxRowGroupRows.key(), "100"); + ASSERT_THAT(valid_properties->Commit(), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + + ASSERT_THAT(executor->Execute(plan), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto rewritten_tasks, Tasks(table_)); + ASSERT_EQ(rewritten_tasks.size(), 1); + EXPECT_NE(rewritten_tasks.front()->data_file()->file_path, data_file->file_path); +} + +TEST_F(CompactionExecutorTest, CleansPartiallyCreatedOutputAndAllowsRetry) { + ICEBERG_UNWRAP_OR_FAIL( + auto file, WriteDataFile("input.parquet", R"([[10, 100, 1000], [10, 200, 2000]])")); + ASSERT_THAT(Append({file}), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto tasks, Tasks(table_)); + ICEBERG_UNWRAP_OR_FAIL(auto plan, Plan(tasks)); + auto io = std::make_shared(table_->io(), FailurePoint::kAfterCreate); + ICEBERG_UNWRAP_OR_FAIL( + auto writer_table, + Table::Make(table_->name(), table_->metadata(), + std::string(table_->metadata_file_location()), io, catalog_)); + ICEBERG_UNWRAP_OR_FAIL(auto executor, CompactionExecutor::Make(writer_table)); + EXPECT_THAT(executor->Execute(plan), IsError(ErrorKind::kIOError)); + EXPECT_TRUE(CompactedFiles().empty()); + EXPECT_THAT(executor->Cleanup(), IsOk()); + ASSERT_THAT(executor->Execute(plan), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto rewritten, Tasks(table_)); + ASSERT_EQ(rewritten.size(), 1); + EXPECT_NE(rewritten.front()->data_file()->file_path, file->file_path); +} + +TEST_F(CompactionExecutorV2UpgradeTest, + RemovesParquetDeleteAndAssignsUpgradedRowLineage) { + ICEBERG_UNWRAP_OR_FAIL( + auto data_file, + WriteDataFile("input.parquet", + R"([[10, 100, 1000], [10, 200, 2000], [10, 300, 3000]])")); + ASSERT_THAT(Append({data_file}), IsOk()); + + ASSERT_THAT(DeletePositions({{data_file->file_path, 1}}), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto v2_tasks, Tasks(table_)); + ASSERT_EQ(v2_tasks.size(), 1); + ASSERT_EQ(v2_tasks.front()->delete_files().size(), 1); + EXPECT_EQ(v2_tasks.front()->delete_files().front()->file_format, + FileFormatType::kParquet); + + ICEBERG_UNWRAP_OR_FAIL(auto properties, table_->NewUpdateProperties()); + properties->Set(TableProperties::kFormatVersion.key(), "3"); + ASSERT_THAT(properties->Commit(), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + + ICEBERG_UNWRAP_OR_FAIL(auto tasks, Tasks(table_)); + ASSERT_EQ(tasks.size(), 1); + ASSERT_FALSE(tasks.front()->data_file()->first_row_id.has_value()); + ICEBERG_UNWRAP_OR_FAIL(auto plan, Plan(tasks)); + + ICEBERG_UNWRAP_OR_FAIL(auto executor, CompactionExecutor::Make(table_)); + ASSERT_THAT(executor->Execute(plan), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + + ICEBERG_UNWRAP_OR_FAIL(auto rewritten_tasks, Tasks(table_)); + ASSERT_EQ(rewritten_tasks.size(), 1); + ASSERT_TRUE(rewritten_tasks.front()->data_file()->first_row_id.has_value()); + const auto first_row_id = *rewritten_tasks.front()->data_file()->first_row_id; + ICEBERG_UNWRAP_OR_FAIL(auto rows, ReadRows(*rewritten_tasks.front())); + ASSERT_EQ(rows.size(), 2); + EXPECT_EQ(rows[0][3], first_row_id); + EXPECT_EQ(rows[1][3], first_row_id + 1); + // The v2 rows had no assigned lineage, so their sequence is inherited + // from the replacement file along with their newly assigned row IDs. + const auto sequence = rewritten_tasks.front()->data_file()->data_sequence_number; + ASSERT_TRUE(sequence.has_value()); + EXPECT_EQ(rows[0][4], *sequence); + EXPECT_EQ(rows[1][4], *sequence); + EXPECT_TRUE(rewritten_tasks.front()->delete_files().empty()); + ICEBERG_UNWRAP_OR_FAIL(auto live_deletes, LiveDeleteEntries()); + EXPECT_TRUE(live_deletes.empty()); +} + +} // namespace +} // namespace iceberg diff --git a/src/iceberg/test/compaction_planner_test.cc b/src/iceberg/test/compaction_planner_test.cc new file mode 100644 index 0000000000..e749d4b45e --- /dev/null +++ b/src/iceberg/test/compaction_planner_test.cc @@ -0,0 +1,326 @@ +/* + * 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 "iceberg/compaction_planner.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "iceberg/expression/literal.h" +#include "iceberg/file_format.h" +#include "iceberg/manifest/manifest_entry.h" +#include "iceberg/table_scan.h" +#include "iceberg/test/matchers.h" +#include "iceberg/type.h" + +namespace iceberg { +namespace { + +using ::testing::ElementsAre; +using ::testing::IsEmpty; +using ::testing::SizeIs; + +class CompactionPlannerTest : public testing::Test { + protected: + static constexpr int64_t kSnapshotId = 1234; + + static std::shared_ptr Data(std::string path, PartitionValues partition, + int64_t size, std::optional spec_id = 1, + int64_t records = 100) { + return std::make_shared(DataFile{ + .file_path = std::move(path), + .partition = std::move(partition), + .record_count = records, + .file_size_in_bytes = size, + .partition_spec_id = spec_id, + }); + } + + static std::shared_ptr Data(std::string path, int32_t partition, int64_t size, + std::optional spec_id = 1, + int64_t records = 100) { + return Data(std::move(path), PartitionValues(Literal::Int(partition)), size, spec_id, + records); + } + + static std::shared_ptr PositionDelete(std::string path, + const std::string& referenced_file, + int64_t records, + bool file_scoped = true) { + return std::make_shared(DataFile{ + .content = DataFile::Content::kPositionDeletes, + .file_path = std::move(path), + .record_count = records, + .referenced_data_file = + file_scoped ? std::make_optional(referenced_file) : std::nullopt, + }); + } + + static std::shared_ptr DeletionVector(std::string path, + const std::string& referenced_file, + int64_t records, int64_t offset = 0, + int64_t size = 10) { + return std::make_shared(DataFile{ + .content = DataFile::Content::kPositionDeletes, + .file_path = std::move(path), + .file_format = FileFormatType::kPuffin, + .record_count = records, + .referenced_data_file = referenced_file, + .content_offset = offset, + .content_size_in_bytes = size, + }); + } + + static std::shared_ptr EqualityDelete(std::string path, int64_t records) { + return std::make_shared(DataFile{ + .content = DataFile::Content::kEqualityDeletes, + .file_path = std::move(path), + .record_count = records, + }); + } + + static std::shared_ptr Task( + std::shared_ptr data_file, + std::vector> deletes = {}) { + return std::make_shared(std::move(data_file), std::move(deletes)); + } + + static std::vector Paths(const CompactionGroup& group) { + std::vector paths; + for (const auto& file : group.files) { + paths.push_back(file.scan_task->data_file()->file_path); + } + return paths; + } + + static CompactionPlannerConfig Config() { + return CompactionPlannerConfig{ + .target_file_size_bytes = 100, + .min_file_size_ratio = 0.5, + .min_input_files = 2, + .delete_file_threshold = 2, + .delete_ratio_threshold = 0.2, + }; + } +}; + +TEST_F(CompactionPlannerTest, ValidatesConfig) { + auto config = Config(); + config.target_file_size_bytes = 0; + EXPECT_THAT(CompactionPlanner::Plan(kSnapshotId, {}, config), + IsError(ErrorKind::kInvalidArgument)); +} + +TEST_F(CompactionPlannerTest, ZeroDeleteThresholdsDisableDeleteSelection) { + auto config = Config(); + config.delete_file_threshold = 0; + config.delete_ratio_threshold = 0; + std::vector> tasks{ + Task(Data("data", 1, 100), {PositionDelete("delete-a", "data", 100), + PositionDelete("delete-b", "data", 100)})}; + + ICEBERG_UNWRAP_OR_FAIL(auto plan, CompactionPlanner::Plan(kSnapshotId, tasks, config)); + EXPECT_THAT(plan.groups, IsEmpty()); +} + +TEST_F(CompactionPlannerTest, SelectsThresholdBoundariesAndIgnoresOtherDeletes) { + std::vector> tasks{ + Task(Data("small-a", 1, 49)), + Task(Data("small-b", 1, 49)), + Task(Data("at-min-size", 1, 50)), + Task(Data("below-ratio", 2, 100), + {DeletionVector("below-ratio.dv", "below-ratio", 19)}), + Task(Data("at-ratio", 2, 100), {DeletionVector("at-ratio.dv", "at-ratio", 20)}), + Task(Data("at-count", 3, 100), {PositionDelete("count-a", "at-count", 0), + PositionDelete("count-b", "at-count", 0)}), + Task(Data("ignored", 4, 100), + {EqualityDelete("equality", 100), + PositionDelete("partition-scoped", "ignored", 100, false)})}; + + ICEBERG_UNWRAP_OR_FAIL(auto plan, + CompactionPlanner::Plan(kSnapshotId, tasks, Config())); + ASSERT_THAT(plan.groups, SizeIs(3)); + EXPECT_THAT(Paths(plan.groups[0]), ElementsAre("small-a", "small-b")); + EXPECT_THAT(Paths(plan.groups[1]), ElementsAre("at-ratio")); + EXPECT_EQ(plan.groups[1].file_scoped_delete_record_count, 20); + EXPECT_THAT(Paths(plan.groups[2]), ElementsAre("at-count")); +} + +TEST_F(CompactionPlannerTest, GroupsNullPartitionsTogether) { + auto null_partition = [] { return PartitionValues(Literal::Null(int32())); }; + std::vector> tasks{ + Task(Data("null-b", null_partition(), 10)), Task(Data("value-a", 1, 10)), + Task(Data("null-a", null_partition(), 10)), Task(Data("value-b", 1, 10))}; + + ICEBERG_UNWRAP_OR_FAIL(auto plan, + CompactionPlanner::Plan(kSnapshotId, tasks, Config())); + ASSERT_THAT(plan.groups, SizeIs(2)); + EXPECT_THAT(Paths(plan.groups[0]), ElementsAre("null-a", "null-b")); + EXPECT_THAT(Paths(plan.groups[1]), ElementsAre("value-a", "value-b")); +} + +TEST_F(CompactionPlannerTest, GroupsCanonicalNaNPartitionsTogether) { + auto quiet_nan = + PartitionValues(Literal::Double(std::numeric_limits::quiet_NaN())); + auto signaling_nan = + PartitionValues(Literal::Double(std::numeric_limits::signaling_NaN())); + std::vector> tasks{ + Task(Data("nan-b", std::move(signaling_nan), 10)), + Task(Data("nan-a", std::move(quiet_nan), 10))}; + + ICEBERG_UNWRAP_OR_FAIL(auto plan, + CompactionPlanner::Plan(kSnapshotId, tasks, Config())); + ASSERT_THAT(plan.groups, SizeIs(1)); + EXPECT_THAT(Paths(plan.groups[0]), ElementsAre("nan-a", "nan-b")); +} + +TEST_F(CompactionPlannerTest, RejectsMissingPartitionSpecId) { + std::vector> tasks{ + Task(Data("missing-spec", 1, 10, std::nullopt))}; + + EXPECT_THAT(CompactionPlanner::Plan(kSnapshotId, tasks, Config()), + IsError(ErrorKind::kInvalidArgument)); +} + +TEST_F(CompactionPlannerTest, RejectsDuplicateDataFileTasks) { + std::vector> tasks{Task(Data("duplicate", 1, 10)), + Task(Data("duplicate", 1, 10))}; + + EXPECT_THAT(CompactionPlanner::Plan(kSnapshotId, tasks, Config()), + IsError(ErrorKind::kInvalidArgument)); +} + +TEST_F(CompactionPlannerTest, ProducesCanonicalPartitionAndFileOrder) { + std::vector> tasks{ + Task(Data("s2-z", 1, 10, 2)), Task(Data("p2-z", 2, 10)), Task(Data("p1-z", 1, 10)), + Task(Data("s2-a", 1, 10, 2)), Task(Data("p2-a", 2, 10)), Task(Data("p1-a", 1, 10))}; + + ICEBERG_UNWRAP_OR_FAIL(auto first, + CompactionPlanner::Plan(kSnapshotId, tasks, Config())); + std::ranges::reverse(tasks); + ICEBERG_UNWRAP_OR_FAIL(auto second, + CompactionPlanner::Plan(kSnapshotId, tasks, Config())); + + ASSERT_THAT(first.groups, SizeIs(3)); + ASSERT_THAT(second.groups, SizeIs(3)); + EXPECT_EQ(first.source_snapshot_id, kSnapshotId); + for (size_t i = 0; i < first.groups.size(); ++i) { + EXPECT_EQ(first.groups[i].partition_spec_id, second.groups[i].partition_spec_id); + EXPECT_EQ(Paths(first.groups[i]), Paths(second.groups[i])); + } + EXPECT_EQ(first.groups[0].partition_spec_id, 1); + EXPECT_THAT(Paths(first.groups[0]), ElementsAre("p1-a", "p1-z")); + EXPECT_THAT(Paths(first.groups[1]), ElementsAre("p2-a", "p2-z")); + EXPECT_EQ(first.groups[2].partition_spec_id, 2); + EXPECT_THAT(Paths(first.groups[2]), ElementsAre("s2-a", "s2-z")); +} + +TEST_F(CompactionPlannerTest, DeduplicatesDeleteReferencesAndDistinguishesDvRanges) { + std::vector> tasks{ + Task(Data("data", 1, 100), + {PositionDelete("deletes", "data", 30), PositionDelete("deletes", "data", 30), + DeletionVector("deletes", "data", 20, 0, 10), + DeletionVector("deletes", "data", 20, 0, 10), + DeletionVector("deletes", "data", 5, 10, 10)})}; + auto config = Config(); + config.delete_file_threshold = 3; + config.delete_ratio_threshold = 0; + + ICEBERG_UNWRAP_OR_FAIL(auto plan, CompactionPlanner::Plan(kSnapshotId, tasks, config)); + ASSERT_THAT(plan.groups, SizeIs(1)); + ASSERT_THAT(plan.groups[0].files, SizeIs(1)); + EXPECT_EQ(plan.groups[0].files[0].file_scoped_delete_count, 3); + EXPECT_EQ(plan.groups[0].files[0].file_scoped_delete_record_count, 55); +} + +TEST_F(CompactionPlannerTest, CapsPositionDeleteCardinalityAtDataRows) { + std::vector> tasks{Task( + Data("data", 1, 100), + {PositionDelete("delete-a", "data", 80), PositionDelete("delete-b", "data", 40)})}; + + ICEBERG_UNWRAP_OR_FAIL(auto plan, + CompactionPlanner::Plan(kSnapshotId, tasks, Config())); + ASSERT_THAT(plan.groups, SizeIs(1)); + EXPECT_EQ(plan.groups[0].files[0].file_scoped_delete_record_count, 100); + EXPECT_EQ(plan.groups[0].file_scoped_delete_record_count, 100); +} + +TEST_F(CompactionPlannerTest, RejectsDvCardinalityAboveDataRows) { + std::vector> tasks{ + Task(Data("data", 1, 100), {DeletionVector("dv", "data", 101)})}; + + EXPECT_THAT(CompactionPlanner::Plan(kSnapshotId, tasks, Config()), + IsError(ErrorKind::kInvalidArgument)); +} + +TEST_F(CompactionPlannerTest, RequiresDeletePressureForOversizedFiles) { + std::vector> tasks{ + Task(Data("no-deletes", 1, 201)), + Task(Data("below-ratio", 1, 201), {DeletionVector("below.dv", "below-ratio", 19)}), + Task(Data("at-ratio", 1, 201), {DeletionVector("at.dv", "at-ratio", 20)})}; + + ICEBERG_UNWRAP_OR_FAIL(auto plan, + CompactionPlanner::Plan(kSnapshotId, tasks, Config())); + ASSERT_THAT(plan.groups, SizeIs(1)); + EXPECT_THAT(Paths(plan.groups[0]), ElementsAre("at-ratio")); +} + +TEST_F(CompactionPlannerTest, SplitsPartitionIntoTargetSizedGroups) { + std::vector> tasks; + for (const auto* path : {"f", "e", "d", "c", "b", "a"}) { + tasks.push_back(Task(Data(path, 1, 40))); + } + + ICEBERG_UNWRAP_OR_FAIL(auto plan, + CompactionPlanner::Plan(kSnapshotId, tasks, Config())); + ASSERT_THAT(plan.groups, SizeIs(3)); + EXPECT_THAT(Paths(plan.groups[0]), ElementsAre("a", "b")); + EXPECT_THAT(Paths(plan.groups[1]), ElementsAre("c", "d")); + EXPECT_THAT(Paths(plan.groups[2]), ElementsAre("e", "f")); + for (const auto& group : plan.groups) { + EXPECT_EQ(group.data_file_size_bytes, 80); + } +} + +TEST_F(CompactionPlannerTest, BestFitAvoidsDroppingCompatibleSmallFiles) { + auto config = Config(); + config.min_file_size_ratio = 1.0; + std::vector> tasks{ + Task(Data("d40", 1, 40)), Task(Data("b60", 1, 60)), Task(Data("c40", 1, 40)), + Task(Data("a60", 1, 60))}; + + ICEBERG_UNWRAP_OR_FAIL(auto plan, CompactionPlanner::Plan(kSnapshotId, tasks, config)); + ASSERT_THAT(plan.groups, SizeIs(2)); + EXPECT_THAT(Paths(plan.groups[0]), ElementsAre("a60", "c40")); + EXPECT_THAT(Paths(plan.groups[1]), ElementsAre("b60", "d40")); + EXPECT_EQ(plan.groups[0].data_file_size_bytes, 100); + EXPECT_EQ(plan.groups[1].data_file_size_bytes, 100); +} + +} // namespace +} // namespace iceberg diff --git a/src/iceberg/test/position_delete_update_test.cc b/src/iceberg/test/position_delete_update_test.cc new file mode 100644 index 0000000000..32d0727b36 --- /dev/null +++ b/src/iceberg/test/position_delete_update_test.cc @@ -0,0 +1,287 @@ +/* + * 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 +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "iceberg/action/position_delete_action_internal.h" +#include "iceberg/arrow/arrow_io_internal.h" +#include "iceberg/avro/avro_register.h" +#include "iceberg/data/data_writer.h" +#include "iceberg/data/file_scan_task_reader.h" +#include "iceberg/data_table_scan.h" +#include "iceberg/file_reader.h" +#include "iceberg/metadata_columns.h" +#include "iceberg/parquet/parquet_register.h" +#include "iceberg/partition_spec.h" +#include "iceberg/schema.h" +#include "iceberg/schema_internal.h" +#include "iceberg/table.h" +#include "iceberg/table_metadata.h" +#include "iceberg/table_properties.h" +#include "iceberg/test/matchers.h" +#include "iceberg/test/mock_catalog.h" +#include "iceberg/test/update_test_base.h" +#include "iceberg/update/delete_files.h" +#include "iceberg/update/fast_append.h" +#include "iceberg/update/row_delta.h" +#include "iceberg/update/update_partition_spec.h" +#include "iceberg/update/update_properties.h" + +namespace iceberg { +namespace { + +class ScanFileIO : public FileIO { + public: + MOCK_METHOD(Result>, NewInputFile, (std::string), + (override)); +}; + +class PositionDeleteV3Test : public MinimalUpdateTestBase { + protected: + static void SetUpTestSuite() { + avro::RegisterAll(); + parquet::RegisterAll(); + } + + int8_t format_version() const override { return 3; } + virtual bool unpartitioned() const { return false; } + + void SetUp() override { + MinimalUpdateTestBase::SetUp(); + ICEBERG_UNWRAP_OR_FAIL(auto properties, table_->NewUpdateProperties()); + properties->Set(TableProperties::kDeleteParquetCompression.key(), "uncompressed"); + ASSERT_THAT(properties->Commit(), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + if (unpartitioned()) { + ICEBERG_UNWRAP_OR_FAIL(auto evolution, table_->NewUpdatePartitionSpec()); + evolution->RemoveField("x"); + ASSERT_THAT(evolution->Commit(), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + } + ICEBERG_UNWRAP_OR_FAIL(auto schema, table_->schema()); + ICEBERG_UNWRAP_OR_FAIL(auto spec, table_->spec()); + ICEBERG_UNWRAP_OR_FAIL( + auto writer, + DataWriter::Make({ + .path = table_location_ + "/data/file.parquet", + .schema = schema, + .spec = spec, + .partition = + unpartitioned() ? PartitionValues{} : PartitionValues(Literal::Long(10)), + .format = FileFormatType::kParquet, + .io = file_io_, + .properties = {{"write.parquet.compression-codec", "uncompressed"}}, + })); + ArrowSchema c_schema{}; + ASSERT_THAT(ToArrowSchema(*schema, &c_schema), IsOk()); + auto type = ::arrow::ImportType(&c_schema).ValueOrDie(); + auto array = ::arrow::json::ArrayFromJSONString( + type, "[[10,0,0],[10,1,10],[10,2,20],[10,3,30],[10,4,40]]") + .ValueOrDie(); + ArrowArray c_array{}; + ASSERT_TRUE(::arrow::ExportArray(*array, &c_array).ok()); + ASSERT_THAT(writer->Write(&c_array), IsOk()); + ASSERT_THAT(writer->Close(), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto result, writer->Metadata()); + data_file_ = result.data_files.front(); + ICEBERG_UNWRAP_OR_FAIL(auto append, table_->NewFastAppend()); + append->AppendFile(data_file_); + ASSERT_THAT(append->Commit(), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + } + + Status DeletePositions(std::vector positions, + std::shared_ptr scan_io = nullptr) { + const auto snapshot_id = table_->metadata()->current_snapshot_id; + ICEBERG_ASSIGN_OR_RAISE(auto builder, table_->NewScan()); + builder->UseSnapshot(snapshot_id); + ICEBERG_ASSIGN_OR_RAISE(auto scan, builder->Build()); + ICEBERG_ASSIGN_OR_RAISE(auto tasks, scan->PlanFiles()); + ICEBERG_ASSIGN_OR_RAISE(auto delta, table_->NewRowDelta()); + return internal::CommitPositionDeletes(*table_, *delta, snapshot_id, + scan_io ? scan_io : scan->io(), + {{tasks.at(0), std::move(positions)}}); + } + + std::vector> Tasks() { + ICEBERG_THROW_NOT_OK(table_->Refresh()); + auto builder = table_->NewScan().value(); + return builder->Build().value()->PlanFiles().value(); + } + + std::vector ReadRows() { + table_ = catalog_->LoadTable(table_ident_).value(); + auto tasks = Tasks(); + auto schema = table_->schema().value(); + auto reader = FileScanTaskReader::Make({ + .io = file_io_, + .table_schema = schema, + .schemas = table_->metadata()->schemas, + .projected_schema = schema, + }) + .value(); + auto stream = reader->Open(*tasks.at(0)).value(); + auto batches = ::arrow::ImportRecordBatchReader(&stream).ValueOrDie(); + std::vector rows; + while (auto batch = batches->Next().ValueOrDie()) { + const auto& values = static_cast(*batch->column(1)); + for (int64_t i = 0; i < values.length(); ++i) rows.push_back(values.Value(i)); + } + return rows; + } + + std::shared_ptr data_file_; +}; + +class PositionDeleteUpdateTest : public PositionDeleteV3Test { + protected: + int8_t format_version() const override { return 2; } +}; + +TEST_F(PositionDeleteUpdateTest, WritesSortedParquetDeletes) { + ASSERT_THAT(DeletePositions({3, 1}), IsOk()); + EXPECT_THAT(ReadRows(), ::testing::ElementsAre(0, 2, 4)); + const auto old_delete = Tasks().at(0)->delete_files().at(0); + ASSERT_EQ(old_delete->file_format, FileFormatType::kParquet); + auto projection = std::make_shared(std::vector{ + MetadataColumns::kDeleteFilePath, MetadataColumns::kDeleteFilePos}); + ICEBERG_UNWRAP_OR_FAIL( + auto reader, + ReaderFactoryRegistry::Open( + FileFormatType::kParquet, + {.path = old_delete->file_path, .io = file_io_, .projection = projection})); + ICEBERG_UNWRAP_OR_FAIL(auto batch, reader->Next()); + ASSERT_TRUE(batch.has_value()); + ArrowSchema schema{}; + ASSERT_THAT(ToArrowSchema(*projection, &schema), IsOk()); + auto rows = ::arrow::ImportArray(&*batch, ::arrow::ImportType(&schema).ValueOrDie()) + .ValueOrDie(); + const auto& positions = static_cast( + *static_cast(*rows).field(1)); + ASSERT_EQ(positions.length(), 2); + EXPECT_EQ(positions.Value(0), 1); + EXPECT_EQ(positions.Value(1), 3); +} + +TEST_F(PositionDeleteUpdateTest, UpgradeMergesPreviousParquetDeletes) { + ASSERT_THAT(DeletePositions({3, 1}), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto properties, table_->NewUpdateProperties()); + properties->Set(TableProperties::kFormatVersion.key(), "3"); + ASSERT_THAT(properties->Commit(), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + ASSERT_THAT(DeletePositions({2}), IsOk()); + EXPECT_THAT(ReadRows(), ::testing::ElementsAre(0, 4)); + auto task = Tasks().at(0); + ASSERT_EQ(task->delete_files().size(), 1); + EXPECT_TRUE(task->delete_files().front()->IsDeletionVector()); +} + +TEST_F(PositionDeleteV3Test, MergesPreviousVectorAfterPartitionEvolution) { + ASSERT_THAT(DeletePositions({3, 1}), IsOk()); + EXPECT_THAT(ReadRows(), ::testing::ElementsAre(0, 2, 4)); + const auto old_delete = Tasks().at(0)->delete_files().at(0); + ICEBERG_UNWRAP_OR_FAIL(auto evolution, table_->NewUpdatePartitionSpec()); + evolution->RemoveField("x"); + ASSERT_THAT(evolution->Commit(), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + ASSERT_NE(table_->metadata()->default_spec_id, data_file_->partition_spec_id); + auto scan_io = std::make_shared(); + EXPECT_CALL(*scan_io, NewInputFile(old_delete->file_path)) + .WillOnce( + [this](std::string path) { return file_io_->NewInputFile(std::move(path)); }); + ASSERT_THAT(DeletePositions({2}, scan_io), IsOk()); + EXPECT_THAT(ReadRows(), ::testing::ElementsAre(0, 4)); + auto task = Tasks().at(0); + ASSERT_EQ(task->delete_files().size(), 1); + const auto& dv = task->delete_files().front(); + EXPECT_EQ(dv->file_format, FileFormatType::kPuffin); + EXPECT_NE(dv->file_path, old_delete->file_path); + EXPECT_EQ(dv->partition_spec_id, data_file_->partition_spec_id); + EXPECT_EQ(dv->partition, data_file_->partition); +} + +class UnpartitionedPositionDeleteV3Test : public PositionDeleteV3Test { + protected: + bool unpartitioned() const override { return true; } +}; + +TEST_F(UnpartitionedPositionDeleteV3Test, ReloadsCommittedDeletes) { + ASSERT_THAT(DeletePositions({1, 2}), IsOk()); + EXPECT_THAT(ReadRows(), ::testing::ElementsAre(0, 3, 4)); +} + +TEST_F(PositionDeleteV3Test, RejectsPositionPastEndOfFile) { + EXPECT_THAT(DeletePositions({data_file_->record_count}), + IsError(ErrorKind::kInvalidArgument)); +} + +TEST_F(PositionDeleteV3Test, LostCommitResponsePreservesPublishedVector) { + auto task = Tasks().at(0); + auto mock = std::make_shared<::testing::NiceMock>(); + EXPECT_CALL(*mock, UpdateTable(::testing::_, ::testing::_, ::testing::_)) + .WillOnce([this](const auto& name, const auto& requirements, + const auto& updates) -> Result> { + ICEBERG_RETURN_UNEXPECTED(catalog_->UpdateTable(name, requirements, updates)); + return CommitStateUnknown("lost commit response"); + }); + ICEBERG_UNWRAP_OR_FAIL( + auto uncertain, + Table::Make(table_->name(), table_->metadata(), + std::string(table_->metadata_file_location()), file_io_, mock)); + ICEBERG_UNWRAP_OR_FAIL(auto delta, uncertain->NewRowDelta()); + EXPECT_THAT(internal::CommitPositionDeletes(*uncertain, *delta, + table_->metadata()->current_snapshot_id, + file_io_, {{task, {2}}}), + IsError(ErrorKind::kCommitStateUnknown)); + EXPECT_THAT(ReadRows(), ::testing::ElementsAre(0, 1, 3, 4)); +} + +TEST_F(PositionDeleteV3Test, ConcurrentRemovalRejectsPreparedDeletes) { + auto snapshot_id = table_->metadata()->current_snapshot_id; + auto task = Tasks().at(0); + + ICEBERG_UNWRAP_OR_FAIL(auto removal, table_->NewDeleteFiles()); + removal->DeleteFile(data_file_); + ASSERT_THAT(removal->Commit(), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + + ICEBERG_UNWRAP_OR_FAIL(auto delta, table_->NewRowDelta()); + EXPECT_THAT(internal::CommitPositionDeletes(*table_, *delta, snapshot_id, file_io_, + {{task, {1}}}), + IsError(ErrorKind::kValidationFailed)); + auto io = std::static_pointer_cast(file_io_); + ::arrow::fs::FileSelector selector; + selector.base_dir = table_location_ + "/data"; + const auto files = io->fs()->GetFileInfo(selector).ValueOrDie(); + ASSERT_EQ(files.size(), 1); + EXPECT_EQ(files.front().path(), data_file_->file_path); + EXPECT_TRUE(Tasks().empty()); +} + +} // namespace +} // namespace iceberg diff --git a/src/iceberg/test/std_io.h b/src/iceberg/test/std_io.h index b5b2a617c0..2ddd115283 100644 --- a/src/iceberg/test/std_io.h +++ b/src/iceberg/test/std_io.h @@ -319,11 +319,9 @@ class StdFileIO : public FileIO { Status DeleteFile(const std::string& file_location) override { std::error_code ec; - if (!std::filesystem::remove(file_location, ec)) { - if (ec) { - return IOError("Failed to delete file {}: {}", file_location, ec.message()); - } - return IOError("File does not exist: {}", file_location); + std::filesystem::remove(file_location, ec); + if (ec) { + return IOError("Failed to delete file {}: {}", file_location, ec.message()); } return {}; } diff --git a/src/iceberg/test/struct_like_test.cc b/src/iceberg/test/struct_like_test.cc index e04d2c089b..458b507a0d 100644 --- a/src/iceberg/test/struct_like_test.cc +++ b/src/iceberg/test/struct_like_test.cc @@ -40,6 +40,7 @@ #include "iceberg/manifest/manifest_reader_internal.h" #include "iceberg/row/arrow_array_wrapper.h" #include "iceberg/row/manifest_wrapper.h" +#include "iceberg/row/partition_values.h" #include "iceberg/schema.h" #include "iceberg/schema_internal.h" #include "iceberg/test/matchers.h" @@ -181,9 +182,7 @@ TEST(LiteralToScalarTest, Uuid) { TEST(StructLikeAccessorTest, GetLiteralUuid) { ICEBERG_UNWRAP_OR_FAIL(auto uuid, Uuid::FromString("123e4567-e89b-12d3-a456-426614174000")); - const auto& bytes = uuid.bytes(); - std::string_view uuid_data(reinterpret_cast(bytes.data()), bytes.size()); - SingleFieldStructLike row(Scalar{uuid_data}); + PartitionValues row(Literal::UUID(uuid)); std::array path = {0}; StructLikeAccessor accessor(iceberg::uuid(), path, {false});