diff --git a/dev/dv-fixtures/generate_go_fixtures.go b/dev/dv-fixtures/generate_go_fixtures.go new file mode 100644 index 000000000..67d26d6c0 --- /dev/null +++ b/dev/dv-fixtures/generate_go_fixtures.go @@ -0,0 +1,152 @@ +// 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. + +//go:build ignore + +package main + +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "strconv" + + "github.com/apache/iceberg-go/puffin" + "github.com/apache/iceberg-go/table/dv" +) + +type fixtureBlob struct { + referencedDataFile string + positions []uint64 + ranges []positionRange +} + +type positionRange struct { + start uint64 + end uint64 +} + +func writeFixture(outputDir, fileName, createdBy string, blobs []fixtureBlob) error { + var output bytes.Buffer + writer, err := puffin.NewWriter(&output) + if err != nil { + return err + } + if err := writer.SetCreatedBy(createdBy); err != nil { + return err + } + + for _, blob := range blobs { + bitmap := dv.NewRoaringPositionBitmap() + for _, position := range blob.positions { + bitmap.Set(position) + } + for _, positionRange := range blob.ranges { + bitmap.SetRange(positionRange.start, positionRange.end) + } + payload, err := dv.SerializeDV(bitmap) + if err != nil { + return err + } + _, err = writer.AddBlob(puffin.BlobMetadataInput{ + Type: puffin.BlobTypeDeletionVector, + SnapshotID: -1, + SequenceNumber: -1, + Fields: []int32{}, + Properties: map[string]string{ + "referenced-data-file": blob.referencedDataFile, + "cardinality": strconv.FormatInt(bitmap.Cardinality(), 10), + }, + }, payload) + if err != nil { + return err + } + } + + if err := writer.Finish(); err != nil { + return err + } + return os.WriteFile(filepath.Join(outputDir, fileName), output.Bytes(), 0o644) +} + +func main() { + if len(os.Args) != 2 { + fmt.Fprintln(os.Stderr, "usage: go run generate_go_fixtures.go OUTPUT_DIR") + os.Exit(2) + } + outputDir := os.Args[1] + if err := os.MkdirAll(outputDir, 0o755); err != nil { + panic(err) + } + + err := writeFixture(outputDir, "single-blob-dv.puffin", + "iceberg-go test fixture", []fixtureBlob{{ + referencedDataFile: "data/test.parquet", + positions: []uint64{1, 3, 5, 7, 9}, + }}) + if err != nil { + panic(err) + } + + err = writeFixture(outputDir, "multi-blob-dv.puffin", + "iceberg-go cross-language fixture", []fixtureBlob{ + { + referencedDataFile: "s3://warehouse/db/table/data/go-file-001.parquet", + positions: []uint64{ + 0, 100, 200, (uint64(1) << 32) + 7, + }, + }, + { + referencedDataFile: "s3://warehouse/db/table/data/go-file-002.parquet", + positions: []uint64{ + 50, 150, (uint64(2) << 32) + 9, + }, + }, + }) + if err != nil { + panic(err) + } + + position := func(bucket, container, value uint64) uint64 { + return (bucket << 32) + (container << 16) + value + } + allContainerPositions := []uint64{ + position(0, 0, 5), + position(0, 0, 7), + position(1, 0, 10), + position(1, 0, 20), + } + for bucket := uint64(0); bucket < 2; bucket++ { + for value := uint64(0); value < 10000; value += 2 { + allContainerPositions = + append(allContainerPositions, position(bucket, 2, value)) + } + } + err = writeFixture(outputDir, "all-container-types-dv.puffin", + "iceberg-go cross-language fixture", []fixtureBlob{{ + referencedDataFile: "s3://warehouse/db/table/data/all-containers.parquet", + positions: allContainerPositions, + ranges: []positionRange{ + {start: position(0, 1, 1), end: position(0, 1, 1000)}, + {start: position(1, 1, 10), end: position(1, 1, 500)}, + }, + }}) + if err != nil { + panic(err) + } +} diff --git a/src/iceberg/CMakeLists.txt b/src/iceberg/CMakeLists.txt index 8a98274ff..53b3230b4 100644 --- a/src/iceberg/CMakeLists.txt +++ b/src/iceberg/CMakeLists.txt @@ -26,6 +26,7 @@ set(ICEBERG_SOURCES catalog/memory/in_memory_catalog.cc catalog/session_catalog.cc catalog/session_context.cc + compaction_planner.cc delete_file_index.cc deletes/dv_util.cc deletes/dv_writer.cc diff --git a/src/iceberg/compaction_planner.cc b/src/iceberg/compaction_planner.cc new file mode 100644 index 000000000..c7e963ef6 --- /dev/null +++ b/src/iceberg/compaction_planner.cc @@ -0,0 +1,392 @@ +/* + * 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 "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/int128.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; +}; + +enum class Comparison { + kLess, + kEqual, + kGreater, +}; + +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( + std::isfinite(config.max_file_size_ratio) && config.max_file_size_ratio >= 1, + "max_file_size_ratio must be finite and at least 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; +} + +Comparison Compare(uint128_t lhs, uint128_t rhs) { + if (lhs < rhs) { + return Comparison::kLess; + } + if (lhs > rhs) { + return Comparison::kGreater; + } + return Comparison::kEqual; +} + +Comparison CompareIntegerToScaled(int64_t value, int64_t scale, double factor) { + if (factor == 0) { + return Compare(static_cast(value), uint128_t{0}); + } + + constexpr int64_t kLargestExactDoubleInteger = int64_t{1} << 53; + if (value <= kLargestExactDoubleInteger && scale <= kLargestExactDoubleInteger) { + // Preserve normal double threshold semantics while both integers are exact. + const double scaled = static_cast(scale) * factor; + if (static_cast(value) < scaled) { + return Comparison::kLess; + } + if (static_cast(value) > scaled) { + return Comparison::kGreater; + } + return Comparison::kEqual; + } + + // Avoid lossy integer-to-double conversion by comparing against the exact binary + // rational represented by factor. + int exponent = 0; + const double fraction = std::frexp(factor, &exponent); + constexpr int kDoubleDigits = std::numeric_limits::digits; + const auto significand = static_cast(std::ldexp(fraction, kDoubleDigits)); + const int shift = exponent - kDoubleDigits; + const uint128_t product = + static_cast(scale) * static_cast(significand); + constexpr uint128_t kMax = ~uint128_t{0}; + if (product == 0) { + return Compare(static_cast(value), uint128_t{0}); + } + + if (shift >= 0) { + if (shift >= 128 || product > (kMax >> shift)) { + return Comparison::kLess; + } + return Compare(static_cast(value), product << shift); + } + + const int left_shift = -shift; + const uint128_t lhs = static_cast(value); + if (lhs == 0) { + return Comparison::kLess; + } + if (left_shift >= 128 || lhs > (kMax >> left_shift)) { + return Comparison::kGreater; + } + return Compare(lhs << left_shift, product); +} + +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); + } + + ICEBERG_ASSIGN_OR_RAISE(result.file_scoped_delete_count, + CheckedAddNonNegative(result.file_scoped_delete_count, 1, + "File-scoped delete-file 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(); + ICEBERG_ASSIGN_OR_RAISE( + group.data_file_size_bytes, + CheckedAddNonNegative(group.data_file_size_bytes, data_file.file_size_in_bytes, + "Compaction group data-file size")); + 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; + 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(); + int64_t best_remaining = std::numeric_limits::max(); + for (size_t i = 0; i < bins.size(); ++i) { + const int64_t bin_size = bins[i].group.data_file_size_bytes; + if (bin_size > config.target_file_size_bytes || + file_size > config.target_file_size_bytes - bin_size) { + continue; + } + + const int64_t remaining = config.target_file_size_bytes - bin_size - file_size; + if (remaining < best_remaining) { + best_bin = i; + best_remaining = remaining; + } + } + + 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)); + } + + 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 = CompareIntegerToScaled( + data_file.file_size_in_bytes, config.target_file_size_bytes, + config.min_file_size_ratio) == Comparison::kLess; + const bool is_oversized = + CompareIntegerToScaled(data_file.file_size_in_bytes, + config.target_file_size_bytes, + config.max_file_size_ratio) == Comparison::kGreater; + 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 && + CompareIntegerToScaled(file.file_scoped_delete_record_count, + data_file.record_count, + config.delete_ratio_threshold) != Comparison::kLess; + const bool has_delete_pressure = has_many_delete_files || has_high_delete_ratio; + const bool should_compact = + is_oversized ? has_delete_pressure : is_small || has_delete_pressure; + if (!should_compact) { + 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 000000000..599ffbc8a --- /dev/null +++ b/src/iceberg/compaction_planner.h @@ -0,0 +1,126 @@ +/* + * 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. +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; + + /// Files larger than this ratio of the target size are oversized. + /// + /// Oversized files are selected only when they also meet an enabled delete-pressure + /// threshold. + double max_file_size_ratio = 1.8; + + /// 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/delete_file_index.cc b/src/iceberg/delete_file_index.cc index a8c4ef126..7a59c2b26 100644 --- a/src/iceberg/delete_file_index.cc +++ b/src/iceberg/delete_file_index.cc @@ -41,6 +41,7 @@ #include "iceberg/util/content_file_util.h" #include "iceberg/util/executor_util_internal.h" #include "iceberg/util/macros.h" +#include "iceberg/util/struct_like_set.h" namespace iceberg { @@ -453,10 +454,20 @@ Result> DeleteFileIndex::FindDV( return nullptr; } - ICEBERG_CHECK(it->second.sequence_number.value() >= seq, - "DV data sequence number {} must be greater than or equal to data file " - "sequence number {}", - it->second.sequence_number.value(), seq); + const auto& dv = *it->second.data_file; + ICEBERG_PRECHECK(data_file.partition_spec_id.has_value(), + "Missing partition spec id from data file {}", data_file.file_path); + ICEBERG_PRECHECK(dv.partition_spec_id.has_value(), + "Missing partition spec id from DV {}", dv.file_path); + if (dv.partition_spec_id != data_file.partition_spec_id) { + return nullptr; + } + + ICEBERG_ASSIGN_OR_RAISE(auto partitions_match, + StructLikeEqual(dv.partition, data_file.partition)); + if (!partitions_match || it->second.sequence_number.value() < seq) { + return nullptr; + } return it->second.data_file; } diff --git a/src/iceberg/meson.build b/src/iceberg/meson.build index 989f4ae03..404f8689a 100644 --- a/src/iceberg/meson.build +++ b/src/iceberg/meson.build @@ -79,6 +79,7 @@ iceberg_sources = files( 'catalog/memory/in_memory_catalog.cc', 'catalog/session_catalog.cc', 'catalog/session_context.cc', + 'compaction_planner.cc', 'delete_file_index.cc', 'deletes/dv_util.cc', 'deletes/dv_writer.cc', @@ -319,6 +320,7 @@ install_headers( [ 'arrow_c_data.h', 'catalog.h', + 'compaction_planner.h', 'constants.h', 'delete_file_index.h', 'exception.h', diff --git a/src/iceberg/test/CMakeLists.txt b/src/iceberg/test/CMakeLists.txt index 5ca9fd915..66b25b39a 100644 --- a/src/iceberg/test/CMakeLists.txt +++ b/src/iceberg/test/CMakeLists.txt @@ -158,10 +158,13 @@ add_iceberg_test(util_test add_iceberg_test(puffin_test USE_DATA SOURCES + puffin_dv_interop_test.cc puffin_format_test.cc 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 diff --git a/src/iceberg/test/compaction_planner_test.cc b/src/iceberg/test/compaction_planner_test.cc new file mode 100644 index 000000000..65eff74ca --- /dev/null +++ b/src/iceberg/test/compaction_planner_test.cc @@ -0,0 +1,420 @@ +/* + * 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, + .max_file_size_ratio = 2.0, + .min_input_files = 2, + .delete_file_threshold = 2, + .delete_ratio_threshold = 0.2, + }; + } +}; + +TEST_F(CompactionPlannerTest, ValidatesConfig) { + std::vector invalid; + + auto config = Config(); + config.target_file_size_bytes = 0; + invalid.push_back(config); + config = Config(); + config.min_file_size_ratio = -0.1; + invalid.push_back(config); + config = Config(); + config.min_file_size_ratio = 1.1; + invalid.push_back(config); + config = Config(); + config.min_file_size_ratio = std::numeric_limits::quiet_NaN(); + invalid.push_back(config); + config = Config(); + config.max_file_size_ratio = 0.9; + invalid.push_back(config); + config = Config(); + config.max_file_size_ratio = std::numeric_limits::infinity(); + invalid.push_back(config); + config = Config(); + config.min_input_files = 0; + invalid.push_back(config); + config = Config(); + config.delete_file_threshold = -1; + invalid.push_back(config); + config = Config(); + config.delete_ratio_threshold = -0.1; + invalid.push_back(config); + config = Config(); + config.delete_ratio_threshold = 1.1; + invalid.push_back(config); + config = Config(); + config.delete_ratio_threshold = std::numeric_limits::quiet_NaN(); + invalid.push_back(config); + + for (const auto& invalid_config : invalid) { + EXPECT_THAT(CompactionPlanner::Plan(kSnapshotId, {}, invalid_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, BindsPlanToSourceSnapshot) { + ICEBERG_UNWRAP_OR_FAIL(auto plan, CompactionPlanner::Plan(kSnapshotId, {}, Config())); + + EXPECT_EQ(plan.source_snapshot_id, kSnapshotId); + EXPECT_THAT(CompactionPlanner::Plan(-1, {}, Config()), + IsError(ErrorKind::kInvalidArgument)); +} + +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)); + 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, ComparesLargeFileSizeRatiosExactly) { + constexpr int64_t kMax = std::numeric_limits::max(); + auto config = Config(); + config.target_file_size_bytes = kMax; + config.min_file_size_ratio = std::nextafter(1.0, 0.0); + config.max_file_size_ratio = 1.0; + config.min_input_files = 1; + config.delete_file_threshold = 0; + config.delete_ratio_threshold = 0; + std::vector> tasks{ + Task(Data("below-boundary", 1, kMax - 1024)), + Task(Data("above-boundary", 2, kMax - 1023))}; + + ICEBERG_UNWRAP_OR_FAIL(auto plan, CompactionPlanner::Plan(kSnapshotId, tasks, config)); + ASSERT_THAT(plan.groups, SizeIs(1)); + EXPECT_THAT(Paths(plan.groups[0]), ElementsAre("below-boundary")); +} + +TEST_F(CompactionPlannerTest, ComparesLargeDeleteRatiosExactly) { + constexpr int64_t kMax = std::numeric_limits::max(); + auto config = Config(); + config.min_file_size_ratio = 0; + config.delete_file_threshold = 0; + config.delete_ratio_threshold = std::nextafter(1.0, 0.0); + std::vector> tasks{ + Task(Data("below-boundary", 1, 100, 1, kMax), + {PositionDelete("below.delete", "below-boundary", kMax - 1024)}), + Task(Data("at-boundary", 2, 100, 1, kMax), + {PositionDelete("at.delete", "at-boundary", kMax - 1023)})}; + + 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-boundary")); +} + +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, ReturnsErrorsForAggregateOverflow) { + constexpr int64_t kMax = std::numeric_limits::max(); + std::vector> file_overflow{ + Task(Data("data", 1, 100, 1, kMax), {PositionDelete("delete-a", "data", kMax), + PositionDelete("delete-b", "data", kMax)})}; + EXPECT_THAT(CompactionPlanner::Plan(kSnapshotId, file_overflow, Config()), + IsError(ErrorKind::kInvalidArgument)); + + std::vector> group_overflow{ + Task(Data("a", 1, 0, 1, kMax), {PositionDelete("delete-a", "a", kMax)}), + Task(Data("b", 1, 0, 1, kMax), {PositionDelete("delete-b", "b", kMax)})}; + EXPECT_THAT(CompactionPlanner::Plan(kSnapshotId, group_overflow, 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/delete_file_index_test.cc b/src/iceberg/test/delete_file_index_test.cc index 75c82bc39..340688632 100644 --- a/src/iceberg/test/delete_file_index_test.cc +++ b/src/iceberg/test/delete_file_index_test.cc @@ -65,6 +65,11 @@ class DeleteFileIndexTest : public testing::TestWithParam { PartitionSpec::Make( /*spec_id=*/1, {PartitionField(/*source_id=*/2, /*field_id=*/1000, "data_bucket", Transform::Bucket(16))})); + ICEBERG_UNWRAP_OR_FAIL( + equivalent_partitioned_spec_, + PartitionSpec::Make( + /*spec_id=*/2, {PartitionField(/*source_id=*/2, /*field_id=*/1000, + "data_bucket", Transform::Bucket(16))})); // Unpartitioned spec unpartitioned_spec_ = PartitionSpec::Unpartitioned(); @@ -187,6 +192,7 @@ class DeleteFileIndexTest : public testing::TestWithParam { std::unordered_map> GetSpecsById() { return {{partitioned_spec_->spec_id(), partitioned_spec_}, + {equivalent_partitioned_spec_->spec_id(), equivalent_partitioned_spec_}, {unpartitioned_spec_->spec_id(), unpartitioned_spec_}}; } @@ -209,6 +215,7 @@ class DeleteFileIndexTest : public testing::TestWithParam { std::shared_ptr file_io_; std::shared_ptr schema_; std::shared_ptr partitioned_spec_; + std::shared_ptr equivalent_partitioned_spec_; std::shared_ptr unpartitioned_spec_; std::shared_ptr file_a_; @@ -1041,8 +1048,9 @@ TEST_P(DeleteFileIndexTest, TestMixDeleteFilesAndDVs) { auto partition_b = PartitionValues({Literal::Int(1)}); // Position delete for file_a_ - auto pos_delete_a = MakePositionDeleteFile("/path/to/pos-delete-a.parquet", partition_a, - partitioned_spec_->spec_id()); + auto pos_delete_a = + MakePositionDeleteFile("/path/to/pos-delete-a.parquet", partition_a, + partitioned_spec_->spec_id(), file_a_->file_path); // DV for file_a_ (should take precedence) auto dv_a = MakeDV("/path/to/dv-a.puffin", partition_a, partitioned_spec_->spec_id(), file_a_->file_path); @@ -1113,7 +1121,82 @@ TEST_P(DeleteFileIndexTest, TestMultipleDVs) { EXPECT_THAT(index_result, HasErrorMessage(file_a_->file_path)); } -TEST_P(DeleteFileIndexTest, TestInvalidDVSequenceNumber) { +TEST_P(DeleteFileIndexTest, TestDVApplicability) { + auto version = GetParam(); + if (version < 3) { + GTEST_SKIP() << "DVs only supported in V3+"; + } + + const auto null_partition = PartitionValues({Literal::Null(int32())}); + auto null_partition_file = MakeDataFile("/path/to/data-null.parquet", null_partition, + partitioned_spec_->spec_id()); + + struct TestCase { + std::string name; + PartitionValues dv_partition; + std::shared_ptr dv_spec; + std::shared_ptr data_file; + bool applies; + }; + const std::vector cases = { + { + .name = "equal-partition", + .dv_partition = file_a_->partition, + .dv_spec = partitioned_spec_, + .data_file = file_a_, + .applies = true, + }, + { + .name = "different-spec", + .dv_partition = file_a_->partition, + .dv_spec = equivalent_partitioned_spec_, + .data_file = file_a_, + .applies = false, + }, + { + .name = "different-partition-value", + .dv_partition = file_b_->partition, + .dv_spec = partitioned_spec_, + .data_file = file_a_, + .applies = false, + }, + { + .name = "equal-null-partition", + .dv_partition = null_partition, + .dv_spec = partitioned_spec_, + .data_file = null_partition_file, + .applies = true, + }, + { + .name = "null-partition-mismatch", + .dv_partition = file_a_->partition, + .dv_spec = partitioned_spec_, + .data_file = null_partition_file, + .applies = false, + }, + }; + + for (const auto& test_case : cases) { + SCOPED_TRACE(test_case.name); + auto dv = MakeDV("/path/to/" + test_case.name + ".puffin", test_case.dv_partition, + test_case.dv_spec->spec_id(), test_case.data_file->file_path); + std::vector entries; + entries.push_back(MakeDeleteEntry(/*snapshot_id=*/1000L, /*sequence_number=*/2, dv)); + auto manifest = WriteDeleteManifest(version, /*snapshot_id=*/1000L, + std::move(entries), test_case.dv_spec); + ICEBERG_UNWRAP_OR_FAIL(auto index, BuildIndex({manifest})); + ICEBERG_UNWRAP_OR_FAIL(auto deletes, index->ForDataFile(1, *test_case.data_file)); + + if (test_case.applies) { + ASSERT_EQ(deletes.size(), 1); + EXPECT_EQ(deletes[0]->file_path, dv->file_path); + } else { + EXPECT_TRUE(deletes.empty()); + } + } +} + +TEST_P(DeleteFileIndexTest, TestInapplicableDVSequenceNumber) { auto version = GetParam(); if (version < 3) { GTEST_SKIP() << "DVs only supported in V3+"; @@ -1123,20 +1206,23 @@ TEST_P(DeleteFileIndexTest, TestInvalidDVSequenceNumber) { auto dv = MakeDV("/path/to/dv.puffin", partition_a, partitioned_spec_->spec_id(), file_a_->file_path); + auto pos_delete = + MakePositionDeleteFile("/path/to/pos-delete.parquet", partition_a, + partitioned_spec_->spec_id(), file_a_->file_path); std::vector entries; entries.push_back(MakeDeleteEntry(/*snapshot_id=*/1000L, /*sequence_number=*/1, dv)); + entries.push_back( + MakeDeleteEntry(/*snapshot_id=*/1000L, /*sequence_number=*/2, pos_delete)); auto manifest = WriteDeleteManifest(version, /*snapshot_id=*/1000L, std::move(entries), partitioned_spec_); ICEBERG_UNWRAP_OR_FAIL(auto index, BuildIndex({manifest})); - // Querying with sequence number > DV sequence number should fail - auto result = index->ForDataFile(2, *file_a_); - EXPECT_THAT(result, IsError(ErrorKind::kValidationFailed)); - EXPECT_THAT(result, HasErrorMessage( - "must be greater than or equal to data file sequence number")); + ICEBERG_UNWRAP_OR_FAIL(auto deletes, index->ForDataFile(2, *file_a_)); + ASSERT_EQ(deletes.size(), 1); + EXPECT_EQ(deletes[0]->file_path, pos_delete->file_path); } TEST_P(DeleteFileIndexTest, TestReferencedDeleteFiles) { diff --git a/src/iceberg/test/meson.build b/src/iceberg/test/meson.build index 6844df5e9..91ea41ed0 100644 --- a/src/iceberg/test/meson.build +++ b/src/iceberg/test/meson.build @@ -63,6 +63,7 @@ iceberg_tests = { 'update_schema_test.cc', ), }, + 'compaction_planner_test': {'sources': files('compaction_planner_test.cc')}, 'logging_test': { 'sources': files( 'cerr_logger_test.cc', diff --git a/src/iceberg/test/puffin_dv_interop_test.cc b/src/iceberg/test/puffin_dv_interop_test.cc new file mode 100644 index 000000000..b81dcdd51 --- /dev/null +++ b/src/iceberg/test/puffin_dv_interop_test.cc @@ -0,0 +1,256 @@ +/* + * 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/deletes/position_delete_index.h" +#include "iceberg/file_format.h" +#include "iceberg/manifest/manifest_entry.h" +#include "iceberg/metadata_columns.h" +#include "iceberg/puffin/file_metadata.h" +#include "iceberg/puffin/puffin_reader.h" +#include "iceberg/test/matchers.h" +#include "iceberg/test/std_io.h" +#include "iceberg/test/test_resource.h" + +namespace iceberg::puffin { + +namespace { + +constexpr std::string_view kReferencedDataFileProperty = "referenced-data-file"; +constexpr std::string_view kCardinalityProperty = "cardinality"; + +int64_t Position(int64_t bucket, int64_t container, int64_t value) { + return (bucket << 32) + (container << 16) + value; +} + +std::vector AllContainerPositions() { + std::vector positions = { + Position(0, 0, 5), + Position(0, 0, 7), + Position(1, 0, 10), + Position(1, 0, 20), + }; + positions.reserve(10004); + for (int64_t bucket = 0; bucket < 2; ++bucket) { + for (int64_t value = 0; value < 10000; value += 2) { + positions.push_back(Position(bucket, 2, value)); + } + } + return positions; +} + +struct PositionRange { + int64_t begin; + int64_t end; +}; + +struct ExpectedBlob { + std::string referenced_data_file; + std::vector input_fields; + int64_t offset; + int64_t length; + int64_t cardinality; + std::vector positions; + std::vector ranges; +}; + +std::shared_ptr MakeDeleteFile(const ExpectedBlob& expected, + const std::string& fixture_path, + int64_t file_size) { + return std::make_shared(DataFile{ + .content = DataFile::Content::kPositionDeletes, + .file_path = fixture_path, + .file_format = FileFormatType::kPuffin, + .record_count = expected.cardinality, + .file_size_in_bytes = file_size, + .referenced_data_file = expected.referenced_data_file, + .content_offset = expected.offset, + .content_size_in_bytes = expected.length, + }); +} + +void AssertPositions(const ExpectedBlob& expected, + const std::shared_ptr& delete_file, + const std::shared_ptr& io) { + ASSERT_TRUE(delete_file->content_offset.has_value()); + ASSERT_TRUE(delete_file->content_size_in_bytes.has_value()); + ICEBERG_UNWRAP_OR_FAIL(auto input_file, io->NewInputFile(delete_file->file_path)); + ICEBERG_UNWRAP_OR_FAIL(auto stream, input_file->Open()); + std::vector data(static_cast(*delete_file->content_size_in_bytes)); + ASSERT_THAT(stream->ReadFully(*delete_file->content_offset, data), IsOk()); + + std::span blob(reinterpret_cast(data.data()), + data.size()); + ICEBERG_UNWRAP_OR_FAIL(auto positions, + PositionDeleteIndex::Deserialize(blob, delete_file)); + EXPECT_EQ(positions.Cardinality(), expected.cardinality); + int64_t expected_cardinality = static_cast(expected.positions.size()); + for (const auto& range : expected.ranges) { + expected_cardinality += range.end - range.begin; + } + ASSERT_EQ(expected_cardinality, expected.cardinality); + for (int64_t position : expected.positions) { + EXPECT_TRUE(positions.IsDeleted(position)) << "Missing position " << position; + } + for (const auto& range : expected.ranges) { + for (int64_t position = range.begin; position < range.end; ++position) { + ASSERT_TRUE(positions.IsDeleted(position)) << "Missing position " << position; + } + } +} + +void AssertFixture(const std::string& resource_name, + const std::vector& expected_blobs) { + const std::string fixture_path = GetResourcePath(resource_name); + const auto file_size = static_cast(std::filesystem::file_size(fixture_path)); + auto io = std::make_shared(); + ICEBERG_UNWRAP_OR_FAIL(auto input_file, io->NewInputFile(fixture_path)); + ICEBERG_UNWRAP_OR_FAIL(auto reader, PuffinReader::Make(std::move(input_file))); + ICEBERG_UNWRAP_OR_FAIL(auto metadata, reader->ReadFileMetadata()); + + ASSERT_EQ(metadata.blobs.size(), expected_blobs.size()); + std::unordered_set seen; + for (const auto& blob : metadata.blobs) { + const auto& referenced_data_file = + blob.properties.at(std::string(kReferencedDataFileProperty)); + auto expected = std::ranges::find_if(expected_blobs, [&](const auto& candidate) { + return candidate.referenced_data_file == referenced_data_file; + }); + ASSERT_NE(expected, expected_blobs.end()) + << "Unexpected referenced data file " << referenced_data_file; + ASSERT_TRUE(seen.insert(referenced_data_file).second) + << "Duplicate referenced data file " << referenced_data_file; + + EXPECT_EQ(blob.type, StandardBlobTypes::kDeletionVectorV1); + EXPECT_EQ(blob.input_fields, expected->input_fields); + EXPECT_EQ(blob.snapshot_id, -1); + EXPECT_EQ(blob.sequence_number, -1); + EXPECT_EQ(blob.offset, expected->offset); + EXPECT_EQ(blob.length, expected->length); + EXPECT_TRUE(blob.compression_codec.empty()); + EXPECT_EQ(blob.properties.at(std::string(kCardinalityProperty)), + std::to_string(expected->cardinality)); + + AssertPositions(*expected, MakeDeleteFile(*expected, fixture_path, file_size), io); + } + EXPECT_EQ(seen.size(), expected_blobs.size()); +} + +} // namespace + +TEST(PuffinDVInteropTest, ReadsJavaSingleBlobFixture) { + AssertFixture( + "deletion_vectors/java/single-blob-dv.puffin", + {{ + .referenced_data_file = "s3://warehouse/db/table/data/00000-0-abc.parquet", + .input_fields = {MetadataColumns::kFilePositionColumnId}, + .offset = 4, + .length = 50, + .cardinality = 5, + .positions = {1, 3, 5, 7, 9}, + }}); +} + +TEST(PuffinDVInteropTest, ReadsJavaMultiBlobFixture) { + AssertFixture( + "deletion_vectors/java/multi-blob-dv.puffin", + { + { + .referenced_data_file = "s3://warehouse/db/table/data/file-001.parquet", + .input_fields = {MetadataColumns::kFilePositionColumnId}, + .offset = 4, + .length = 46, + .cardinality = 3, + .positions = {0, 100, 200}, + }, + { + .referenced_data_file = "s3://warehouse/db/table/data/file-002.parquet", + .input_fields = {MetadataColumns::kFilePositionColumnId}, + .offset = 50, + .length = 44, + .cardinality = 2, + .positions = {50, 150}, + }, + }); +} + +TEST(PuffinDVInteropTest, ReadsGoSingleBlobFixture) { + AssertFixture("deletion_vectors/go/single-blob-dv.puffin", + {{ + .referenced_data_file = "data/test.parquet", + .input_fields = {}, + .offset = 4, + .length = 50, + .cardinality = 5, + .positions = {1, 3, 5, 7, 9}, + }}); +} + +TEST(PuffinDVInteropTest, ReadsGoMultiBlobFixture) { + AssertFixture( + "deletion_vectors/go/multi-blob-dv.puffin", + { + { + .referenced_data_file = "s3://warehouse/db/table/data/go-file-001.parquet", + .input_fields = {}, + .offset = 4, + .length = 68, + .cardinality = 4, + .positions = {0, 100, 200, (int64_t{1} << 32) + 7}, + }, + { + .referenced_data_file = "s3://warehouse/db/table/data/go-file-002.parquet", + .input_fields = {}, + .offset = 72, + .length = 66, + .cardinality = 3, + .positions = {50, 150, (int64_t{2} << 32) + 9}, + }, + }); +} + +TEST(PuffinDVInteropTest, ReadsGoAllContainerTypesFixture) { + AssertFixture( + "deletion_vectors/go/all-container-types-dv.puffin", + {{ + .referenced_data_file = "s3://warehouse/db/table/data/all-containers.parquet", + .input_fields = {}, + .offset = 4, + .length = 16466, + .cardinality = 11493, + .positions = AllContainerPositions(), + .ranges = + { + {Position(0, 1, 1), Position(0, 1, 1000)}, + {Position(1, 1, 10), Position(1, 1, 500)}, + }, + }}); +} + +} // namespace iceberg::puffin diff --git a/src/iceberg/test/resources/deletion_vectors/README.md b/src/iceberg/test/resources/deletion_vectors/README.md new file mode 100644 index 000000000..983cbfe3e --- /dev/null +++ b/src/iceberg/test/resources/deletion_vectors/README.md @@ -0,0 +1,44 @@ +# Deletion vector interoperability fixtures + +These fixtures verify deletion-vector compatibility against bytes produced by +implementations other than Iceberg C++. + +## Java fixtures + +The files under `java/` were copied byte-for-byte from Apache Iceberg Go commit +`3020adbbc3faff047da6f483f739f1b5e1de611b`, where they are consumed by +`table/dv/dv_cross_client_test.go`. + +- `single-blob-dv.puffin` and `multi-blob-dv.puffin` were produced by Apache + Iceberg Java using + `iceberg-go/dev/dv-fixtures/GenerateDVFixtures.java`. + +The committed Puffin bytes were reproduced against Apache Iceberg Java commit +`76d35b1e40f77edcad19646bb6afdd9f05249964`. To regenerate them, follow +`iceberg-go/dev/dv-fixtures/README.md` at the Iceberg Go commit above using +that Java revision, then copy the generated files into `java/`. + +## Go fixtures + +The files under `go/` are produced with the Iceberg Go Puffin and deletion +vector writers. From an Iceberg Go checkout at commit +`3020adbbc3faff047da6f483f739f1b5e1de611b`, run: + +```bash +go run /path/to/iceberg-cpp/dev/dv-fixtures/generate_go_fixtures.go \ + /path/to/iceberg-cpp/src/iceberg/test/resources/deletion_vectors/go +``` + +The multi-blob fixture includes positions in three distinct high-32-bit +buckets. `all-container-types-dv.puffin` covers array, run, and bitmap +containers inside a complete Puffin file. + +## Checksums + +```text +ab8309671c0c5ef1956f4f1d7b907f4a69ffeb154ab77d5a4855d7dd4779108c java/single-blob-dv.puffin +fed7edbb5a343a6c6fc4706ff4c213ab3f0a50916baeb228619f1f2c956f3f27 java/multi-blob-dv.puffin +dd293e827439cd22053a9356ae6d56f0d5d69e648b1850d39663cdc5c7ec5a77 go/single-blob-dv.puffin +000a77697d5ddce01e0242786b91fc15482a8b8f4fa3c8e214a936d7c2fc978b go/multi-blob-dv.puffin +d9f374706891b4780f8a59f155a7cc4cae4161b6415578abb4790f6eed793a52 go/all-container-types-dv.puffin +``` diff --git a/src/iceberg/test/resources/deletion_vectors/go/all-container-types-dv.puffin b/src/iceberg/test/resources/deletion_vectors/go/all-container-types-dv.puffin new file mode 100644 index 000000000..5582a008e Binary files /dev/null and b/src/iceberg/test/resources/deletion_vectors/go/all-container-types-dv.puffin differ diff --git a/src/iceberg/test/resources/deletion_vectors/go/multi-blob-dv.puffin b/src/iceberg/test/resources/deletion_vectors/go/multi-blob-dv.puffin new file mode 100644 index 000000000..4404137af Binary files /dev/null and b/src/iceberg/test/resources/deletion_vectors/go/multi-blob-dv.puffin differ diff --git a/src/iceberg/test/resources/deletion_vectors/go/single-blob-dv.puffin b/src/iceberg/test/resources/deletion_vectors/go/single-blob-dv.puffin new file mode 100644 index 000000000..84c6baf79 Binary files /dev/null and b/src/iceberg/test/resources/deletion_vectors/go/single-blob-dv.puffin differ diff --git a/src/iceberg/test/resources/deletion_vectors/java/multi-blob-dv.puffin b/src/iceberg/test/resources/deletion_vectors/java/multi-blob-dv.puffin new file mode 100644 index 000000000..b9037900c Binary files /dev/null and b/src/iceberg/test/resources/deletion_vectors/java/multi-blob-dv.puffin differ diff --git a/src/iceberg/test/resources/deletion_vectors/java/single-blob-dv.puffin b/src/iceberg/test/resources/deletion_vectors/java/single-blob-dv.puffin new file mode 100644 index 000000000..5c0007e21 Binary files /dev/null and b/src/iceberg/test/resources/deletion_vectors/java/single-blob-dv.puffin differ