From 8bb7ee71653f1cee9f31cf4ca69a28e0a4649cb6 Mon Sep 17 00:00:00 2001 From: Zhuo Wang Date: Fri, 4 Dec 2026 21:21:29 +0800 Subject: [PATCH] refactor: extract ReachableFileUtil from ExpireSnapshots Add a public ReachableFileUtil mirroring Java's ReachableFileUtil, and make ExpireSnapshots' reachable file cleanup use it for reading snapshot manifests and live file paths. Co-Authored-By: Claude Opus 4.8 --- src/iceberg/CMakeLists.txt | 1 + src/iceberg/cpp20_compatibility_internal.h | 1 + src/iceberg/test/CMakeLists.txt | 1 + src/iceberg/test/reachable_file_util_test.cc | 276 +++++++++++++++++++ src/iceberg/update/expire_snapshots.cc | 47 +--- src/iceberg/util/reachable_file_util.cc | 242 ++++++++++++++++ src/iceberg/util/reachable_file_util.h | 139 ++++++++++ 7 files changed, 667 insertions(+), 40 deletions(-) create mode 100644 src/iceberg/test/reachable_file_util_test.cc create mode 100644 src/iceberg/util/reachable_file_util.cc create mode 100644 src/iceberg/util/reachable_file_util.h diff --git a/src/iceberg/CMakeLists.txt b/src/iceberg/CMakeLists.txt index f9604e257..57cc382d7 100644 --- a/src/iceberg/CMakeLists.txt +++ b/src/iceberg/CMakeLists.txt @@ -166,6 +166,7 @@ set(ICEBERG_SOURCES util/mumbling_bitmap.cc util/murmurhash3_internal.cc util/property_util.cc + util/reachable_file_util.cc util/retry_util.cc util/scheduled_executor.cc util/snapshot_util.cc diff --git a/src/iceberg/cpp20_compatibility_internal.h b/src/iceberg/cpp20_compatibility_internal.h index 93d716e95..a803bd5e2 100644 --- a/src/iceberg/cpp20_compatibility_internal.h +++ b/src/iceberg/cpp20_compatibility_internal.h @@ -199,6 +199,7 @@ #include "iceberg/util/macros.h" #include "iceberg/util/partition_value_util.h" #include "iceberg/util/property_util.h" +#include "iceberg/util/reachable_file_util.h" #include "iceberg/util/retry_util.h" #include "iceberg/util/snapshot_util.h" #include "iceberg/util/stream.h" diff --git a/src/iceberg/test/CMakeLists.txt b/src/iceberg/test/CMakeLists.txt index 125ba128a..91aaec26c 100644 --- a/src/iceberg/test/CMakeLists.txt +++ b/src/iceberg/test/CMakeLists.txt @@ -332,6 +332,7 @@ if(ICEBERG_BUILD_BUNDLE) update_sort_order_test.cc update_statistics_test.cc overwrite_files_test.cc + reachable_file_util_test.cc replace_partitions_test.cc) add_iceberg_test(data_test diff --git a/src/iceberg/test/reachable_file_util_test.cc b/src/iceberg/test/reachable_file_util_test.cc new file mode 100644 index 000000000..926712c89 --- /dev/null +++ b/src/iceberg/test/reachable_file_util_test.cc @@ -0,0 +1,276 @@ +/* + * 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/util/reachable_file_util.h" + +#include +#include +#include +#include +#include +#include + +#include + +#include "iceberg/avro/avro_register.h" +#include "iceberg/manifest/manifest_entry.h" +#include "iceberg/manifest/manifest_writer.h" +#include "iceberg/partition_spec.h" +#include "iceberg/schema.h" +#include "iceberg/snapshot.h" +#include "iceberg/statistics_file.h" +#include "iceberg/table_metadata.h" +#include "iceberg/test/executor.h" +#include "iceberg/test/matchers.h" +#include "iceberg/test/update_test_base.h" + +namespace iceberg { + +namespace { + +using ::testing::ElementsAre; +using ::testing::UnorderedElementsAre; + +constexpr int64_t kFirstSnapshotId = 3051729675574597004; +constexpr int64_t kSecondSnapshotId = 3055729675574597004; + +std::unordered_set ManifestPaths( + const std::unordered_set& manifests) { + std::unordered_set paths; + for (const auto& manifest : manifests) { + paths.insert(manifest.manifest_path); + } + return paths; +} + +} // namespace + +class ReachableFileUtilTest : public UpdateTestBase { + protected: + void SetUp() override { + UpdateTestBase::SetUp(); + avro::RegisterAll(); + metadata_ = ReloadMetadata(); + } + + std::shared_ptr MakeDataFile(const std::string& path) const { + return std::make_shared(DataFile{ + .file_path = path, + .file_format = FileFormatType::kParquet, + .partition = PartitionValues({Literal::Long(1)}), + .record_count = 1, + .file_size_in_bytes = 10, + .sort_order_id = 0, + }); + } + + ManifestEntry MakeEntry(ManifestStatus status, int64_t snapshot_id, + std::shared_ptr file) const { + return ManifestEntry{ + .status = status, + .snapshot_id = snapshot_id, + .sequence_number = 0, + .file_sequence_number = 0, + .data_file = std::move(file), + }; + } + + ManifestFile WriteDataManifest(const std::string& path, int64_t snapshot_id, + const std::vector& entries) { + ICEBERG_ASSIGN_OR_THROW(auto schema, metadata_->Schema()); + ICEBERG_ASSIGN_OR_THROW(auto spec, + metadata_->PartitionSpecById(metadata_->default_spec_id)); + auto writer_result = ManifestWriter::MakeWriter( + metadata_->format_version, snapshot_id, path, file_io_, spec, schema, + ManifestContent::kData, /*first_row_id=*/std::nullopt); + EXPECT_THAT(writer_result, IsOk()); + auto writer = std::move(writer_result.value()); + for (const auto& entry : entries) { + EXPECT_THAT(writer->WriteEntry(entry), IsOk()); + } + EXPECT_THAT(writer->Close(), IsOk()); + auto manifest_result = writer->ToManifestFile(); + EXPECT_THAT(manifest_result, IsOk()); + // Committed manifests carry the sequence number assigned by their snapshot. + auto manifest = std::move(manifest_result.value()); + manifest.sequence_number = 0; + manifest.min_sequence_number = 0; + return manifest; + } + + void WriteManifestList(const std::string& path, int64_t snapshot_id, + int64_t parent_snapshot_id, + const std::vector& manifests) { + auto writer_result = ManifestListWriter::MakeWriter( + metadata_->format_version, snapshot_id, parent_snapshot_id, path, file_io_, + /*sequence_number=*/std::optional(0), + /*first_row_id=*/std::nullopt); + ASSERT_THAT(writer_result, IsOk()); + auto writer = std::move(writer_result.value()); + ASSERT_THAT(writer->AddAll(manifests), IsOk()); + ASSERT_THAT(writer->Close(), IsOk()); + } + + /// \brief Point both snapshots at manifest lists written to the mock file system. + void WriteSnapshotManifests() { + const auto metadata_dir = table_location_ + "/metadata/"; + shared_manifest_ = WriteDataManifest( + metadata_dir + "shared.avro", kFirstSnapshotId, + {MakeEntry(ManifestStatus::kAdded, kFirstSnapshotId, + MakeDataFile(table_location_ + "/data/shared.parquet"))}); + second_manifest_ = WriteDataManifest( + metadata_dir + "second.avro", kSecondSnapshotId, + {MakeEntry(ManifestStatus::kAdded, kSecondSnapshotId, + MakeDataFile(table_location_ + "/data/live.parquet")), + MakeEntry(ManifestStatus::kDeleted, kSecondSnapshotId, + MakeDataFile(table_location_ + "/data/removed.parquet"))}); + + const auto first_manifest_list = metadata_dir + "snap-1.avro"; + const auto second_manifest_list = metadata_dir + "snap-2.avro"; + WriteManifestList(first_manifest_list, kFirstSnapshotId, 0, {shared_manifest_}); + WriteManifestList(second_manifest_list, kSecondSnapshotId, kFirstSnapshotId, + {shared_manifest_, second_manifest_}); + + metadata_->snapshots.at(0)->manifest_list = first_manifest_list; + metadata_->snapshots.at(1)->manifest_list = second_manifest_list; + } + + std::shared_ptr metadata_; + ManifestFile shared_manifest_; + ManifestFile second_manifest_; +}; + +TEST_F(ReachableFileUtilTest, LocationsFromMetadata) { + EXPECT_EQ(ReachableFileUtil::VersionHintLocation("s3://bucket/db/tbl"), + "s3://bucket/db/tbl/metadata/version-hint.text"); + EXPECT_EQ(ReachableFileUtil::VersionHintLocation("s3://bucket/db/tbl/"), + "s3://bucket/db/tbl/metadata/version-hint.text"); + + EXPECT_THAT(ReachableFileUtil::ManifestListLocations(*metadata_), + UnorderedElementsAre("s3://a/b/1.avro", "s3://a/b/2.avro")); + EXPECT_THAT(ReachableFileUtil::ManifestListLocations(*metadata_, {kSecondSnapshotId}), + ElementsAre("s3://a/b/2.avro")); + EXPECT_TRUE(ReachableFileUtil::ManifestListLocations(*metadata_, {}).empty()); + + auto stats = std::make_shared(); + stats->snapshot_id = kFirstSnapshotId; + stats->path = "s3://a/b/stats-1.puffin"; + auto partition_stats = std::make_shared(); + partition_stats->snapshot_id = kSecondSnapshotId; + partition_stats->path = "s3://a/b/partition-stats-2.parquet"; + metadata_->statistics = {stats}; + metadata_->partition_statistics = {partition_stats}; + + EXPECT_THAT(ReachableFileUtil::StatisticsFilesLocations(*metadata_), + UnorderedElementsAre("s3://a/b/stats-1.puffin", + "s3://a/b/partition-stats-2.parquet")); + EXPECT_THAT(ReachableFileUtil::StatisticsFilesLocationsForSnapshots( + *metadata_, {kSecondSnapshotId}), + ElementsAre("s3://a/b/partition-stats-2.parquet")); +} + +TEST_F(ReachableFileUtilTest, MetadataFileLocations) { + const auto metadata_dir = table_location_ + "/metadata/"; + const auto v1 = metadata_dir + "v1.metadata.json"; + const auto v2 = metadata_dir + "v2.metadata.json"; + const auto v3 = metadata_dir + "v3.metadata.json"; + const auto gone = metadata_dir + "gone.json"; + + // v2 lists v1, which was pruned from v3's log. + auto v2_metadata = std::make_shared(*metadata_); + v2_metadata->metadata_log = { + {.timestamp_ms = TimePointMsFromUnixMs(1), .metadata_file = v1}, + }; + ASSERT_THAT(TableMetadataUtil::Write(*file_io_, v2, *v2_metadata), IsOk()); + + // v3 lists a missing file, which recursion skips, and v2. + metadata_->metadata_log = { + {.timestamp_ms = TimePointMsFromUnixMs(2), .metadata_file = gone}, + {.timestamp_ms = TimePointMsFromUnixMs(3), .metadata_file = v2}, + }; + + EXPECT_THAT(ReachableFileUtil::MetadataFileLocations(*metadata_, v3, file_io_, + /*recursive=*/false), + UnorderedElementsAre(gone, v2, v3)); + EXPECT_THAT(ReachableFileUtil::MetadataFileLocations(*metadata_, "", file_io_, + /*recursive=*/false), + UnorderedElementsAre(gone, v2)); + EXPECT_THAT(ReachableFileUtil::MetadataFileLocations(*metadata_, v3, file_io_, + /*recursive=*/true), + UnorderedElementsAre(gone, v1, v2, v3)); + + // Recursion stops when readable metadata files list each other. + v2_metadata->metadata_log = { + {.timestamp_ms = TimePointMsFromUnixMs(3), .metadata_file = v3}, + }; + ASSERT_THAT(TableMetadataUtil::Write(*file_io_, v2, *v2_metadata), IsOk()); + ASSERT_THAT(TableMetadataUtil::Write(*file_io_, v3, *metadata_), IsOk()); + EXPECT_THAT(ReachableFileUtil::MetadataFileLocations(*metadata_, v3, file_io_, + /*recursive=*/true), + UnorderedElementsAre(gone, v2, v3)); + // Without a starting location, the cycle is still cut once v2 is revisited. + EXPECT_THAT(ReachableFileUtil::MetadataFileLocations(*metadata_, "", file_io_, + /*recursive=*/true), + UnorderedElementsAre(gone, v2, v3)); +} + +TEST_F(ReachableFileUtilTest, Manifests) { + WriteSnapshotManifests(); + + ICEBERG_UNWRAP_OR_FAIL(auto first, ReachableFileUtil::ManifestsForSnapshots( + *metadata_, {kFirstSnapshotId}, file_io_)); + EXPECT_THAT(ManifestPaths(first), UnorderedElementsAre(shared_manifest_.manifest_path)); + + test::InlineExecutor executor; + ICEBERG_UNWRAP_OR_FAIL(auto all, ReachableFileUtil::ReachableManifests( + *metadata_, file_io_, std::ref(executor))); + EXPECT_THAT(ManifestPaths(all), UnorderedElementsAre(shared_manifest_.manifest_path, + second_manifest_.manifest_path)); + EXPECT_EQ(executor.submit_count(), 2); + + EXPECT_THAT(ReachableFileUtil::ManifestsForSnapshots(*metadata_, {12345}, file_io_), + IsError(ErrorKind::kNotFound)); +} + +TEST_F(ReachableFileUtilTest, LiveFileLocations) { + WriteSnapshotManifests(); + + // Deleted entries are excluded. + ICEBERG_UNWRAP_OR_FAIL(auto second, ReachableFileUtil::LiveFileLocations( + second_manifest_, *metadata_, file_io_)); + EXPECT_THAT(second, UnorderedElementsAre(table_location_ + "/data/live.parquet")); + + ICEBERG_UNWRAP_OR_FAIL(auto all, + ReachableFileUtil::LiveFileLocationsForManifests( + {shared_manifest_, second_manifest_}, *metadata_, file_io_)); + EXPECT_THAT(all, UnorderedElementsAre(table_location_ + "/data/shared.parquet", + table_location_ + "/data/live.parquet")); + + ICEBERG_UNWRAP_OR_FAIL(auto none, ReachableFileUtil::LiveFileLocationsForManifests( + {}, *metadata_, file_io_)); + EXPECT_TRUE(none.empty()); + + ManifestFile missing = second_manifest_; + missing.manifest_path = table_location_ + "/metadata/missing.avro"; + EXPECT_THAT(ReachableFileUtil::LiveFileLocationsForManifests( + {shared_manifest_, missing}, *metadata_, file_io_), + IsError(ErrorKind::kIOError)); +} + +} // namespace iceberg diff --git a/src/iceberg/update/expire_snapshots.cc b/src/iceberg/update/expire_snapshots.cc index 541d16e45..244d9ba13 100644 --- a/src/iceberg/update/expire_snapshots.cc +++ b/src/iceberg/update/expire_snapshots.cc @@ -44,6 +44,7 @@ #include "iceberg/util/error_collector.h" #include "iceberg/util/executor_util_internal.h" #include "iceberg/util/macros.h" +#include "iceberg/util/reachable_file_util.h" #include "iceberg/util/retry_util.h" #include "iceberg/util/snapshot_util.h" #include "iceberg/util/string_util.h" @@ -265,25 +266,11 @@ class ReachableFileCleanup : public FileCleanupStrategy { } private: - /// \brief Collect manifests for a snapshot into manifests. - Result> ReadManifestsForSnapshot( - const TableMetadata& metadata, int64_t snapshot_id) { - ICEBERG_ASSIGN_OR_RAISE(auto snapshot, metadata.SnapshotById(snapshot_id)); - - SnapshotReader snapshot_reader(snapshot.get()); - ICEBERG_ASSIGN_OR_RAISE(auto snapshot_manifests, snapshot_reader.Manifests(file_io_)); - - return snapshot_manifests | std::views::as_rvalue | - std::ranges::to>(); - } - /// \brief Collect manifests for a set of snapshots. Result> ReadManifests( const TableMetadata& metadata, const std::unordered_set& snapshot_ids) { - return ParallelCollect(plan_executor_, snapshot_ids, - [this, &metadata](int64_t snapshot_id) { - return ReadManifestsForSnapshot(metadata, snapshot_id); - }); + return ReachableFileUtil::ManifestsForSnapshots(metadata, snapshot_ids, file_io_, + plan_executor_); } /// \brief Remove manifests still referenced by retained snapshots. @@ -305,24 +292,6 @@ class ReachableFileCleanup : public FileCleanupStrategy { return manifests_to_delete; } - Result> ReadLiveFilePaths( - const TableMetadata& metadata, const ManifestFile& manifest) { - // TODO(shangxinli): optimize by only reading file paths - ICEBERG_ASSIGN_OR_RAISE(auto reader, - MakeManifestReader(manifest, file_io_, metadata)); - reader->Select({"file_path"}); - ICEBERG_ASSIGN_OR_RAISE(auto entries, reader->LiveEntries()); - - std::unordered_set file_paths; - for (const auto& entry : entries) { - if (entry.data_file) { - file_paths.insert(entry.data_file->file_path); - } - } - - return file_paths; - } - /// \brief Project manifests to manifest paths for deletion. std::unordered_set ManifestPaths( const std::unordered_set& manifests) const { @@ -344,7 +313,8 @@ class ReachableFileCleanup : public FileCleanupStrategy { plan_executor_, manifests_to_delete, [this, &metadata]( const ManifestFile& manifest) -> Result> { - auto result = ReadLiveFilePaths(metadata, manifest); + auto result = + ReachableFileUtil::LiveFileLocations(manifest, metadata, file_io_); // Ignore expired-manifest read failures and keep scanning candidates. if (!result.has_value()) { return std::unordered_set{}; @@ -360,11 +330,8 @@ class ReachableFileCleanup : public FileCleanupStrategy { } // Remove files still referenced by current manifests. - auto current_live_results = - ParallelCollect(plan_executor_, current_manifests, - [this, &metadata](const ManifestFile& manifest) { - return ReadLiveFilePaths(metadata, manifest); - }); + auto current_live_results = ReachableFileUtil::LiveFileLocationsForManifests( + current_manifests, metadata, file_io_, plan_executor_); // Fail closed if any retained manifest cannot be read safely. if (!current_live_results.has_value()) { return std::unordered_set{}; diff --git a/src/iceberg/util/reachable_file_util.cc b/src/iceberg/util/reachable_file_util.cc new file mode 100644 index 000000000..7279d751e --- /dev/null +++ b/src/iceberg/util/reachable_file_util.cc @@ -0,0 +1,242 @@ +/* + * 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/util/reachable_file_util.h" + +#include +#include +#include +#include + +#include "iceberg/file_io.h" +#include "iceberg/logging/log_macros.h" +#include "iceberg/manifest/manifest_entry.h" +#include "iceberg/manifest/manifest_reader.h" +#include "iceberg/snapshot.h" +#include "iceberg/statistics_file.h" +#include "iceberg/table_metadata.h" +#include "iceberg/util/executor_util_internal.h" +#include "iceberg/util/location_util.h" +#include "iceberg/util/macros.h" + +namespace iceberg { + +namespace { + +constexpr std::string_view kMetadataFolderName = "metadata"; + +/// \brief Read the first previous metadata file that can be loaded. +std::unique_ptr FindFirstExistentPreviousMetadata( + const std::vector& metadata_log, FileIO& io, + std::unordered_set& visited, size_t depth) { + for (size_t i = 0; i < metadata_log.size(); ++i) { + const auto& location = metadata_log[i].metadata_file; + // Guard against metadata logs that reference each other in a cycle. + if (!visited.insert(location).second) { + continue; + } + auto metadata = TableMetadataUtil::Read(io, location); + if (metadata.has_value()) { + return std::move(metadata).value(); + } + // Locations and IO errors may carry credentials, so log neither. + ICEBERG_LOG_WARN( + "Skipping unreadable previous metadata file at index {} of the metadata log {} " + "level(s) back", + i, depth); + } + return nullptr; +} + +/// \brief Return the snapshots with the given IDs, failing if any is missing. +Result>> SnapshotsByIds( + const TableMetadata& metadata, const std::unordered_set& snapshot_ids) { + std::unordered_map> snapshots_by_id; + snapshots_by_id.reserve(metadata.snapshots.size()); + for (const auto& snapshot : metadata.snapshots) { + if (snapshot) { + snapshots_by_id.emplace(snapshot->snapshot_id, snapshot); + } + } + + std::vector> snapshots; + snapshots.reserve(snapshot_ids.size()); + for (int64_t snapshot_id : snapshot_ids) { + auto it = snapshots_by_id.find(snapshot_id); + if (it == snapshots_by_id.end()) { + return NotFound("Snapshot with ID {} is not found", snapshot_id); + } + snapshots.push_back(it->second); + } + return snapshots; +} + +template +std::vector StatisticsFilesLocationsIf(const TableMetadata& metadata, + Predicate&& predicate) { + std::vector locations; + for (const auto& stats_file : metadata.statistics) { + if (stats_file && predicate(stats_file->snapshot_id)) { + locations.push_back(stats_file->path); + } + } + for (const auto& stats_file : metadata.partition_statistics) { + if (stats_file && predicate(stats_file->snapshot_id)) { + locations.push_back(stats_file->path); + } + } + return locations; +} + +template +std::vector ManifestListLocationsIf(const TableMetadata& metadata, + Predicate&& predicate) { + std::vector locations; + for (const auto& snapshot : metadata.snapshots) { + if (snapshot && !snapshot->manifest_list.empty() && + predicate(snapshot->snapshot_id)) { + locations.push_back(snapshot->manifest_list); + } + } + return locations; +} + +Result> ReadManifests( + const Snapshot& snapshot, const std::shared_ptr& io) { + SnapshotReader snapshot_reader(&snapshot); + ICEBERG_ASSIGN_OR_RAISE(auto snapshot_manifests, snapshot_reader.Manifests(io)); + + return snapshot_manifests | std::views::as_rvalue | + std::ranges::to>(); +} + +Result> ReadManifests( + const std::vector>& snapshots, + const std::shared_ptr& io, OptionalExecutor executor) { + return ParallelCollect(executor, snapshots, + [&io](const std::shared_ptr& snapshot) { + return ReadManifests(*snapshot, io); + }); +} + +} // namespace + +std::string ReachableFileUtil::VersionHintLocation(std::string_view table_location) { + return std::format("{}/{}/{}", LocationUtil::StripTrailingSlash(table_location), + kMetadataFolderName, kVersionHintFileName); +} + +std::unordered_set ReachableFileUtil::MetadataFileLocations( + const TableMetadata& metadata, std::string_view metadata_file_location, + const std::shared_ptr& io, bool recursive) { + std::unordered_set locations; + std::unordered_set visited; + if (!metadata_file_location.empty()) { + locations.emplace(metadata_file_location); + visited.emplace(metadata_file_location); + } + + // Walk iteratively so that each previous metadata is released before the next one + // is read. + const TableMetadata* current = &metadata; + std::unique_ptr previous; + for (size_t depth = 0; current != nullptr && !current->metadata_log.empty(); ++depth) { + for (const auto& entry : current->metadata_log) { + locations.insert(entry.metadata_file); + } + if (!recursive || io == nullptr) { + break; + } + previous = + FindFirstExistentPreviousMetadata(current->metadata_log, *io, visited, depth); + current = previous.get(); + } + return locations; +} + +std::vector ReachableFileUtil::ManifestListLocations( + const TableMetadata& metadata) { + return ManifestListLocationsIf(metadata, [](int64_t) { return true; }); +} + +std::vector ReachableFileUtil::ManifestListLocations( + const TableMetadata& metadata, const std::unordered_set& snapshot_ids) { + return ManifestListLocationsIf( + metadata, [&](int64_t snapshot_id) { return snapshot_ids.contains(snapshot_id); }); +} + +std::vector ReachableFileUtil::StatisticsFilesLocations( + const TableMetadata& metadata) { + return StatisticsFilesLocationsIf(metadata, [](int64_t) { return true; }); +} + +std::vector ReachableFileUtil::StatisticsFilesLocationsForSnapshots( + const TableMetadata& metadata, const std::unordered_set& snapshot_ids) { + return StatisticsFilesLocationsIf( + metadata, [&](int64_t snapshot_id) { return snapshot_ids.contains(snapshot_id); }); +} + +Result> ReachableFileUtil::ReachableManifests( + const TableMetadata& metadata, const std::shared_ptr& io, + OptionalExecutor executor) { + auto snapshots = + metadata.snapshots | + std::views::filter([](const auto& snapshot) { return snapshot != nullptr; }) | + std::ranges::to>>(); + return ReadManifests(snapshots, io, executor); +} + +Result> ReachableFileUtil::ManifestsForSnapshots( + const TableMetadata& metadata, const std::unordered_set& snapshot_ids, + const std::shared_ptr& io, OptionalExecutor executor) { + ICEBERG_ASSIGN_OR_RAISE(auto snapshots, SnapshotsByIds(metadata, snapshot_ids)); + return ReadManifests(snapshots, io, executor); +} + +Result> ReachableFileUtil::LiveFileLocations( + const ManifestFile& manifest, const TableMetadata& metadata, + const std::shared_ptr& io) { + ICEBERG_ASSIGN_OR_RAISE(auto schema, metadata.Schema()); + TableMetadataCache metadata_cache(&metadata); + ICEBERG_ASSIGN_OR_RAISE(auto specs_by_id, metadata_cache.GetPartitionSpecsById()); + ICEBERG_ASSIGN_OR_RAISE( + auto reader, + ManifestReader::Make(manifest, io, std::move(schema), specs_by_id.get())); + reader->Select({"file_path"}); + ICEBERG_ASSIGN_OR_RAISE(auto entries, reader->LiveEntries()); + + std::unordered_set file_paths; + for (const auto& entry : entries) { + if (entry.data_file) { + file_paths.insert(entry.data_file->file_path); + } + } + return file_paths; +} + +Result> ReachableFileUtil::LiveFileLocationsForManifests( + const std::unordered_set& manifests, const TableMetadata& metadata, + const std::shared_ptr& io, OptionalExecutor executor) { + return ParallelCollect(executor, manifests, + [&metadata, &io](const ManifestFile& manifest) { + return LiveFileLocations(manifest, metadata, io); + }); +} + +} // namespace iceberg diff --git a/src/iceberg/util/reachable_file_util.h b/src/iceberg/util/reachable_file_util.h new file mode 100644 index 000000000..4513d4e82 --- /dev/null +++ b/src/iceberg/util/reachable_file_util.h @@ -0,0 +1,139 @@ +/* + * 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/util/reachable_file_util.h +/// \brief Utility functions for locating files reachable from table metadata. + +#include +#include +#include +#include +#include +#include + +#include "iceberg/iceberg_export.h" +#include "iceberg/manifest/manifest_list.h" +#include "iceberg/result.h" +#include "iceberg/type_fwd.h" +#include "iceberg/util/executor.h" + +namespace iceberg { + +/// \brief Utility functions for locating files reachable from table metadata. +/// +/// The location functions mirror Java's org.apache.iceberg.ReachableFileUtil. The +/// manifest functions have no counterpart there; they read manifest lists and +/// manifests to find the manifests and content files that snapshots reference. +class ICEBERG_EXPORT ReachableFileUtil { + public: + /// \brief File name of the version hint written by Hadoop tables. + static constexpr std::string_view kVersionHintFileName = "version-hint.text"; + + /// \brief Returns the location of the version hint file. + /// + /// Only Hadoop tables write a version hint, and they use a fixed metadata layout. + /// Trailing slashes are removed from the table location; other path normalization + /// done by Hadoop's Path is not applied. + /// + /// \param table_location The table location + /// \return The location of the version hint file + static std::string VersionHintLocation(std::string_view table_location); + + /// \brief Returns the locations of JSON metadata files of a table. + /// + /// \param metadata The table metadata + /// \param metadata_file_location The location of the metadata file; skipped if empty + /// \param io The FileIO used to read previous metadata files when recursive; when + /// null, previous metadata files are not read + /// \param recursive When true, also collects metadata files listed by previous + /// metadata files. As in Java, each step follows only the oldest readable entry of + /// the metadata log, which has the longest history; unreadable entries are skipped. + /// \return The locations of JSON metadata files + static std::unordered_set MetadataFileLocations( + const TableMetadata& metadata, std::string_view metadata_file_location, + const std::shared_ptr& io, bool recursive); + + /// \brief Returns the manifest list locations of all snapshots. + static std::vector ManifestListLocations(const TableMetadata& metadata); + + /// \brief Returns the manifest list locations of the given snapshots. + /// + /// \param metadata The table metadata + /// \param snapshot_ids IDs of the snapshots whose manifest lists are returned + static std::vector ManifestListLocations( + const TableMetadata& metadata, const std::unordered_set& snapshot_ids); + + /// \brief Returns the locations of all statistics and partition statistics files. + static std::vector StatisticsFilesLocations(const TableMetadata& metadata); + + /// \brief Returns the locations of statistics and partition statistics files for the + /// given snapshots. + /// + /// \param metadata The table metadata + /// \param snapshot_ids IDs of the snapshots whose statistics files are returned + static std::vector StatisticsFilesLocationsForSnapshots( + const TableMetadata& metadata, const std::unordered_set& snapshot_ids); + + /// \brief Returns the manifests referenced by any snapshot. + /// + /// \param metadata The table metadata + /// \param io The FileIO used to read manifest lists + /// \param executor Executor to read manifest lists with, or std::nullopt to read them + /// serially + static Result> ReachableManifests( + const TableMetadata& metadata, const std::shared_ptr& io, + OptionalExecutor executor = std::nullopt); + + /// \brief Returns the manifests referenced by the given snapshots. + /// + /// \param metadata The table metadata + /// \param snapshot_ids IDs of the snapshots to read; each must exist in metadata + /// \param io The FileIO used to read manifest lists + /// \param executor Executor to read manifest lists with, or std::nullopt to read them + /// serially + static Result> ManifestsForSnapshots( + const TableMetadata& metadata, const std::unordered_set& snapshot_ids, + const std::shared_ptr& io, OptionalExecutor executor = std::nullopt); + + /// \brief Returns the paths of data and delete files in live entries of a manifest. + /// + /// \param manifest The manifest to read + /// \param metadata Table metadata used to resolve the manifest's schema and spec + /// \param io The FileIO used to read the manifest + static Result> LiveFileLocations( + const ManifestFile& manifest, const TableMetadata& metadata, + const std::shared_ptr& io); + + /// \brief Returns the paths of data and delete files in live entries of manifests. + /// + /// Fails if any manifest cannot be read. + /// + /// \param manifests The manifests to read + /// \param metadata Table metadata used to resolve the manifests' schemas and specs + /// \param io The FileIO used to read the manifests + /// \param executor Executor to read manifests with, or std::nullopt to read them + /// serially + static Result> LiveFileLocationsForManifests( + const std::unordered_set& manifests, const TableMetadata& metadata, + const std::shared_ptr& io, OptionalExecutor executor = std::nullopt); +}; + +} // namespace iceberg