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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/iceberg/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/iceberg/cpp20_compatibility_internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
1 change: 1 addition & 0 deletions src/iceberg/test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
276 changes: 276 additions & 0 deletions src/iceberg/test/reachable_file_util_test.cc
Original file line number Diff line number Diff line change
@@ -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 <functional>
#include <memory>
#include <optional>
#include <string>
#include <unordered_set>
#include <vector>

#include <gmock/gmock.h>

#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<std::string> ManifestPaths(
const std::unordered_set<ManifestFile>& manifests) {
std::unordered_set<std::string> 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<DataFile> MakeDataFile(const std::string& path) const {
return std::make_shared<DataFile>(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<DataFile> 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<ManifestEntry>& 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<ManifestFile>& manifests) {
auto writer_result = ManifestListWriter::MakeWriter(
metadata_->format_version, snapshot_id, parent_snapshot_id, path, file_io_,
/*sequence_number=*/std::optional<int64_t>(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<TableMetadata> 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<StatisticsFile>();
stats->snapshot_id = kFirstSnapshotId;
stats->path = "s3://a/b/stats-1.puffin";
auto partition_stats = std::make_shared<PartitionStatisticsFile>();
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<TableMetadata>(*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
47 changes: 7 additions & 40 deletions src/iceberg/update/expire_snapshots.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -265,25 +266,11 @@ class ReachableFileCleanup : public FileCleanupStrategy {
}

private:
/// \brief Collect manifests for a snapshot into manifests.
Result<std::unordered_set<ManifestFile>> 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<std::unordered_set<ManifestFile>>();
}

/// \brief Collect manifests for a set of snapshots.
Result<std::unordered_set<ManifestFile>> ReadManifests(
const TableMetadata& metadata, const std::unordered_set<int64_t>& 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.
Expand All @@ -305,24 +292,6 @@ class ReachableFileCleanup : public FileCleanupStrategy {
return manifests_to_delete;
}

Result<std::unordered_set<std::string>> 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<std::string> 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<std::string> ManifestPaths(
const std::unordered_set<ManifestFile>& manifests) const {
Expand All @@ -344,7 +313,8 @@ class ReachableFileCleanup : public FileCleanupStrategy {
plan_executor_, manifests_to_delete,
[this, &metadata](
const ManifestFile& manifest) -> Result<std::unordered_set<std::string>> {
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<std::string>{};
Expand All @@ -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<std::string>{};
Expand Down
Loading