diff --git a/src/iceberg/catalog/rest/rest_catalog.cc b/src/iceberg/catalog/rest/rest_catalog.cc index a6ba928e50..28683d8e9e 100644 --- a/src/iceberg/catalog/rest/rest_catalog.cc +++ b/src/iceberg/catalog/rest/rest_catalog.cc @@ -856,6 +856,16 @@ Result RestCatalog::UpdateTableInternal( const std::vector>& updates, auth::AuthSession& session) { ICEBERG_ENDPOINT_CHECK(supported_endpoints_, Endpoint::UpdateTable()); + // The server may have roots absent from the client, including after an upgrade. + // Defer pruning until the server guarantees root validation at commit time. + if (std::ranges::any_of(updates, [](const auto& update) { + return update->kind() == TableUpdate::Kind::kRemoveSchemas || + update->kind() == TableUpdate::Kind::kRemovePartitionSpecs; + })) { + return NotSupported( + "Removing schemas or partition specs through REST requires a server " + "guarantee for root-manifest validation"); + } ICEBERG_ASSIGN_OR_RAISE(auto path, paths_->Table(identifier)); CommitTableRequest request{.identifier = identifier}; diff --git a/src/iceberg/inspect/snapshots_table.cc b/src/iceberg/inspect/snapshots_table.cc index 4d8c972fb9..bd88a7d767 100644 --- a/src/iceberg/inspect/snapshots_table.cc +++ b/src/iceberg/inspect/snapshots_table.cc @@ -56,7 +56,7 @@ class SnapshotsScan final : public MetadataScan { const std::shared_ptr task_; }; -constexpr std::array, 6> kSnapshotColumns = { +constexpr std::array, 7> kSnapshotColumns = { {{.field_id = 1, .append = [](ArrowArray* column, const Snapshot& row) { @@ -83,13 +83,19 @@ constexpr std::array, 6> kSnapshotColumn return row.manifest_list.empty() ? AppendNull(column) : AppendString(column, row.manifest_list); }}, - {.field_id = 6, .append = [](ArrowArray* column, const Snapshot& row) { - if (row.summary.empty()) { - return AppendNull(column); - } - auto summary = row.summary; - summary.erase(SnapshotSummaryFields::kOperation); - return AppendStringMap(column, summary); + {.field_id = 6, + .append = + [](ArrowArray* column, const Snapshot& row) { + if (row.summary.empty()) { + return AppendNull(column); + } + auto summary = row.summary; + summary.erase(SnapshotSummaryFields::kOperation); + return AppendStringMap(column, summary); + }}, + {.field_id = 9, .append = [](ArrowArray* column, const Snapshot& row) { + return row.root_manifest ? AppendString(column, *row.root_manifest) + : AppendNull(column); }}}}; } // namespace @@ -112,7 +118,8 @@ const std::shared_ptr& SnapshotsTable::CanonicalSchema() { SchemaField::MakeOptional( 6, "summary", std::make_shared(SchemaField::MakeRequired(7, "key", string()), - SchemaField::MakeRequired(8, "value", string())))}); + SchemaField::MakeRequired(8, "value", string()))), + SchemaField::MakeOptional(9, "root_manifest", string())}); return schema; } diff --git a/src/iceberg/json_serde.cc b/src/iceberg/json_serde.cc index 37f6c08c94..af9e8c6c5a 100644 --- a/src/iceberg/json_serde.cc +++ b/src/iceberg/json_serde.cc @@ -114,6 +114,7 @@ constexpr std::string_view kParentSnapshotId = "parent-snapshot-id"; constexpr std::string_view kSequenceNumber = "sequence-number"; constexpr std::string_view kTimestampMs = "timestamp-ms"; constexpr std::string_view kManifestList = "manifest-list"; +constexpr std::string_view kRootManifest = "root-manifest"; constexpr std::string_view kSummary = "summary"; constexpr std::string_view kFirstRowId = "first-row-id"; constexpr std::string_view kAddedRows = "added-rows"; @@ -739,7 +740,11 @@ nlohmann::json ToJson(const Snapshot& snapshot) { json[kSequenceNumber] = snapshot.sequence_number; } json[kTimestampMs] = UnixMsFromTimePointMs(snapshot.timestamp_ms); - json[kManifestList] = snapshot.manifest_list; + if (snapshot.root_manifest.has_value()) { + json[kRootManifest] = snapshot.root_manifest.value(); + } else { + json[kManifestList] = snapshot.manifest_list; + } // If there is an operation, write the summary map if (snapshot.Operation().has_value()) { json[kSummary] = snapshot.summary; @@ -1130,7 +1135,19 @@ Result> SnapshotFromJson(const nlohmann::json& json) { ICEBERG_ASSIGN_OR_RAISE(auto unix_ms, GetJsonValue(json, kTimestampMs)); auto timestamp_ms = TimePointMsFromUnixMs(unix_ms); ICEBERG_ASSIGN_OR_RAISE(auto manifest_list, - GetJsonValue(json, kManifestList)); + GetJsonValueOptional(json, kManifestList)); + ICEBERG_ASSIGN_OR_RAISE(auto root_manifest, + GetJsonValueOptional(json, kRootManifest)); + if (manifest_list.has_value() == root_manifest.has_value()) { + return JsonParseError( + "Snapshot requires exactly one of manifest-list or root-manifest"); + } + ICEBERG_ASSIGN_OR_RAISE( + auto constraint_statuses, + GetJsonValueOptional(json, "constraint-statuses")); + if (constraint_statuses.has_value() && !constraint_statuses->empty()) { + return NotSupported("Snapshot constraint statuses are not supported yet"); + } ICEBERG_ASSIGN_OR_RAISE(auto parent_snapshot_id, GetJsonValueOptional(json, kParentSnapshotId)); @@ -1148,16 +1165,8 @@ Result> SnapshotFromJson(const nlohmann::json& json) { "Invalid snapshot summary field value for '{}' (JSON value of type {})", key, value.type_name()); } - if (key == SnapshotSummaryFields::kOperation && - !kValidDataOperation.contains(value.get())) { - return JsonParseError("Invalid snapshot operation in snapshot summary"); - } summary[key] = value.get(); } - // If summary is available but operation is missing, set operation to overwrite. - if (!summary.contains(SnapshotSummaryFields::kOperation)) { - summary[SnapshotSummaryFields::kOperation] = DataOperation::kOverwrite; - } } ICEBERG_ASSIGN_OR_RAISE(auto first_row_id, @@ -1165,29 +1174,41 @@ Result> SnapshotFromJson(const nlohmann::json& json) { ICEBERG_ASSIGN_OR_RAISE(auto added_rows, GetJsonValueOptional(json, kAddedRows)); - if (first_row_id.has_value() && first_row_id.value() < 0) { - return JsonParseError("Invalid first-row-id (cannot be negative): {}", - first_row_id.value()); - } - if (added_rows.has_value() && added_rows.value() < 0) { - return JsonParseError("Invalid added-rows (cannot be negative): {}", - added_rows.value()); - } - if (first_row_id.has_value() && !added_rows.has_value()) { - return JsonParseError("Invalid added-rows (required when first-row-id is set): null"); - } - if (!first_row_id.has_value()) { - added_rows = std::nullopt; + if (!root_manifest.has_value()) { + const auto operation = summary.find(SnapshotSummaryFields::kOperation); + if (operation != summary.end() && !kValidDataOperation.contains(operation->second)) { + return JsonParseError("Invalid snapshot operation in snapshot summary"); + } + // Preserve the legacy overwrite default when summary omits operation. + if (summary_json.has_value() && operation == summary.end()) { + summary[SnapshotSummaryFields::kOperation] = DataOperation::kOverwrite; + } + if (first_row_id.has_value() && first_row_id.value() < 0) { + return JsonParseError("Invalid first-row-id (cannot be negative): {}", + first_row_id.value()); + } + if (added_rows.has_value() && added_rows.value() < 0) { + return JsonParseError("Invalid added-rows (cannot be negative): {}", + added_rows.value()); + } + if (first_row_id.has_value() && !added_rows.has_value()) { + return JsonParseError( + "Invalid added-rows (required when first-row-id is set): null"); + } + if (!first_row_id.has_value()) { + added_rows = std::nullopt; + } } ICEBERG_ASSIGN_OR_RAISE(auto schema_id, GetJsonValueOptional(json, kSchemaId)); ICEBERG_ASSIGN_OR_RAISE(auto key_id, GetJsonValueOptional(json, kKeyId)); - return std::make_unique( + auto snapshot = std::make_unique( snapshot_id, parent_snapshot_id, sequence_number.value_or(TableMetadata::kInitialSequenceNumber), timestamp_ms, - manifest_list, std::move(summary), schema_id, first_row_id, added_rows, - std::move(key_id)); + manifest_list.value_or(""), std::move(summary), schema_id, first_row_id, added_rows, + std::move(key_id), std::move(root_manifest)); + return snapshot; } nlohmann::json ToJson(const BlobMetadata& blob_metadata) { @@ -1345,10 +1366,14 @@ Result EncryptedKeyFromJson(const nlohmann::json& json) { } Result ToJson(const TableMetadata& table_metadata) { + if (auto status = table_metadata.ValidateSnapshots(); !status) { + return InvalidArgument("Cannot write snapshot: {}", status.error().message); + } nlohmann::json json; json[kFormatVersion] = table_metadata.format_version; json[kTableUuid] = table_metadata.table_uuid; + ICEBERG_RETURN_UNEXPECTED(table_metadata.ValidateLocation()); json[kLocation] = table_metadata.location; if (table_metadata.format_version > 1) { json[kLastSequenceNumber] = table_metadata.last_sequence_number; @@ -1372,6 +1397,7 @@ Result ToJson(const TableMetadata& table_metadata) { json[kCurrentSchemaId] = table_metadata.current_schema_id; // ToJson(Schema) is fallible, so the shared ToJsonList helper (which assumes an // infallible ToJson) cannot be used here; build the array with an explicit loop. + ICEBERG_RETURN_UNEXPECTED(table_metadata.ValidateIdentifierFields()); nlohmann::json schemas_json = nlohmann::json::array(); for (const auto& schema : table_metadata.schemas) { ICEBERG_ASSIGN_OR_RAISE(auto schema_json, ToJson(*schema)); @@ -1455,9 +1481,19 @@ Result> ParseSchemas( ICEBERG_ASSIGN_OR_RAISE(current_schema_id, GetJsonInteger(json, kCurrentSchemaId)); + const auto parse_schema = + [format_version]( + const nlohmann::json& schema_json) -> Result> { + if (format_version >= TableMetadata::kMinFormatVersionConstraints && + schema_json.is_object() && schema_json.contains(kIdentifierFieldIds)) { + auto schema_without_identifiers = schema_json; + schema_without_identifiers.erase(kIdentifierFieldIds); + return SchemaFromJson(schema_without_identifiers); + } + return SchemaFromJson(schema_json); + }; for (const auto& schema_json : schema_array) { - ICEBERG_ASSIGN_OR_RAISE(std::shared_ptr schema, - SchemaFromJson(schema_json)); + ICEBERG_ASSIGN_OR_RAISE(std::shared_ptr schema, parse_schema(schema_json)); ICEBERG_RETURN_UNEXPECTED(schema->Validate(format_version)); if (schema->schema_id() == current_schema_id) { current_schema = schema; @@ -1604,8 +1640,33 @@ Result> TableMetadataFromJson(const nlohmann::jso ICEBERG_ASSIGN_OR_RAISE(table_metadata->table_uuid, GetJsonValueOrDefault(json, kTableUuid)); - ICEBERG_ASSIGN_OR_RAISE(table_metadata->location, - GetJsonValue(json, kLocation)); + if (table_metadata->format_version >= TableMetadata::kMinFormatVersionConstraints) { + ICEBERG_ASSIGN_OR_RAISE( + auto constraints, + GetJsonValueOptional(json, "constraints")); + if (constraints.has_value() && !constraints->empty()) { + return NotSupported("Table constraints are not supported yet"); + } + ICEBERG_ASSIGN_OR_RAISE(auto last_constraint_id, + GetJsonIntegerOptional(json, "last-constraint-id")); + if (last_constraint_id.value_or(0) != 0) { + return NotSupported("Table constraint IDs are not supported yet"); + } + } + if (table_metadata->format_version >= + TableMetadata::kMinFormatVersionOptionalLocation) { + ICEBERG_ASSIGN_OR_RAISE(table_metadata->location, + GetJsonValueOrDefault(json, kLocation)); + } else { + ICEBERG_ASSIGN_OR_RAISE(table_metadata->location, + GetJsonValue(json, kLocation)); + } + if (auto status = table_metadata->ValidateLocation(); !status) { + if (status.error().kind == ErrorKind::kNotSupported) { + return NotSupported("{}", status.error().message); + } + return JsonParseError("{}", status.error().message); + } if (table_metadata->format_version > 1) { ICEBERG_ASSIGN_OR_RAISE(table_metadata->last_sequence_number, @@ -1684,6 +1745,9 @@ Result> TableMetadataFromJson(const nlohmann::jso ICEBERG_ASSIGN_OR_RAISE(table_metadata->snapshots, FromJsonList(json, kSnapshots, SnapshotFromJson)); + if (auto status = table_metadata->ValidateSnapshots(); !status) { + return JsonParseError("Invalid snapshot: {}", status.error().message); + } ICEBERG_ASSIGN_OR_RAISE( table_metadata->statistics, FromJsonList(json, kStatistics, StatisticsFileFromJson)); diff --git a/src/iceberg/snapshot.cc b/src/iceberg/snapshot.cc index f791c37247..475233ff28 100644 --- a/src/iceberg/snapshot.cc +++ b/src/iceberg/snapshot.cc @@ -27,6 +27,7 @@ #include "iceberg/manifest/manifest_entry.h" #include "iceberg/manifest/manifest_list.h" #include "iceberg/manifest/manifest_reader.h" +#include "iceberg/table_metadata.h" #include "iceberg/util/macros.h" #include "iceberg/util/string_util.h" @@ -165,6 +166,36 @@ Result> Snapshot::FirstRowId() const { return first_row_i Result> Snapshot::AddedRows() const { return added_rows; } +Status Snapshot::ValidateForFormatVersion(int8_t format_version, + bool is_new_snapshot) const { + if (is_new_snapshot && format_version >= TableMetadata::kMinFormatVersionRootManifest) { + ICEBERG_CHECK(root_manifest.has_value(), + "New v{} snapshots require root-manifest instead of manifest-list", + format_version); + } + if (root_manifest.has_value()) { + ICEBERG_CHECK(format_version >= TableMetadata::kMinFormatVersionRootManifest, + "root-manifest requires format version {}", + TableMetadata::kMinFormatVersionRootManifest); + ICEBERG_CHECK(manifest_list.empty(), + "root-manifest cannot coexist with manifest-list"); + ICEBERG_CHECK(!root_manifest->empty(), "Snapshot root-manifest cannot be empty"); + ICEBERG_CHECK(sequence_number > 0, "V{} snapshots require a positive sequence-number", + format_version); + ICEBERG_CHECK(first_row_id.has_value() && first_row_id.value() >= 0, + "V{} snapshots require a non-negative first-row-id", format_version); + ICEBERG_CHECK(added_rows.has_value() && added_rows.value() >= 0, + "V{} snapshots require non-negative added-rows", format_version); + const auto operation = Operation(); + ICEBERG_CHECK(operation.has_value() && (operation == DataOperation::kAppend || + operation == DataOperation::kReplace || + operation == DataOperation::kOverwrite || + operation == DataOperation::kDelete), + "V{} snapshots require a valid operation in summary", format_version); + } + return {}; +} + bool Snapshot::Equals(const Snapshot& other) const { if (this == &other) { return true; @@ -173,7 +204,8 @@ bool Snapshot::Equals(const Snapshot& other) const { parent_snapshot_id == other.parent_snapshot_id && sequence_number == other.sequence_number && timestamp_ms == other.timestamp_ms && schema_id == other.schema_id && first_row_id == other.first_row_id && - added_rows == other.added_rows && key_id == other.key_id; + added_rows == other.added_rows && key_id == other.key_id && + root_manifest == other.root_manifest; } Result> Snapshot::Make( @@ -205,6 +237,9 @@ Result> Snapshot::Make( Result SnapshotReader::InitManifestsCache( const Snapshot* snapshot, std::shared_ptr file_io) { + if (snapshot->root_manifest.has_value()) { + return NotSupported("Reading root manifests is not supported yet"); + } if (file_io == nullptr) { return InvalidArgument("Cannot cache manifests: FileIO is null"); } diff --git a/src/iceberg/snapshot.h b/src/iceberg/snapshot.h index 54c6fea2d5..583282b85b 100644 --- a/src/iceberg/snapshot.h +++ b/src/iceberg/snapshot.h @@ -417,6 +417,19 @@ struct ICEBERG_EXPORT Snapshot { /// encrypted key metadata of the manifest list. Set only for encrypted tables. std::optional key_id; + /// Location of the root manifest for a snapshot written in format version 4 + /// or later. Mutually exclusive with manifest_list. Snapshots written in + /// earlier formats retain their manifest list after a table upgrade. + std::optional root_manifest; + + /// \brief Validate snapshot metadata against a table format version. + /// New snapshots require a root manifest in format version 4 and later. + /// Existing snapshots from earlier formats may retain their manifest list. + /// \param format_version The table's current format version. + /// \param is_new_snapshot Whether the snapshot is being added to the table. + Status ValidateForFormatVersion(int8_t format_version, + bool is_new_snapshot = false) const; + /// \brief Create a new Snapshot instance with validation on the inputs. static Result> Make( int64_t sequence_number, int64_t snapshot_id, diff --git a/src/iceberg/table_metadata.cc b/src/iceberg/table_metadata.cc index 20e9ae4c95..b709aacbe0 100644 --- a/src/iceberg/table_metadata.cc +++ b/src/iceberg/table_metadata.cc @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -320,6 +321,58 @@ Result> TableMetadata::SnapshotById(int64_t snapshot_i return *iter; } +bool TableMetadata::HasRootManifest() const { + return std::ranges::any_of(snapshots, [](const auto& snapshot) { + return snapshot && snapshot->root_manifest.has_value(); + }); +} + +Status TableMetadata::ValidateLocation() const { + if (format_version >= kMinFormatVersionOptionalLocation) { + if (location.empty()) { + return NotSupported("V{} tables without a location are not supported yet", + format_version); + } + ICEBERG_PRECHECK(!LocationUtil::ParseScheme(location).empty(), + "V{} table location must be absolute: {}", format_version, location); + } + return {}; +} + +Status TableMetadata::ValidateIdentifierFields() const { + if (format_version >= kMinFormatVersionConstraints && + std::ranges::any_of(schemas, [](const auto& schema) { + return !schema->IdentifierFieldIds().empty(); + })) { + return NotSupported( + "Primary-key constraints are not supported yet; " + "identifier-field-ids cannot be written in format version {}", + format_version); + } + return {}; +} + +Status TableMetadata::ValidateSnapshots() const { + for (const auto& snapshot : snapshots) { + ICEBERG_CHECK(snapshot != nullptr, "Cannot write null snapshot"); + ICEBERG_RETURN_UNEXPECTED(snapshot->ValidateForFormatVersion(format_version)); + if (snapshot->root_manifest.has_value()) { + ICEBERG_CHECK( + last_sequence_number >= snapshot->sequence_number, + "last-sequence-number {} is below retained snapshot {} sequence-number {}", + last_sequence_number, snapshot->snapshot_id, snapshot->sequence_number); + const auto first_row_id = snapshot->first_row_id.value(); + const auto added_rows = snapshot->added_rows.value(); + ICEBERG_CHECK( + first_row_id <= next_row_id && added_rows <= next_row_id - first_row_id, + "next-row-id {} does not cover retained snapshot {} row IDs " + "(first-row-id {}, added-rows {})", + next_row_id, snapshot->snapshot_id, first_row_id, added_rows); + } + } + return {}; +} + int64_t TableMetadata::NextSequenceNumber() const { return format_version > 1 ? last_sequence_number + 1 : kInitialSequenceNumber; } @@ -790,6 +843,19 @@ Status TableMetadataBuilder::Impl::UpgradeFormatVersion(int8_t new_format_versio return {}; } + // A create transaction may upgrade before selecting the current schema. + // Build() checks identifier-field compatibility across all schemas. + if (new_format_version >= TableMetadata::kMinFormatVersionConstraints) { + auto current_schema = schemas_by_id_.find(metadata_.current_schema_id); + if (current_schema != schemas_by_id_.end() && + !current_schema->second->IdentifierFieldIds().empty()) { + return NotSupported( + "Cannot upgrade a table with identifier fields to format version {}: " + "primary-key constraint migration is not supported yet", + new_format_version); + } + } + // Update the format version metadata_.format_version = new_format_version; @@ -1114,14 +1180,35 @@ Status TableMetadataBuilder::Impl::AddSnapshot(std::shared_ptr snapsho "Attempting to add a snapshot before a sort order is added"); ICEBERG_CHECK(!snapshots_by_id_.contains(snapshot->snapshot_id), "Snapshot already exists for id: {}", snapshot->snapshot_id); + ICEBERG_RETURN_UNEXPECTED( + snapshot->ValidateForFormatVersion(metadata_.format_version, true)); if (metadata_.format_version != 1 && snapshot->sequence_number <= metadata_.last_sequence_number && - snapshot->parent_snapshot_id.has_value()) { + (snapshot->parent_snapshot_id.has_value() || snapshot->root_manifest.has_value())) { return RetryableValidationFailed( "Cannot add snapshot with sequence number {} older than last sequence number {}", snapshot->sequence_number, metadata_.last_sequence_number); } - + if (metadata_.format_version >= TableMetadata::kMinFormatVersionMonotonicTimestamps && + snapshot->parent_snapshot_id.has_value()) { + auto parent = snapshots_by_id_.find(snapshot->parent_snapshot_id.value()); + if (parent != snapshots_by_id_.end() && + snapshot->timestamp_ms <= parent->second->timestamp_ms) { + return ValidationFailed( + "V{} snapshot timestamp must be greater than its parent timestamp", + metadata_.format_version); + } + } + if (snapshot->root_manifest.has_value()) { + if (snapshot->first_row_id.value() != metadata_.next_row_id) { + return RetryableValidationFailed( + "Cannot add snapshot, first-row-id must match table next-row-id: {} != {}", + snapshot->first_row_id.value(), metadata_.next_row_id); + } + ICEBERG_CHECK(snapshot->added_rows.value() <= + std::numeric_limits::max() - metadata_.next_row_id, + "Cannot add snapshot: row ID range overflows int64"); + } metadata_.last_sequence_number = snapshot->sequence_number; metadata_.snapshots.push_back(snapshot); snapshots_by_id_.emplace(snapshot->snapshot_id, snapshot); @@ -1397,7 +1484,19 @@ Result> TableMetadataBuilder::Impl::UpdateSnapshot } Result> TableMetadataBuilder::Impl::Build() { - // 1. Validate metadata consistency through TableMetadata#Validate + // 1. Validate the location and retained snapshots. + ICEBERG_RETURN_UNEXPECTED(metadata_.ValidateLocation()); + // Catalog replay may use a newer base whose roots were absent during planning. + if (metadata_.HasRootManifest() && + std::ranges::any_of(changes_, [](const auto& change) { + return change->kind() == TableUpdate::Kind::kRemoveSchemas || + change->kind() == TableUpdate::Kind::kRemovePartitionSpecs; + })) { + return NotSupported( + "Removing schemas or partition specs with root manifests is not supported yet"); + } + + ICEBERG_RETURN_UNEXPECTED(metadata_.ValidateSnapshots()); // 2. Update last_updated_ms if there are changes if (metadata_.last_updated_ms == kInvalidLastUpdatedMs) { @@ -1410,6 +1509,7 @@ Result> TableMetadataBuilder::Impl::Build() { auto schema_it = schemas_by_id_.find(current_schema_id); ICEBERG_PRECHECK(schema_it != schemas_by_id_.end(), "Current schema ID {} not found in schemas", current_schema_id); + ICEBERG_RETURN_UNEXPECTED(metadata_.ValidateIdentifierFields()); { const auto& current_schema = schema_it->second; diff --git a/src/iceberg/table_metadata.h b/src/iceberg/table_metadata.h index 2779d413f9..2260f4dc01 100644 --- a/src/iceberg/table_metadata.h +++ b/src/iceberg/table_metadata.h @@ -64,15 +64,14 @@ struct ICEBERG_EXPORT MetadataLogEntry { /// \brief Represents the metadata for an Iceberg table /// -/// Note that it only contains table metadata from the spec. Compared to the Java -/// implementation, missing pieces including: -/// (1) Map -/// (2) List -/// (3) Map -/// (4) Map +/// Builders maintain lookup indexes and track metadata updates separately. struct ICEBERG_EXPORT TableMetadata { static constexpr int8_t kDefaultTableFormatVersion = 2; - static constexpr int8_t kSupportedTableFormatVersion = 3; + static constexpr int8_t kSupportedTableFormatVersion = 4; + static constexpr int8_t kMinFormatVersionOptionalLocation = 4; + static constexpr int8_t kMinFormatVersionRootManifest = 4; + static constexpr int8_t kMinFormatVersionMonotonicTimestamps = 4; + static constexpr int8_t kMinFormatVersionConstraints = 4; static constexpr int8_t kMinFormatVersionRowLineage = 3; static constexpr int8_t kMinFormatVersionDefaultValues = 3; static constexpr int64_t kInitialSequenceNumber = 0; @@ -87,7 +86,8 @@ struct ICEBERG_EXPORT TableMetadata { int8_t format_version; /// A UUID that identifies the table std::string table_uuid; - /// The table's base location + /// The table's base location. An absolute URI is required in format version 4 + /// and later. std::string location; /// The table's highest assigned sequence number int64_t last_sequence_number; @@ -169,6 +169,23 @@ struct ICEBERG_EXPORT TableMetadata { /// \brief Get the next sequence number int64_t NextSequenceNumber() const; + /// \brief Validate retained snapshots for this format and root allocation bounds. + Status ValidateSnapshots() const; + + /// \brief Whether any snapshot references a root manifest. + bool HasRootManifest() const; + + /// \brief Validate the table location for this format version. + /// In format version 4 and later, the location must be an absolute URI. + /// Omitted locations are not supported yet. + Status ValidateLocation() const; + + /// \brief Validate identifier-field support across all schemas. + /// Returns NotSupported for format version 4 and later if any schema has + /// identifier fields, as primary-key constraint migration is not supported yet. + /// Earlier format versions pass this check. + Status ValidateIdentifierFields() const; + ICEBERG_EXPORT friend bool operator==(const TableMetadata& lhs, const TableMetadata& rhs); diff --git a/src/iceberg/test/expire_snapshots_test.cc b/src/iceberg/test/expire_snapshots_test.cc index 9695b4a850..5d2f4e74a4 100644 --- a/src/iceberg/test/expire_snapshots_test.cc +++ b/src/iceberg/test/expire_snapshots_test.cc @@ -19,6 +19,7 @@ #include "iceberg/update/expire_snapshots.h" +#include #include #include #include @@ -30,6 +31,7 @@ #include #include "iceberg/avro/avro_register.h" +#include "iceberg/logging/logger.h" #include "iceberg/manifest/manifest_entry.h" #include "iceberg/manifest/manifest_writer.h" #include "iceberg/partition_spec.h" @@ -38,7 +40,10 @@ #include "iceberg/statistics_file.h" #include "iceberg/table_metadata.h" #include "iceberg/table_properties.h" +#include "iceberg/table_requirements.h" +#include "iceberg/table_update.h" #include "iceberg/test/executor.h" +#include "iceberg/test/logging_test_helpers.h" #include "iceberg/test/matchers.h" #include "iceberg/test/mock_catalog.h" #include "iceberg/test/update_test_base.h" @@ -224,6 +229,252 @@ class ExpireSnapshotsCleanupTest : public UpdateTestBase { } }; +class ExpireSnapshotsV4Test : public ExpireSnapshotsCleanupTest { + protected: + void SetUp() override { + ExpireSnapshotsCleanupTest::SetUp(); + auto metadata = ReloadMetadata(); + // Prepare schemas without primary keys and an absolute table URI. Keep + // legacy snapshots until each test explicitly introduces a root manifest. + for (auto& schema : metadata->schemas) { + if (!schema->IdentifierFieldIds().empty()) { + schema = std::make_shared( + std::vector(schema->fields().begin(), schema->fields().end()), + schema->schema_id()); + } + } + metadata->location = "file:" + table_location_; + metadata->properties.Set(TableProperties::kWriteMetadataLocation, + table_location_ + "/metadata"); + metadata->snapshots.back()->first_row_id = 0; + metadata->snapshots.back()->added_rows = 0; + RewriteTable(std::move(metadata)); + } +}; + +class ExpireSnapshotsV4CleanupTest : public ExpireSnapshotsV4Test, + public ::testing::WithParamInterface { +}; + +TEST_P(ExpireSnapshotsV4CleanupTest, RejectsCleanupBeforeCommit) { + const auto data_path = table_location_ + "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/data/shared.parquet"; + const auto manifest_path = table_location_ + "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/metadata/shared-manifest.avro"; + const auto expired_list = table_location_ + "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/metadata/expired-list.avro"; + ASSERT_THAT(file_io_->WriteFile(data_path, "data"), IsOk()); + auto manifest = + WriteDataManifest(manifest_path, kExpiredSnapshotId, + {MakeEntry(ManifestStatus::kAdded, kExpiredSnapshotId, + kExpiredSequenceNumber, MakeDataFile(data_path))}); + WriteManifestList(expired_list, kExpiredSnapshotId, 0, kExpiredSequenceNumber, + {manifest}); + + auto metadata = ReloadMetadata(); + metadata->snapshots.front()->manifest_list = expired_list; + metadata->format_version = 4; + metadata->snapshots.back()->manifest_list.clear(); + metadata->snapshots.back()->root_manifest = "metadata/current-root.avro"; + RewriteTable(std::move(metadata)); + const auto metadata_location = std::string(table_->metadata_file_location()); + + // The opaque root manifest may still reference the legacy manifest. Exercise both + // incremental (by age) and reachable (by explicit ID) cleanup selection. + for (bool explicit_id : {false, true}) { + SCOPED_TRACE(explicit_id); + std::vector deleted_files; + ICEBERG_UNWRAP_OR_FAIL(auto update, table_->NewExpireSnapshots()); + if (explicit_id) { + update->ExpireSnapshotId(kExpiredSnapshotId); + } else { + update->ExpireOlderThan( + UnixMsFromTimePointMs(table_->metadata()->snapshots.back()->timestamp_ms)); + } + update->CleanupLevel(GetParam()).DeleteWith([&](const std::string& path) { + deleted_files.push_back(path); + }); + EXPECT_THAT(update->Apply(), IsError(ErrorKind::kNotSupported)); + EXPECT_THAT(update->Commit(), IsError(ErrorKind::kNotSupported)); + EXPECT_TRUE(deleted_files.empty()); + EXPECT_TRUE(ReloadMetadata()->SnapshotById(kExpiredSnapshotId).has_value()); + EXPECT_EQ(table_->metadata_file_location(), metadata_location); + for (const auto& path : {data_path, manifest_path, expired_list}) { + EXPECT_THAT(file_io_->ReadFile(path, std::nullopt), IsOk()); + } + } +} + +INSTANTIATE_TEST_SUITE_P(FileCleanupLevels, ExpireSnapshotsV4CleanupTest, + ::testing::Values(CleanupLevel::kAll, + CleanupLevel::kMetadataOnly)); + +TEST_F(ExpireSnapshotsV4Test, V4SupportsNoOpAndExpirationWithoutFileCleanup) { + const auto expired_list = table_location_ + "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/metadata/expired-list.avro"; + WriteManifestList(expired_list, kExpiredSnapshotId, 0, kExpiredSequenceNumber, {}); + auto metadata = ReloadMetadata(); + metadata->snapshots.front()->manifest_list = expired_list; + metadata->format_version = 4; + metadata->snapshots.back()->manifest_list.clear(); + metadata->snapshots.back()->root_manifest = "metadata/current-root.avro"; + RewriteTable(std::move(metadata)); + + ICEBERG_UNWRAP_OR_FAIL(auto noop, table_->NewExpireSnapshots()); + noop->RetainLast(2); + EXPECT_THAT(noop->Commit(), IsOk()); + + std::vector deleted_files; + ICEBERG_UNWRAP_OR_FAIL(auto update, table_->NewExpireSnapshots()); + update->ExpireSnapshotId(kExpiredSnapshotId) + .CleanupLevel(CleanupLevel::kNone) + .DeleteWith([&](const std::string& path) { deleted_files.push_back(path); }); + ASSERT_THAT(update->Commit(), IsOk()); + EXPECT_TRUE(deleted_files.empty()); + metadata = ReloadMetadata(); + EXPECT_FALSE(metadata->SnapshotById(kExpiredSnapshotId).has_value()); + EXPECT_TRUE(metadata->SnapshotById(kCurrentSnapshotId).has_value()); + EXPECT_THAT(file_io_->ReadFile(expired_list, std::nullopt), IsOk()); +} + +TEST_F(ExpireSnapshotsV4Test, V4RejectsSchemaSpecPruningBeforeCommit) { + auto metadata = ReloadMetadata(); + metadata->format_version = 4; + metadata->snapshots.back()->manifest_list.clear(); + metadata->snapshots.back()->root_manifest = "metadata/current-root.avro"; + RewriteTable(std::move(metadata)); + const auto location = std::string(table_->metadata_file_location()); + for (bool expire_snapshot : {false, true}) { + SCOPED_TRACE(expire_snapshot); + std::vector deleted_files; + ICEBERG_UNWRAP_OR_FAIL(auto update, table_->NewExpireSnapshots()); + update->CleanupLevel(CleanupLevel::kNone) + .CleanExpiredMetadata(true) + .DeleteWith([&](const std::string& path) { deleted_files.push_back(path); }); + if (expire_snapshot) { + update->ExpireSnapshotId(kExpiredSnapshotId); + } else { + update->RetainLast(2); + } + auto result = update->Apply(); + EXPECT_THAT(result, IsError(ErrorKind::kNotSupported)); + EXPECT_THAT(result, HasErrorMessage("disable CleanExpiredMetadata")); + EXPECT_THAT(update->Commit(), IsError(ErrorKind::kNotSupported)); + EXPECT_TRUE(deleted_files.empty()); + EXPECT_EQ(table_->metadata_file_location(), location); + EXPECT_TRUE(ReloadMetadata()->SnapshotById(kExpiredSnapshotId).has_value()); + } +} + +TEST_F(ExpireSnapshotsV4Test, ConcurrentRootPreventsStaleSchemaSpecPruning) { + const auto current_list = table_location_ + "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/metadata/current-list.avro"; + WriteManifestList(current_list, kCurrentSnapshotId, kExpiredSnapshotId, + kCurrentSequenceNumber, {}); + auto metadata = ReloadMetadata(); + metadata->format_version = 4; + metadata->snapshots.back()->manifest_list = current_list; + ICEBERG_UNWRAP_OR_FAIL(auto old_spec, PartitionSpec::Make(1, {})); + metadata->partition_specs.push_back(std::move(old_spec)); + RewriteTable(std::move(metadata)); + + ICEBERG_UNWRAP_OR_FAIL(auto txn, table_->NewTransaction()); + ICEBERG_UNWRAP_OR_FAIL(auto expiration, txn->NewExpireSnapshots()); + expiration->ExpireSnapshotId(kExpiredSnapshotId) + .CleanupLevel(CleanupLevel::kNone) + .CleanExpiredMetadata(true); + ICEBERG_UNWRAP_OR_FAIL(auto plan, expiration->Apply()); + EXPECT_THAT(plan.partition_spec_ids_to_remove, ::testing::Contains(1)); + EXPECT_THAT(plan.schema_ids_to_remove, ::testing::Contains(0)); + ASSERT_THAT(expiration->Commit(), IsOk()); + + ICEBERG_UNWRAP_OR_FAIL(auto writer_table, catalog_->LoadTable(table_ident_)); + auto snapshot = std::make_shared( + Snapshot{.snapshot_id = kCurrentSnapshotId + 1, + .parent_snapshot_id = kCurrentSnapshotId, + .sequence_number = writer_table->metadata()->NextSequenceNumber(), + .timestamp_ms = writer_table->metadata()->snapshots.back()->timestamp_ms + + std::chrono::milliseconds(1), + .summary = {{"operation", "append"}}, + .schema_id = 0, + .first_row_id = writer_table->metadata()->next_row_id, + .added_rows = 0, + .root_manifest = "metadata/concurrent-root.parquet"}); + auto writer = TableMetadataBuilder::BuildFrom(writer_table->metadata().get()); + writer->AddSnapshot(snapshot).SetBranchSnapshot(snapshot->snapshot_id, "main"); + ASSERT_THAT(writer->Build(), IsOk()); + ICEBERG_UNWRAP_OR_FAIL( + auto requirements, + TableRequirements::ForUpdateTable(*writer_table->metadata(), writer->changes())); + ICEBERG_UNWRAP_OR_FAIL(auto committed, catalog_->UpdateTable(table_ident_, requirements, + writer->changes())); + const auto location = std::string(committed->metadata_file_location()); + EXPECT_THAT(txn->Commit(), IsError(ErrorKind::kNotSupported)); + ICEBERG_UNWRAP_OR_FAIL(auto retained, catalog_->LoadTable(table_ident_)); + EXPECT_EQ(retained->metadata_file_location(), location); + EXPECT_THAT(retained->metadata()->PartitionSpecById(1), IsOk()); + EXPECT_THAT(retained->metadata()->SchemaById(0), IsOk()); + EXPECT_THAT(retained->metadata()->SnapshotById(kExpiredSnapshotId), IsOk()); + EXPECT_TRUE(retained->metadata()->HasRootManifest()); +} + +TEST_P(ExpireSnapshotsV4CleanupTest, SkipsCleanupWhenCommittedMetadataAddsV4Root) { + const auto data_path = table_location_ + "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/data/expired.parquet"; + const auto manifest_path = table_location_ + "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/metadata/expired-manifest.avro"; + const auto expired_list = table_location_ + "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/metadata/expired-list.avro"; + const auto current_list = table_location_ + "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/metadata/current-list.avro"; + ASSERT_THAT(file_io_->WriteFile(data_path, "data"), IsOk()); + auto manifest = + WriteDataManifest(manifest_path, kExpiredSnapshotId, + {MakeEntry(ManifestStatus::kAdded, kExpiredSnapshotId, + kExpiredSequenceNumber, MakeDataFile(data_path))}); + WriteManifestList(expired_list, kExpiredSnapshotId, 0, kExpiredSequenceNumber, + {manifest}); + WriteManifestList(current_list, kCurrentSnapshotId, kExpiredSnapshotId, + kCurrentSequenceNumber, {}); + RewriteTableWithManifestLists(expired_list, current_list); + + auto mock = std::make_shared<::testing::NiceMock>(); + EXPECT_CALL(*mock, UpdateTable(::testing::_, ::testing::_, ::testing::_)) + .WillOnce([this](const auto& name, const auto& requirements, + const auto& updates) -> Result> { + ICEBERG_ASSIGN_OR_RAISE(auto committed, + catalog_->UpdateTable(name, requirements, updates)); + auto& metadata = *committed->metadata(); + metadata.format_version = 4; + metadata.snapshots.back()->manifest_list.clear(); + metadata.snapshots.back()->root_manifest = "metadata/current-root.avro"; + ICEBERG_RETURN_UNEXPECTED(TableMetadataUtil::Write( + *file_io_, std::string(committed->metadata_file_location()), + *committed->metadata())); + return committed; + }); + ICEBERG_UNWRAP_OR_FAIL( + auto table, + Table::Make(table_->name(), table_->metadata(), + std::string(table_->metadata_file_location()), file_io_, mock)); + std::vector deleted_files; + ICEBERG_UNWRAP_OR_FAIL(auto update, table->NewExpireSnapshots()); + update->ExpireSnapshotId(kExpiredSnapshotId) + .CleanupLevel(GetParam()) + .DeleteWith([&](const std::string& path) { deleted_files.push_back(path); }); + auto logger = std::make_shared(); + ScopedLogger scoped_logger(logger); + ASSERT_THAT(update->Commit(), IsOk()); + EXPECT_TRUE(deleted_files.empty()); + auto committed = ReloadMetadata(); + EXPECT_FALSE(committed->SnapshotById(kExpiredSnapshotId).has_value()); + EXPECT_TRUE(committed->snapshots.back()->root_manifest.has_value()); + for (const auto& path : {expired_list, manifest_path, data_path}) { + EXPECT_THAT(file_io_->ReadFile(path, std::nullopt), IsOk()); + } + EXPECT_THAT(logger->records(), + ::testing::Contains(::testing::AllOf( + ::testing::Field(&LogMessage::level, LogLevel::kWarn), + ::testing::Field( + &LogMessage::message, + ::testing::HasSubstr("expired snapshot files were retained"))))); + for (const auto& record : logger->records()) { + EXPECT_THAT(record.message, + ::testing::Not(::testing::HasSubstr("Update finalization failed"))); + } +} + TEST_F(ExpireSnapshotsTest, DefaultExpireByAge) { ICEBERG_UNWRAP_OR_FAIL(auto update, table_->NewExpireSnapshots()); ICEBERG_UNWRAP_OR_FAIL(auto result, update->Apply()); diff --git a/src/iceberg/test/in_memory_catalog_test.cc b/src/iceberg/test/in_memory_catalog_test.cc index 06410bceca..b146bb9095 100644 --- a/src/iceberg/test/in_memory_catalog_test.cc +++ b/src/iceberg/test/in_memory_catalog_test.cc @@ -25,6 +25,8 @@ #include #include +#include +#include #include #include @@ -42,6 +44,7 @@ #include "iceberg/test/mock_io.h" #include "iceberg/test/test_resource.h" #include "iceberg/transaction.h" +#include "iceberg/update/fast_append.h" #include "iceberg/update/update_properties.h" #include "iceberg/util/uuid.h" @@ -150,7 +153,9 @@ TEST_P(InMemoryCatalogFormatVersionTest, CreateTable) { std::vector{SchemaField::MakeRequired(1, "x", int64())}); const auto [staged, version] = GetParam(); TableIdentifier ident{.ns = {}, .name = "versioned_table"}; - const auto location = GenerateTestTableLocation(ident.name); + auto location = + ::arrow::util::UriFromAbsolutePath(GenerateTestTableLocation(ident.name)); + ASSERT_TRUE(location.ok()) << location.status().ToString(); const std::unordered_map properties = { {"format-version", std::to_string(version)}, {"owner", "alice"}}; std::shared_ptr created; @@ -158,14 +163,14 @@ TEST_P(InMemoryCatalogFormatVersionTest, CreateTable) { ICEBERG_UNWRAP_OR_FAIL( auto transaction, catalog_->StageCreateTable(ident, schema, PartitionSpec::Unpartitioned(), - SortOrder::Unsorted(), location, properties)); + SortOrder::Unsorted(), *location, properties)); EXPECT_EQ(transaction->current().format_version, version); EXPECT_THAT(catalog_->TableExists(ident), HasValue(::testing::Eq(false))); ICEBERG_UNWRAP_OR_FAIL(created, transaction->Commit()); } else { ICEBERG_UNWRAP_OR_FAIL( created, catalog_->CreateTable(ident, schema, PartitionSpec::Unpartitioned(), - SortOrder::Unsorted(), location, properties)); + SortOrder::Unsorted(), *location, properties)); } EXPECT_EQ(created->metadata()->format_version, version); ICEBERG_UNWRAP_OR_FAIL(auto loaded, catalog_->LoadTable(ident)); @@ -176,7 +181,7 @@ TEST_P(InMemoryCatalogFormatVersionTest, CreateTable) { INSTANTIATE_TEST_SUITE_P(SupportedVersions, InMemoryCatalogFormatVersionTest, ::testing::Combine(::testing::Bool(), - ::testing::Values(1, 2, 3)), + ::testing::Values(1, 2, 3, 4)), [](const ::testing::TestParamInfo>& info) { return std::string(std::get<0>(info.param) ? "StagedV" : "CreateV") + @@ -215,6 +220,29 @@ INSTANTIATE_TEST_SUITE_P(StagedUpgrades, InMemoryCatalogStagedFormatUpgradeTest, return "V" + std::to_string(info.param) + "ToV3"; }); +TEST_F(InMemoryCatalogTest, UpgradeFormatVersionToV4) { + auto schema = std::make_shared( + std::vector{SchemaField::MakeRequired(1, "id", int64())}); + for (const auto* initial_version : {"2", "4"}) { + TableIdentifier ident{.name = std::string("version_") + initial_version}; + auto location = + ::arrow::util::UriFromAbsolutePath(GenerateTestTableLocation(ident.name)); + ASSERT_TRUE(location.ok()) << location.status().ToString(); + ICEBERG_UNWRAP_OR_FAIL( + auto table, catalog_->CreateTable(ident, schema, PartitionSpec::Unpartitioned(), + SortOrder::Unsorted(), *location, + {{"format-version", initial_version}})); + ICEBERG_UNWRAP_OR_FAIL(auto update, table->NewUpdateProperties()); + update->Set("format-version", "4"); + ASSERT_THAT(update->Commit(), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto loaded, catalog_->LoadTable(ident)); + EXPECT_EQ(loaded->metadata()->format_version, 4); + EXPECT_FALSE(loaded->metadata()->properties.configs().contains("format-version")); + ICEBERG_UNWRAP_OR_FAIL(auto append, loaded->NewFastAppend()); + EXPECT_THAT(append->Commit(), IsError(ErrorKind::kNotSupported)); + } +} + class InMemoryCatalogInvalidFormatVersionTest : public InMemoryCatalogTest, public ::testing::WithParamInterface> {}; @@ -244,7 +272,7 @@ INSTANTIATE_TEST_SUITE_P( InvalidVersions, InMemoryCatalogInvalidFormatVersionTest, ::testing::Combine(::testing::Bool(), ::testing::Values("", "abc", "2x", "1.5", "2147483648", "0", "-1", - "4", "257")), + "5", "257")), [](const ::testing::TestParamInfo>& info) { return std::string(std::get<0>(info.param) ? "StagedCase" : "CreateCase") + std::to_string(info.index); diff --git a/src/iceberg/test/inspect/snapshots_table_test.cc b/src/iceberg/test/inspect/snapshots_table_test.cc index 773ab167f1..41ae4b301a 100644 --- a/src/iceberg/test/inspect/snapshots_table_test.cc +++ b/src/iceberg/test/inspect/snapshots_table_test.cc @@ -87,7 +87,7 @@ TEST_F(SnapshotsTableTest, Scan) { // Row and column counts. EXPECT_EQ(batch->num_rows(), 2); - EXPECT_EQ(batch->num_columns(), 6); + EXPECT_EQ(batch->num_columns(), 7); // Column 0: committed_at (timestamptz) — microseconds since epoch. auto committed_at = std::static_pointer_cast<::arrow::TimestampArray>(batch->column(0)); @@ -133,6 +133,56 @@ TEST_F(SnapshotsTableTest, Scan) { second_summary, ::testing::Not(::testing::Contains(::testing::Pair("operation", "append")))); EXPECT_THAT(second_summary, ::testing::Contains(::testing::Pair("total-records", "2"))); + + // Legacy snapshots have no root manifest. + EXPECT_EQ(batch->column(6)->null_count(), 2); +} + +TEST_F(SnapshotsTableTest, ExposesRootManifestAndNullLegacyManifestList) { + auto& metadata = *table_->metadata(); + metadata.format_version = 4; + auto& snapshot = *metadata.snapshots.back(); + snapshot.manifest_list.clear(); + snapshot.root_manifest = "s3://bucket/metadata/root.avro"; + snapshot.first_row_id = 0; + snapshot.added_rows = 0; + + ICEBERG_UNWRAP_OR_FAIL(auto stream, Scan(*snapshots_table_)); + ICEBERG_UNWRAP_OR_FAIL(auto batches, ReadAllBatches(std::move(stream))); + ASSERT_EQ(batches.size(), 1); + const auto& batch = batches.front(); + auto lists = std::static_pointer_cast<::arrow::StringArray>( + batch->GetColumnByName("manifest_list")); + auto roots = std::static_pointer_cast<::arrow::StringArray>( + batch->GetColumnByName("root_manifest")); + ASSERT_NE(lists, nullptr); + ASSERT_NE(roots, nullptr); + EXPECT_EQ(lists->GetString(0), "file:/tmp/manifest1.avro"); + EXPECT_TRUE(lists->IsNull(1)); + EXPECT_TRUE(roots->IsNull(0)); + EXPECT_EQ(roots->GetString(1), snapshot.root_manifest.value()); + + auto projection = std::make_shared( + std::vector{SchemaField::MakeOptional(9, "root_manifest", string()), + SchemaField::MakeOptional(5, "manifest_list", string())}); + ICEBERG_UNWRAP_OR_FAIL(auto builder, snapshots_table_->NewScan()); + ICEBERG_UNWRAP_OR_FAIL(auto projected_stream, + BuildStream(builder->Project(projection))); + ICEBERG_UNWRAP_OR_FAIL(auto projected_batches, + ReadAllBatches(std::move(projected_stream))); + ASSERT_EQ(projected_batches.size(), 1); + const auto& projected = projected_batches.front(); + ASSERT_EQ(projected->num_columns(), 2); + EXPECT_EQ(projected->column_name(0), "root_manifest"); + EXPECT_EQ(projected->column_name(1), "manifest_list"); + auto projected_roots = + std::static_pointer_cast<::arrow::StringArray>(projected->column(0)); + auto projected_lists = + std::static_pointer_cast<::arrow::StringArray>(projected->column(1)); + EXPECT_TRUE(projected_roots->IsNull(0)); + EXPECT_EQ(projected_roots->GetString(1), snapshot.root_manifest.value()); + EXPECT_EQ(projected_lists->GetString(0), "file:/tmp/manifest1.avro"); + EXPECT_TRUE(projected_lists->IsNull(1)); } TEST_F(SnapshotsTableTest, ScanSelectedColumns) { @@ -189,7 +239,7 @@ TEST_F(SnapshotsTableTest, ScanAllColumnsSelection) { ICEBERG_UNWRAP_OR_FAIL(auto batches, ReadAllBatches(std::move(stream))); ASSERT_EQ(batches.size(), 1); EXPECT_EQ(batches.front()->num_rows(), 2); - EXPECT_EQ(batches.front()->num_columns(), 6); + EXPECT_EQ(batches.front()->num_columns(), 7); } TEST_F(SnapshotsTableTest, ScanBuildsRepeatedly) { @@ -417,7 +467,8 @@ TEST_F(SnapshotsTableTest, CanonicalSchema) { SchemaField::MakeOptional( 6, "summary", std::make_shared(SchemaField::MakeRequired(7, "key", string()), - SchemaField::MakeRequired(8, "value", string())))}); + SchemaField::MakeRequired(8, "value", string()))), + SchemaField::MakeOptional(9, "root_manifest", string())}); EXPECT_EQ(*SnapshotsTable::CanonicalSchema(), *expected); EXPECT_EQ(*snapshots_table_->schema(), *expected); } diff --git a/src/iceberg/test/json_serde_test.cc b/src/iceberg/test/json_serde_test.cc index 13b28a7bbe..c5618dbaf5 100644 --- a/src/iceberg/test/json_serde_test.cc +++ b/src/iceberg/test/json_serde_test.cc @@ -118,6 +118,19 @@ void TestSchemaFieldJsonConversion(const SchemaField& field, EXPECT_EQ(field, *obj_ex.value()) << "Deserialized object mismatch."; } +nlohmann::json RootManifestSnapshotJson() { + return nlohmann::json::parse(R"({ + "snapshot-id": 1, + "sequence-number": 1, + "timestamp-ms": 1000, + "root-manifest": "metadata/root.avro", + "summary": {"operation": "append"}, + "schema-id": 0, + "first-row-id": 0, + "added-rows": 10 + })"); +} + } // namespace // Pins the wire format produced by ToJson(SchemaField) / FieldFromJson for @@ -541,6 +554,40 @@ TEST(JsonInternalTest, Snapshot) { TestJsonConversion(snapshot, expected_json); } +TEST(JsonInternalTest, SnapshotRootManifestRoundTrip) { + auto json = RootManifestSnapshotJson(); + ICEBERG_UNWRAP_OR_FAIL(auto snapshot, SnapshotFromJson(json)); + EXPECT_EQ(snapshot->root_manifest, "metadata/root.avro"); + EXPECT_TRUE(snapshot->manifest_list.empty()); + TestJsonConversion(*snapshot, json); + json["manifest-list"] = "legacy.avro"; + EXPECT_THAT(SnapshotFromJson(json), HasErrorMessage("exactly one")); +} + +TEST(JsonInternalTest, SnapshotConstraintStatusesRequireAnObject) { + auto omitted = RootManifestSnapshotJson(); + EXPECT_THAT(SnapshotFromJson(omitted), IsOk()); + for (const auto& value : + std::vector{nullptr, nlohmann::json::object()}) { + auto json = RootManifestSnapshotJson(); + json["constraint-statuses"] = value; + EXPECT_THAT(SnapshotFromJson(json), IsOk()); + } + for (const auto& value : + std::vector{true, 0, 0.0, "statuses", nlohmann::json::array(), + nlohmann::json::array({1})}) { + SCOPED_TRACE(value.dump()); + auto json = RootManifestSnapshotJson(); + json["constraint-statuses"] = value; + auto result = SnapshotFromJson(json); + EXPECT_THAT(result, IsError(ErrorKind::kJsonParseError)); + EXPECT_THAT(result, HasErrorMessage("constraint-statuses")); + } + auto json = RootManifestSnapshotJson(); + json["constraint-statuses"] = {{"validated", {1}}}; + EXPECT_THAT(SnapshotFromJson(json), IsError(ErrorKind::kNotSupported)); +} + TEST(JsonInternalTest, SnapshotRowLineageSerializesTopLevelFields) { ICEBERG_UNWRAP_OR_FAIL( auto snapshot, diff --git a/src/iceberg/test/metadata_serde_test.cc b/src/iceberg/test/metadata_serde_test.cc index 41530db653..f0ee0e4113 100644 --- a/src/iceberg/test/metadata_serde_test.cc +++ b/src/iceberg/test/metadata_serde_test.cc @@ -17,8 +17,13 @@ * under the License. */ +#include +#include +#include #include #include +#include +#include #include #include @@ -134,6 +139,24 @@ nlohmann::json HistoricalSortOrderWithDroppedFieldMetadataJson( return metadata_json; } +nlohmann::json V4MetadataJson() { + std::ifstream file(GetResourcePath("TableMetadataV4ValidMinimal.json")); + return nlohmann::json::parse(file); +} + +nlohmann::json RootManifestSnapshotJson() { + return nlohmann::json::parse(R"({ + "snapshot-id": 1, + "sequence-number": 1, + "timestamp-ms": 1000, + "root-manifest": "metadata/root.avro", + "summary": {"operation": "append"}, + "schema-id": 0, + "first-row-id": 0, + "added-rows": 10 + })"); +} + } // namespace TEST(MetadataSerdeTest, DeserializeV1Valid) { @@ -484,6 +507,282 @@ TEST(MetadataSerdeTest, V3DefaultValuesRoundTrip) { EXPECT_EQ(*reparsed, *metadata); } +TEST(MetadataSerdeTest, V4RoundTrip) { + ICEBERG_UNWRAP_OR_FAIL( + auto metadata, ReadTableMetadataFromResource("TableMetadataV4ValidMinimal.json")); + EXPECT_EQ(metadata->format_version, 4); + EXPECT_EQ(metadata->next_row_id, 0); + EXPECT_TRUE(metadata->snapshots.empty()); + EXPECT_FALSE(metadata->HasRootManifest()); + EXPECT_FALSE(metadata->table_uuid.empty()); + ICEBERG_UNWRAP_OR_FAIL(auto json, ToJson(*metadata)); + EXPECT_EQ(json["format-version"], 4); + EXPECT_EQ(json["next-row-id"], 0); + ICEBERG_UNWRAP_OR_FAIL(auto parsed, TableMetadataFromJson(json)); + EXPECT_EQ(*metadata, *parsed); +} + +TEST(MetadataSerdeTest, SerializationRejectsNullSnapshots) { + auto snapshot_json = RootManifestSnapshotJson(); + snapshot_json.erase("root-manifest"); + snapshot_json["manifest-list"] = "s3://bucket/metadata/legacy.avro"; + ICEBERG_UNWRAP_OR_FAIL(auto snapshot, SnapshotFromJson(snapshot_json)); + auto valid = std::shared_ptr(std::move(snapshot)); + for (int version : {1, 2, 3, 4}) { + SCOPED_TRACE(version); + auto json = V4MetadataJson(); + json["format-version"] = version; + ICEBERG_UNWRAP_OR_FAIL(auto metadata, TableMetadataFromJson(json)); + for (bool null_first : {false, true}) { + metadata->snapshots = null_first + ? std::vector>{nullptr, valid} + : std::vector>{valid, nullptr}; + EXPECT_FALSE(metadata->HasRootManifest()); + auto result = ToJson(*metadata); + EXPECT_THAT(result, IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(result, HasErrorMessage("Cannot write null snapshot")); + } + } +} + +TEST(MetadataSerdeTest, V4RequiresLocationUntilSupported) { + for (bool explicit_null : {false, true}) { + auto json = V4MetadataJson(); + if (explicit_null) { + json["location"] = nullptr; + } else { + json.erase("location"); + } + EXPECT_THAT(TableMetadataFromJson(json), IsError(ErrorKind::kNotSupported)); + } + ICEBERG_UNWRAP_OR_FAIL( + auto metadata, ReadTableMetadataFromResource("TableMetadataV4ValidMinimal.json")); + metadata->location.clear(); + EXPECT_THAT(ToJson(*metadata), IsError(ErrorKind::kNotSupported)); +} + +TEST(MetadataSerdeTest, V4RejectsRelativeLocationAndMissingRequiredFields) { + auto json = V4MetadataJson(); + json["location"] = "relative/table"; + EXPECT_THAT(TableMetadataFromJson(json), IsError(ErrorKind::kJsonParseError)); + EXPECT_THAT(TableMetadataFromJson(json), HasErrorMessage("location must be absolute")); + ICEBERG_UNWRAP_OR_FAIL( + auto metadata, ReadTableMetadataFromResource("TableMetadataV4ValidMinimal.json")); + metadata->location = "relative/table"; + EXPECT_THAT(metadata->ValidateLocation(), IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(ToJson(*metadata), IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(ToJson(*metadata), HasErrorMessage("location must be absolute")); + json = V4MetadataJson(); + json.erase("next-row-id"); + EXPECT_FALSE(TableMetadataFromJson(json).has_value()); +} + +TEST(MetadataSerdeTest, V4RootManifestRoundTrip) { + auto json = V4MetadataJson(); + json["snapshots"] = nlohmann::json::array({RootManifestSnapshotJson()}); + for (int64_t sequence : {0, 1}) { + for (int64_t next_row_id : {0, 9, 10}) { + if (sequence == 1 && next_row_id == 10) { + continue; + } + SCOPED_TRACE(sequence); + SCOPED_TRACE(next_row_id); + auto invalid = json; + invalid["last-sequence-number"] = sequence; + invalid["next-row-id"] = next_row_id; + auto result = TableMetadataFromJson(invalid); + EXPECT_THAT(result, IsError(ErrorKind::kJsonParseError)); + EXPECT_THAT(result, HasErrorMessage(sequence == 0 ? "last-sequence-number" + : "next-row-id")); + } + } + // Counters may retain allocations from newer snapshots that have expired. + for (int64_t sequence : {1, 2}) { + for (int64_t next_row_id : {10, 20}) { + SCOPED_TRACE(sequence); + SCOPED_TRACE(next_row_id); + json["last-sequence-number"] = sequence; + json["next-row-id"] = next_row_id; + ICEBERG_UNWRAP_OR_FAIL(auto metadata, TableMetadataFromJson(json)); + ASSERT_EQ(metadata->snapshots.size(), 1); + EXPECT_TRUE(metadata->HasRootManifest()); + auto snapshot = metadata->snapshots.front(); + EXPECT_EQ(snapshot->root_manifest, "metadata/root.avro"); + EXPECT_TRUE(snapshot->manifest_list.empty()); + ICEBERG_UNWRAP_OR_FAIL(auto serialized, ToJson(*metadata)); + EXPECT_EQ(serialized["snapshots"][0], RootManifestSnapshotJson()); + EXPECT_FALSE(serialized["snapshots"][0].contains("manifest-list")); + ICEBERG_UNWRAP_OR_FAIL(auto parsed, TableMetadataFromJson(serialized)); + EXPECT_EQ(parsed->snapshots.front()->root_manifest, snapshot->root_manifest); + EXPECT_EQ(parsed->last_sequence_number, sequence); + EXPECT_EQ(parsed->next_row_id, next_row_id); + } + } +} + +TEST(MetadataSerdeTest, V4RejectsInvalidSnapshotRoots) { + for (const auto* field : + {"root-manifest", "sequence-number", "first-row-id", "added-rows", "summary"}) { + auto json = RootManifestSnapshotJson(); + json.erase(field); + auto table_json = V4MetadataJson(); + table_json["snapshots"] = nlohmann::json::array({json}); + EXPECT_FALSE(TableMetadataFromJson(table_json).has_value()) << field; + } +} + +TEST(MetadataSerdeTest, SnapshotValidationUsesTableFormatVersion) { + for (int8_t version : {1, 2, 3, 4}) { + SCOPED_TRACE(version); + auto json = V4MetadataJson(); + json["format-version"] = version; + json["last-sequence-number"] = 1; + json["next-row-id"] = 10; + json["snapshots"] = nlohmann::json::array({RootManifestSnapshotJson()}); + auto root = TableMetadataFromJson(json); + if (version < TableMetadata::kMinFormatVersionRootManifest) { + EXPECT_THAT(root, IsError(ErrorKind::kJsonParseError)); + EXPECT_THAT( + root, + HasErrorMessage("requires format version " + + std::to_string(TableMetadata::kMinFormatVersionRootManifest))); + } else { + EXPECT_THAT(root, IsOk()); + } + auto legacy = RootManifestSnapshotJson(); + legacy.erase("root-manifest"); + legacy["manifest-list"] = "legacy.avro"; + json["snapshots"] = nlohmann::json::array({legacy}); + EXPECT_THAT(TableMetadataFromJson(json), IsOk()); + } +} + +TEST(MetadataSerdeTest, V4RejectsWritingIdentifierFieldsWithoutMigration) { + for (bool historical_schema : {false, true}) { + ICEBERG_UNWRAP_OR_FAIL( + auto metadata, ReadTableMetadataFromResource("TableMetadataV4ValidMinimal.json")); + ICEBERG_UNWRAP_OR_FAIL( + auto schema, Schema::Make({SchemaField::MakeRequired(1, "id", int64())}, + historical_schema ? 1 : 0, std::vector{1})); + if (historical_schema) { + metadata->schemas.push_back(std::move(schema)); + } else { + metadata->schemas[0] = std::move(schema); + } + EXPECT_THAT(ToJson(*metadata), IsError(ErrorKind::kNotSupported)); + ASSERT_EQ(metadata->schemas.back()->IdentifierFieldIds(), std::vector{1}); + } +} + +TEST(MetadataSerdeTest, V4IgnoresLegacyIdentifiersAndRejectsUnimplementedConstraints) { + auto json = V4MetadataJson(); + json["schemas"][0]["identifier-field-ids"] = {999}; + ICEBERG_UNWRAP_OR_FAIL(auto metadata, TableMetadataFromJson(json)); + ICEBERG_UNWRAP_OR_FAIL(auto schema, metadata->Schema()); + EXPECT_TRUE(schema->IdentifierFieldIds().empty()); + ICEBERG_UNWRAP_OR_FAIL(auto serialized, ToJson(*metadata)); + EXPECT_FALSE(serialized["schemas"][0].contains("identifier-field-ids")); + for (const auto* field : {"constraints", "last-constraint-id"}) { + json = V4MetadataJson(); + json[field] = field == std::string_view("constraints") + ? nlohmann::json::array({{{"constraint-id", 1}}}) + : nlohmann::json(1); + EXPECT_THAT(TableMetadataFromJson(json), IsError(ErrorKind::kNotSupported)); + } + for (const auto& malformed_schema : std::vector{nullptr, 1, "schema"}) { + json = V4MetadataJson(); + json["schemas"] = nlohmann::json::array({malformed_schema}); + EXPECT_FALSE(TableMetadataFromJson(json).has_value()); + } +} + +TEST(MetadataSerdeTest, V4ConstraintFieldsRequireTheirDeclaredJsonTypes) { + auto json = V4MetadataJson(); + json["constraints"] = nlohmann::json::array(); + json["last-constraint-id"] = 0; + EXPECT_THAT(TableMetadataFromJson(json), IsOk()); + for (const auto* field : {"constraints", "last-constraint-id"}) { + auto nullable = json; + nullable[field] = nullptr; + EXPECT_THAT(TableMetadataFromJson(nullable), IsOk()); + } + for (const auto& value : std::vector{"constraints", true, 0, 0.0, + nlohmann::json::object()}) { + SCOPED_TRACE(value.dump()); + json = V4MetadataJson(); + json["constraints"] = value; + auto result = TableMetadataFromJson(json); + EXPECT_THAT(result, IsError(ErrorKind::kJsonParseError)); + EXPECT_THAT(result, HasErrorMessage("constraints")); + } + for (const auto& value : std::vector{ + "0", true, 0.0, 1.5, 2147483648LL, -2147483649LL, 18446744073709551615ULL, + nlohmann::json::array(), nlohmann::json::object()}) { + SCOPED_TRACE(value.dump()); + json = V4MetadataJson(); + json["last-constraint-id"] = value; + auto result = TableMetadataFromJson(json); + EXPECT_THAT(result, IsError(ErrorKind::kJsonParseError)); + EXPECT_THAT(result, HasErrorMessage("last-constraint-id")); + } +} + +TEST(MetadataSerdeTest, V4RejectsIncompleteSnapshotWrites) { + ICEBERG_UNWRAP_OR_FAIL( + auto metadata, ReadTableMetadataFromResource("TableMetadataV4ValidMinimal.json")); + ICEBERG_UNWRAP_OR_FAIL(auto snapshot, SnapshotFromJson(RootManifestSnapshotJson())); + snapshot->first_row_id.reset(); + metadata->snapshots.push_back(std::move(snapshot)); + EXPECT_THAT(ToJson(*metadata), HasErrorMessage("first-row-id")); +} + +TEST(MetadataSerdeTest, MissingOrNullUuidUsesTheDefaultForEveryVersion) { + for (int version : {1, 2, 3, 4}) { + auto json = V4MetadataJson(); + json["format-version"] = version; + for (bool explicit_null : {false, true}) { + if (explicit_null) { + json["table-uuid"] = nullptr; + } else { + json.erase("table-uuid"); + } + ICEBERG_UNWRAP_OR_FAIL(auto metadata, TableMetadataFromJson(json)); + EXPECT_TRUE(metadata->table_uuid.empty()); + } + } +} + +TEST(MetadataSerdeTest, V4RootOperationValidationIsSharedAcrossMetadataPaths) { + for (const auto& operation : + std::vector>{std::nullopt, "", "invalid"}) { + auto json = RootManifestSnapshotJson(); + if (operation.has_value()) { + json["summary"]["operation"] = operation.value(); + } else { + json["summary"].erase("operation"); + } + auto table_json = V4MetadataJson(); + table_json["snapshots"] = nlohmann::json::array({json}); + EXPECT_THAT(TableMetadataFromJson(table_json), HasErrorMessage("valid operation")); + + ICEBERG_UNWRAP_OR_FAIL(auto snapshot, SnapshotFromJson(RootManifestSnapshotJson())); + if (operation.has_value()) { + snapshot->summary["operation"] = operation.value(); + } else { + snapshot->summary.erase("operation"); + } + EXPECT_THAT(snapshot->ValidateForFormatVersion(4), + IsError(ErrorKind::kValidationFailed)); + ICEBERG_UNWRAP_OR_FAIL( + auto base, ReadTableMetadataFromResource("TableMetadataV4ValidMinimal.json")); + auto builder = TableMetadataBuilder::BuildFrom(base.get()); + builder->AddSnapshot(std::make_shared(*snapshot)); + EXPECT_THAT(builder->Build(), HasErrorMessage("valid operation")); + base->snapshots.push_back(std::move(snapshot)); + EXPECT_THAT(ToJson(*base), HasErrorMessage("valid operation")); + } +} + TEST(MetadataSerdeTest, DeserializeUnsupportedVersion) { ReadTableMetadataExpectError("TableMetadataUnsupportedVersion.json", "Cannot read unsupported version"); diff --git a/src/iceberg/test/resources/TableMetadataV4ValidMinimal.json b/src/iceberg/test/resources/TableMetadataV4ValidMinimal.json new file mode 100644 index 0000000000..5740a3ae52 --- /dev/null +++ b/src/iceberg/test/resources/TableMetadataV4ValidMinimal.json @@ -0,0 +1,40 @@ +{ + "format-version": 4, + "table-uuid": "c9dc1a9f-6564-42ec-9a87-1db146e18019", + "location": "s3://bucket/table", + "last-sequence-number": 0, + "last-updated-ms": 1000, + "last-column-id": 1, + "schemas": [ + { + "type": "struct", + "schema-id": 0, + "fields": [ + { + "id": 1, + "name": "id", + "type": "long", + "required": true + } + ] + } + ], + "current-schema-id": 0, + "partition-specs": [ + { + "spec-id": 0, + "fields": [] + } + ], + "default-spec-id": 0, + "last-partition-id": 999, + "sort-orders": [ + { + "order-id": 0, + "fields": [] + } + ], + "default-sort-order-id": 0, + "next-row-id": 0, + "snapshots": [] +} diff --git a/src/iceberg/test/rest_catalog_unit_test.cc b/src/iceberg/test/rest_catalog_unit_test.cc index 59e672c8bf..0cd3bb43e1 100644 --- a/src/iceberg/test/rest_catalog_unit_test.cc +++ b/src/iceberg/test/rest_catalog_unit_test.cc @@ -19,6 +19,7 @@ #include #include +#include #include #include #include @@ -232,6 +233,46 @@ class RestCatalogLoadTableTest : public ::testing::Test { std::unordered_set no_plan_endpoint_set_; }; +TEST_F(RestCatalogLoadTableTest, RejectsSchemaSpecPruningBeforeSendingCommit) { + ICEBERG_UNWRAP_OR_FAIL(auto root, MakeCatalog(all_plan_endpoints_)); + ICEBERG_UNWRAP_OR_FAIL(auto catalog, root->AsCatalog()); + EXPECT_CALL(*mock_client_, Get(::testing::EndsWith("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/tables/my_table"), _, _, _, _)) + .WillOnce(Return(HttpResponse(200, kLoadTableDefaultResponse))); + ICEBERG_UNWRAP_OR_FAIL(auto loaded_table, catalog->LoadTable(identifier_)); + ON_CALL(*mock_client_, Post(_, _, _, _, _)) + .WillByDefault([](auto&&...) -> Result { + return HttpResponse(200, kCommitTableResponse); + }); + EXPECT_CALL(*mock_client_, Post(_, _, _, _, _)).Times(0); + // Even an older loaded table may have been upgraded concurrently on the server. + for (const auto& handle : {catalog, loaded_table->catalog()}) { + for (bool remove_schema : {false, true}) { + SCOPED_TRACE(remove_schema); + std::vector> updates; + if (remove_schema) { + updates.push_back( + std::make_unique(std::unordered_set{2})); + } else { + updates.push_back( + std::make_unique(std::vector{1})); + } + auto result = handle->UpdateTable(identifier_, {}, updates); + EXPECT_THAT(result, IsError(ErrorKind::kNotSupported)); + EXPECT_THAT(result, HasErrorMessage("server")); + } + } +} + +TEST_F(RestCatalogLoadTableTest, AllowsSnapshotRemovalWithoutSchemaSpecPruning) { + ICEBERG_UNWRAP_OR_FAIL(auto root, MakeCatalog(all_plan_endpoints_)); + ICEBERG_UNWRAP_OR_FAIL(auto catalog, root->AsCatalog()); + EXPECT_CALL(*mock_client_, Post(::testing::EndsWith("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/tables/my_table"), _, _, _, _)) + .WillOnce(Return(HttpResponse(200, kCommitTableResponse))); + std::vector> updates; + updates.push_back(std::make_unique(std::vector{10})); + EXPECT_THAT(catalog->UpdateTable(identifier_, {}, updates), IsOk()); +} + class RestCatalogLabelsTest : public RestCatalogLoadTableTest, public ::testing::WithParamInterface { protected: diff --git a/src/iceberg/test/snapshot_test.cc b/src/iceberg/test/snapshot_test.cc index 2be6a19866..e0b81b7199 100644 --- a/src/iceberg/test/snapshot_test.cc +++ b/src/iceberg/test/snapshot_test.cc @@ -18,8 +18,11 @@ */ #include "iceberg/snapshot.h" +#include + #include +#include "iceberg/test/matchers.h" #include "iceberg/util/timepoint.h" namespace iceberg { @@ -120,4 +123,36 @@ TEST_F(SnapshotTest, EqualityComparison) { EXPECT_NE(snapshot1, snapshot3); } +TEST_F(SnapshotTest, RootManifestRequirementAppliesOnlyToNewV4Snapshots) { + Snapshot snapshot{.snapshot_id = 1, + .sequence_number = 1, + .timestamp_ms = TimePointMsFromUnixMs(1000), + .summary = summary1, + .schema_id = 0, + .first_row_id = 0, + .added_rows = 10}; + for (int8_t version : {1, 2, 3}) { + SCOPED_TRACE(version); + EXPECT_THAT(snapshot.ValidateForFormatVersion(version, true), IsOk()); + } + constexpr int8_t format_version = 4; + EXPECT_THAT(snapshot.ValidateForFormatVersion(format_version), IsOk()); + EXPECT_THAT(snapshot.ValidateForFormatVersion(format_version, true), + HasErrorMessage("New v" + std::to_string(format_version) + + " snapshots require root-manifest")); +} + +TEST_F(SnapshotTest, ReadingRootManifestsIsNotSupported) { + Snapshot snapshot{.snapshot_id = 1, + .sequence_number = 1, + .timestamp_ms = TimePointMsFromUnixMs(1000), + .summary = summary1, + .schema_id = 0, + .first_row_id = 0, + .added_rows = 10, + .root_manifest = "metadata/root.avro"}; + EXPECT_THAT(SnapshotReader(&snapshot).Manifests(nullptr), + IsError(ErrorKind::kNotSupported)); +} + } // namespace iceberg diff --git a/src/iceberg/test/sql_catalog_test.cc b/src/iceberg/test/sql_catalog_test.cc index f46877c357..c3c82a2461 100644 --- a/src/iceberg/test/sql_catalog_test.cc +++ b/src/iceberg/test/sql_catalog_test.cc @@ -31,6 +31,8 @@ #include #include +#include +#include #include #include #include @@ -306,7 +308,8 @@ TEST_P(SqlCatalogFormatVersionTest, CreateTable) { ASSERT_THAT(catalog_->CreateNamespace(ns, {}), IsOk()); const auto [staged, version] = GetParam(); TableIdentifier ident{.ns = ns, .name = "versioned_table"}; - const auto location = MakeTableLocation(ident.name); + auto location = ::arrow::util::UriFromAbsolutePath(MakeTableLocation(ident.name)); + ASSERT_TRUE(location.ok()) << location.status().ToString(); const std::unordered_map properties = { {"format-version", std::to_string(version)}, {"owner", "alice"}}; std::shared_ptr
created; @@ -314,7 +317,7 @@ TEST_P(SqlCatalogFormatVersionTest, CreateTable) { ICEBERG_UNWRAP_OR_FAIL( auto transaction, catalog_->StageCreateTable(ident, MakeSchema(), PartitionSpec::Unpartitioned(), - SortOrder::Unsorted(), location, properties)); + SortOrder::Unsorted(), *location, properties)); EXPECT_EQ(transaction->current().format_version, version); EXPECT_THAT(catalog_->TableExists(ident), HasValue(::testing::Eq(false))); ICEBERG_UNWRAP_OR_FAIL(created, transaction->Commit()); @@ -322,23 +325,24 @@ TEST_P(SqlCatalogFormatVersionTest, CreateTable) { ICEBERG_UNWRAP_OR_FAIL( created, catalog_->CreateTable(ident, MakeSchema(), PartitionSpec::Unpartitioned(), - SortOrder::Unsorted(), location, properties)); + SortOrder::Unsorted(), *location, properties)); } EXPECT_EQ(created->metadata()->format_version, version); ICEBERG_UNWRAP_OR_FAIL(auto loaded, catalog_->LoadTable(ident)); EXPECT_EQ(loaded->metadata()->format_version, version); EXPECT_THAT(loaded->properties().configs(), ::testing::UnorderedElementsAre(::testing::Pair("owner", "alice"))); - std::ifstream input(std::string(loaded->metadata_file_location())); - ASSERT_TRUE(input.is_open()); - const auto json = nlohmann::json::parse(input); + ICEBERG_UNWRAP_OR_FAIL( + auto content, + file_io_->ReadFile(std::string(loaded->metadata_file_location()), std::nullopt)); + const auto json = nlohmann::json::parse(content); EXPECT_EQ(json.at("format-version"), version); EXPECT_FALSE(json.at("properties").contains("format-version")); } INSTANTIATE_TEST_SUITE_P(SupportedVersions, SqlCatalogFormatVersionTest, ::testing::Combine(::testing::Bool(), - ::testing::Values(1, 2, 3)), + ::testing::Values(1, 2, 3, 4)), [](const ::testing::TestParamInfo>& info) { return std::string(std::get<0>(info.param) ? "StagedV" : "CreateV") + @@ -411,7 +415,7 @@ INSTANTIATE_TEST_SUITE_P( InvalidVersions, SqlCatalogInvalidFormatVersionTest, ::testing::Combine(::testing::Bool(), ::testing::Values("", "abc", "2x", "1.5", "2147483648", "0", "-1", - "4", "257")), + "5", "257")), [](const ::testing::TestParamInfo>& info) { return std::string(std::get<0>(info.param) ? "StagedCase" : "CreateCase") + std::to_string(info.index); diff --git a/src/iceberg/test/table_metadata_builder_test.cc b/src/iceberg/test/table_metadata_builder_test.cc index bb5a50a19e..aa0234a2a1 100644 --- a/src/iceberg/test/table_metadata_builder_test.cc +++ b/src/iceberg/test/table_metadata_builder_test.cc @@ -18,6 +18,7 @@ */ #include +#include #include #include #include @@ -94,6 +95,19 @@ std::unique_ptr CreateBaseMetadata( return metadata; } +std::shared_ptr CreateRootManifestSnapshot() { + return std::make_shared(Snapshot{ + .snapshot_id = 1, + .sequence_number = 1, + .timestamp_ms = TimePointMsFromUnixMs(1000), + .summary = {{"operation", "append"}}, + .schema_id = 0, + .first_row_id = 0, + .added_rows = 10, + .root_manifest = "metadata/root.avro", + }); +} + } // namespace // test for TableMetadata @@ -161,10 +175,14 @@ TEST_P(TableMetadataFormatVersionTest, MakeWithProperty) { EXPECT_THAT(metadata->properties.configs(), ::testing::UnorderedElementsAre(::testing::Pair("owner", "alice"))); EXPECT_EQ(properties.at("format-version"), std::to_string(version)); + EXPECT_EQ(metadata->next_row_id, TableMetadata::kInitialRowId); + EXPECT_TRUE(metadata->snapshots.empty()); + EXPECT_FALSE(metadata->HasRootManifest()); + EXPECT_FALSE(metadata->table_uuid.empty()); } INSTANTIATE_TEST_SUITE_P(SupportedVersions, TableMetadataFormatVersionTest, - ::testing::Values(1, 2, 3), + ::testing::Values(1, 2, 3, 4), [](const ::testing::TestParamInfo& info) { return "V" + std::to_string(info.param); }); @@ -181,7 +199,7 @@ TEST_P(TableMetadataInvalidFormatVersionTest, MakeRejectsProperty) { } INSTANTIATE_TEST_SUITE_P(UnsupportedVersions, TableMetadataInvalidFormatVersionTest, - ::testing::Values(0, -1, 4, 257)); + ::testing::Values(0, -1, 5, 257)); struct InvalidFormatVersionString { std::string name; @@ -542,7 +560,7 @@ TEST(TableMetadataBuilderTest, UpgradeFormatVersion) { // Unsupported format version should fail builder = TableMetadataBuilder::BuildFromEmpty(3); - builder->UpgradeFormatVersion(4); + builder->UpgradeFormatVersion(5); EXPECT_THAT(builder->Build(), HasErrorMessage("Cannot upgrade table to unsupported format version")); @@ -552,6 +570,301 @@ TEST(TableMetadataBuilderTest, UpgradeFormatVersion) { EXPECT_THAT(builder->Build(), HasErrorMessage("Cannot downgrade")); } +TEST(TableMetadataBuilderTest, UpgradeToV4PreservesLegacySnapshots) { + for (int8_t version : {1, 2, 3}) { + SCOPED_TRACE(version); + for (int64_t timestamp : {999, 1000}) { + SCOPED_TRACE(timestamp); + auto base = CreateBaseMetadata(); + base->format_version = version; + auto parent = CreateRootManifestSnapshot(); + parent->sequence_number = version == 1 ? 0 : 1; + parent->root_manifest.reset(); + parent->manifest_list = "s3://bucket/table/metadata/parent.avro"; + auto child = std::make_shared(*parent); + child->snapshot_id = 2; + child->parent_snapshot_id = parent->snapshot_id; + child->sequence_number = version == 1 ? 0 : 2; + child->first_row_id = 10; + child->timestamp_ms = TimePointMsFromUnixMs(timestamp); + child->manifest_list = "s3://bucket/table/metadata/child.avro"; + base->snapshots = {parent, child}; + base->last_sequence_number = child->sequence_number; + base->current_snapshot_id = child->snapshot_id; + base->snapshot_log = { + {.timestamp_ms = parent->timestamp_ms, .snapshot_id = parent->snapshot_id}, + {.timestamp_ms = child->timestamp_ms, .snapshot_id = child->snapshot_id}}; + base->refs[std::string(SnapshotRef::kMainBranch)] = + std::make_shared(SnapshotRef{.snapshot_id = child->snapshot_id, + .retention = SnapshotRef::Branch{}}); + base->next_row_id = 20; + auto builder = TableMetadataBuilder::BuildFrom(base.get()); + builder->UpgradeFormatVersion(4); + ICEBERG_UNWRAP_OR_FAIL(auto upgraded, builder->Build()); + EXPECT_EQ(upgraded->format_version, 4); + EXPECT_EQ(upgraded->next_row_id, 20); + EXPECT_EQ(upgraded->table_uuid, base->table_uuid); + EXPECT_EQ(upgraded->snapshot_log, base->snapshot_log); + ASSERT_EQ(upgraded->snapshots.size(), 2); + for (size_t i = 0; i < upgraded->snapshots.size(); ++i) { + EXPECT_EQ(upgraded->snapshots[i]->manifest_list, + base->snapshots[i]->manifest_list); + EXPECT_EQ(upgraded->snapshots[i]->timestamp_ms, base->snapshots[i]->timestamp_ms); + EXPECT_FALSE(upgraded->snapshots[i]->root_manifest.has_value()); + } + ASSERT_EQ(builder->changes().size(), 1); + EXPECT_EQ(builder->changes().front()->kind(), + TableUpdate::Kind::kUpgradeFormatVersion); + ICEBERG_UNWRAP_OR_FAIL(auto json, ToJson(*upgraded)); + ICEBERG_UNWRAP_OR_FAIL(auto parsed, TableMetadataFromJson(json)); + EXPECT_EQ(*parsed, *upgraded); + for (int64_t offset : {-1, 0, 1}) { + auto snapshot = CreateRootManifestSnapshot(); + snapshot->snapshot_id = 3; + snapshot->parent_snapshot_id = child->snapshot_id; + snapshot->sequence_number = child->sequence_number + 1; + snapshot->first_row_id = 20; + snapshot->timestamp_ms = TimePointMsFromUnixMs(timestamp + offset); + auto append = TableMetadataBuilder::BuildFrom(parsed.get()); + append->AddSnapshot(std::move(snapshot)); + if (offset <= 0) { + auto result = append->Build(); + EXPECT_THAT(result, IsError(ErrorKind::kValidationFailed)); + EXPECT_THAT(result, HasErrorMessage("timestamp")); + } else { + EXPECT_THAT(append->Build(), IsOk()); + } + } + auto downgrade = TableMetadataBuilder::BuildFrom(upgraded.get()); + downgrade->UpgradeFormatVersion(3); + EXPECT_THAT(downgrade->Build(), HasErrorMessage("Cannot downgrade")); + } + } +} + +TEST(TableMetadataBuilderTest, AddLegacySnapshotsBeforeV4) { + for (int8_t version : {1, 2, 3}) { + SCOPED_TRACE(version); + auto metadata = CreateBaseMetadata(); + metadata->format_version = version; + auto snapshot = CreateRootManifestSnapshot(); + snapshot->root_manifest.reset(); + snapshot->manifest_list.clear(); + auto builder = TableMetadataBuilder::BuildFrom(metadata.get()); + builder->AddSnapshot(snapshot); + ICEBERG_UNWRAP_OR_FAIL(auto updated, builder->Build()); + EXPECT_THAT(ToJson(*updated), IsOk()); + } +} + +TEST(TableMetadataBuilderTest, V4SnapshotsRequireRootManifests) { + auto base = CreateBaseMetadata(); + base->format_version = 4; + base->snapshots.push_back(CreateRootManifestSnapshot()); + base->last_sequence_number = 1; + base->next_row_id = 10; + auto child = CreateRootManifestSnapshot(); + child->snapshot_id = 2; + child->parent_snapshot_id = 1; + child->sequence_number = 2; + child->first_row_id = 10; + child->timestamp_ms = TimePointMsFromUnixMs(1001); + child->root_manifest.reset(); + child->manifest_list = "legacy.avro"; + auto builder = TableMetadataBuilder::BuildFrom(base.get()); + builder->AddSnapshot(std::move(child)); + EXPECT_THAT(builder->Build(), + HasErrorMessage("New v" + std::to_string(base->format_version) + + " snapshots require root-manifest")); +} + +TEST(TableMetadataBuilderTest, + V4StaleSequenceIsRetryableBeforeParentTimestampValidation) { + auto base = CreateBaseMetadata(); + base->format_version = 4; + base->snapshots.push_back(CreateRootManifestSnapshot()); + base->last_sequence_number = 1; + base->next_row_id = 10; + // A stale sequence must take retry precedence over an invalid parent timestamp. + for (int64_t timestamp : {999, 1000, 1001}) { + for (int64_t sequence : {1, 2}) { + SCOPED_TRACE(timestamp); + SCOPED_TRACE(sequence); + auto child = CreateRootManifestSnapshot(); + child->snapshot_id = 2; + child->parent_snapshot_id = 1; + child->first_row_id = 10; + child->sequence_number = sequence; + child->timestamp_ms = TimePointMsFromUnixMs(timestamp); + auto builder = TableMetadataBuilder::BuildFrom(base.get()); + builder->AddSnapshot(std::move(child)); + auto result = builder->Build(); + if (sequence == 2 && timestamp > 1000) { + ASSERT_THAT(result, IsOk()); + EXPECT_EQ(result.value()->next_row_id, 20); + } else { + EXPECT_THAT(result, IsError(sequence == 1 ? ErrorKind::kRetryableValidationFailed + : ErrorKind::kValidationFailed)); + EXPECT_THAT(result, + HasErrorMessage(sequence == 1 ? "sequence number" : "timestamp")); + EXPECT_TRUE(builder->changes().empty()); + } + } + } +} + +TEST(TableMetadataBuilderTest, RootSnapshotsRequireAlignedRowIdsBeforeMutation) { + for (int64_t first_row_id : {99, 100, 200}) { + SCOPED_TRACE(first_row_id); + auto base = CreateBaseMetadata(); + base->format_version = 4; + base->next_row_id = 100; + auto snapshot = CreateRootManifestSnapshot(); + snapshot->first_row_id = first_row_id; + auto builder = TableMetadataBuilder::BuildFrom(base.get()); + const auto metadata_before = builder->current(); + builder->AddSnapshot(std::move(snapshot)); + auto result = builder->Build(); + if (first_row_id == 100) { + ASSERT_THAT(result, IsOk()); + EXPECT_EQ(result.value()->next_row_id, 110); + } else { + EXPECT_THAT(result, IsError(ErrorKind::kRetryableValidationFailed)); + EXPECT_EQ(builder->current(), metadata_before); + EXPECT_TRUE(builder->changes().empty()); + } + } +} + +TEST(TableMetadataBuilderTest, RootSnapshotsCheckRowIdOverflowBeforeMutation) { + for (int64_t added_rows : {5, 6}) { + SCOPED_TRACE(added_rows); + auto base = CreateBaseMetadata(); + base->format_version = 4; + base->next_row_id = std::numeric_limits::max() - 5; + auto snapshot = CreateRootManifestSnapshot(); + snapshot->first_row_id = base->next_row_id; + snapshot->added_rows = added_rows; + auto builder = TableMetadataBuilder::BuildFrom(base.get()); + const auto metadata_before = builder->current(); + builder->AddSnapshot(std::move(snapshot)); + auto result = builder->Build(); + if (added_rows == 5) { + ASSERT_THAT(result, IsOk()); + EXPECT_EQ(result.value()->next_row_id, std::numeric_limits::max()); + } else { + EXPECT_THAT(result, IsError(ErrorKind::kValidationFailed)); + EXPECT_EQ(builder->current(), metadata_before); + EXPECT_TRUE(builder->changes().empty()); + } + } +} + +TEST(TableMetadataBuilderTest, ParentlessRootsCannotLowerSequenceNumbers) { + for (int64_t sequence : {4, 5, 6}) { + SCOPED_TRACE(sequence); + auto base = CreateBaseMetadata(); + base->format_version = 4; + base->last_sequence_number = 5; + auto snapshot = CreateRootManifestSnapshot(); + snapshot->sequence_number = sequence; + auto builder = TableMetadataBuilder::BuildFrom(base.get()); + const auto metadata_before = builder->current(); + builder->AddSnapshot(std::move(snapshot)); + auto result = builder->Build(); + if (sequence == 6) { + ASSERT_THAT(result, IsOk()); + EXPECT_EQ(result.value()->last_sequence_number, 6); + } else { + EXPECT_THAT(result, IsError(ErrorKind::kRetryableValidationFailed)); + EXPECT_EQ(builder->current(), metadata_before); + EXPECT_TRUE(builder->changes().empty()); + } + } +} + +TEST(TableMetadataBuilderTest, RootSnapshotsPreventSchemaSpecPruningInEitherOrder) { + for (bool remove_schema : {false, true}) { + for (bool root_first : {false, true}) { + SCOPED_TRACE(remove_schema); + SCOPED_TRACE(root_first); + auto base = CreateBaseMetadata(); + base->format_version = 4; + ICEBERG_UNWRAP_OR_FAIL( + auto schema, Schema::Make(std::vector{SchemaField::MakeRequired( + 1, "old", int32())}, + 1, std::vector{})); + base->schemas.push_back(std::move(schema)); + ICEBERG_UNWRAP_OR_FAIL(auto spec, PartitionSpec::Make(1, {})); + base->partition_specs.push_back(std::move(spec)); + auto builder = TableMetadataBuilder::BuildFrom(base.get()); + if (root_first) { + builder->AddSnapshot(CreateRootManifestSnapshot()); + } + if (remove_schema) { + builder->RemoveSchemas({1}); + } else { + builder->RemovePartitionSpecs({1}); + } + if (!root_first) { + builder->AddSnapshot(CreateRootManifestSnapshot()); + } + EXPECT_THAT(builder->Build(), IsError(ErrorKind::kNotSupported)); + } + } +} + +TEST(TableMetadataBuilderTest, V4RejectsIdentifierFieldsWithoutMigration) { + for (bool historical_schema : {false, true}) { + auto metadata = CreateBaseMetadata(); + metadata->format_version = 4; + ICEBERG_UNWRAP_OR_FAIL( + auto schema, Schema::Make({SchemaField::MakeRequired(1, "id", int64())}, + historical_schema ? 1 : 0, std::vector{1})); + if (historical_schema) { + metadata->schemas.push_back(std::move(schema)); + } else { + metadata->schemas[0] = std::move(schema); + } + auto builder = TableMetadataBuilder::BuildFrom(metadata.get()); + EXPECT_THAT(builder->Build(), IsError(ErrorKind::kNotSupported)); + EXPECT_EQ(metadata->schemas.back()->IdentifierFieldIds(), std::vector{1}); + if (!historical_schema) { + metadata->format_version = 3; + builder = TableMetadataBuilder::BuildFrom(metadata.get()); + builder->UpgradeFormatVersion(4); + EXPECT_THAT(builder->Build(), HasErrorMessage("primary-key constraint migration")); + } + } +} + +TEST(TableMetadataBuilderTest, UpgradeToV4BeforeSelectingCurrentSchema) { + auto metadata = CreateBaseMetadata(); + metadata->format_version = 3; + metadata->current_schema_id = -1; + auto builder = TableMetadataBuilder::BuildFrom(metadata.get()); + builder->AddSchema(CreateTestSchema()).UpgradeFormatVersion(4).SetCurrentSchema(0); + ICEBERG_UNWRAP_OR_FAIL(auto upgraded, builder->Build()); + EXPECT_EQ(upgraded->format_version, 4); + EXPECT_EQ(upgraded->current_schema_id, 0); +} + +TEST(TableMetadataBuilderTest, V4RejectsRelativeLocation) { + auto metadata = CreateBaseMetadata(); + metadata->format_version = 4; + auto builder = TableMetadataBuilder::BuildFrom(metadata.get()); + builder->SetLocation("relative/table"); + EXPECT_THAT(builder->Build(), HasErrorMessage("location must be absolute")); +} + +TEST(TableMetadataBuilderTest, V4RequiresLocationUntilSupported) { + auto metadata = CreateBaseMetadata(); + metadata->format_version = 4; + metadata->location.clear(); + auto builder = TableMetadataBuilder::BuildFrom(metadata.get()); + EXPECT_THAT(builder->Build(), IsError(ErrorKind::kNotSupported)); +} + // Test AddSortOrder TEST(TableMetadataBuilderTest, AddSortOrderBasic) { auto base = CreateBaseMetadata(); @@ -1402,8 +1715,10 @@ TEST(TableMetadataBuilderTest, RemoveSnapshotRef) { auto builder = TableMetadataBuilder::BuildFrom(base.get()); // Add multiple snapshots - builder->AddSnapshot(std::make_shared(Snapshot{.snapshot_id = 1})); - builder->AddSnapshot(std::make_shared(Snapshot{.snapshot_id = 2})); + builder->AddSnapshot(std::make_shared( + Snapshot{.snapshot_id = 1, .manifest_list = "s3://bucket/manifest-list-1.avro"})); + builder->AddSnapshot(std::make_shared( + Snapshot{.snapshot_id = 2, .manifest_list = "s3://bucket/manifest-list-2.avro"})); // Add multiple refs ICEBERG_UNWRAP_OR_FAIL(auto ref1, SnapshotRef::MakeBranch(1)); @@ -1426,7 +1741,8 @@ TEST(TableMetadataBuilderTest, SetRefRejectsTagForMainBranch) { auto base = CreateBaseMetadata(); auto builder = TableMetadataBuilder::BuildFrom(base.get()); - builder->AddSnapshot(std::make_shared(Snapshot{.snapshot_id = 1})); + builder->AddSnapshot(std::make_shared( + Snapshot{.snapshot_id = 1, .manifest_list = "s3://bucket/manifest-list-1.avro"})); ICEBERG_UNWRAP_OR_FAIL(auto main_tag, SnapshotRef::MakeTag(1)); builder->SetRef(std::string(SnapshotRef::kMainBranch), std::move(main_tag)); @@ -1442,7 +1758,10 @@ TEST(TableMetadataBuilderTest, SetMainRefToAddedSnapshotUsesSnapshotTimestampFor auto snapshot_time = TimePointMsFromUnixMs(123456789); builder->AddSnapshot(std::make_shared( - Snapshot{.snapshot_id = 1, .sequence_number = 1, .timestamp_ms = snapshot_time})); + Snapshot{.snapshot_id = 1, + .sequence_number = 1, + .timestamp_ms = snapshot_time, + .manifest_list = "s3://bucket/manifest-list-1.avro"})); ICEBERG_UNWRAP_OR_FAIL(auto main_branch, SnapshotRef::MakeBranch(1)); builder->SetRef(std::string(SnapshotRef::kMainBranch), std::move(main_branch)); @@ -1460,8 +1779,10 @@ TEST(TableMetadataBuilderTest, RemoveSnapshot) { auto builder = TableMetadataBuilder::BuildFrom(base.get()); // Add multiple snapshots - builder->AddSnapshot(std::make_shared(Snapshot{.snapshot_id = 1})); - builder->AddSnapshot(std::make_shared(Snapshot{.snapshot_id = 2})); + builder->AddSnapshot(std::make_shared( + Snapshot{.snapshot_id = 1, .manifest_list = "s3://bucket/manifest-list-1.avro"})); + builder->AddSnapshot(std::make_shared( + Snapshot{.snapshot_id = 2, .manifest_list = "s3://bucket/manifest-list-2.avro"})); ICEBERG_UNWRAP_OR_FAIL(auto metadata, builder->Build()); ASSERT_EQ(metadata->snapshots.size(), 2); @@ -1480,8 +1801,10 @@ TEST(TableMetadataBuilderTest, RemoveSnapshotNotExist) { auto builder = TableMetadataBuilder::BuildFrom(base.get()); // Add multiple snapshots - builder->AddSnapshot(std::make_shared(Snapshot{.snapshot_id = 1})); - builder->AddSnapshot(std::make_shared(Snapshot{.snapshot_id = 2})); + builder->AddSnapshot(std::make_shared( + Snapshot{.snapshot_id = 1, .manifest_list = "s3://bucket/manifest-list-1.avro"})); + builder->AddSnapshot(std::make_shared( + Snapshot{.snapshot_id = 2, .manifest_list = "s3://bucket/manifest-list-2.avro"})); ICEBERG_UNWRAP_OR_FAIL(auto metadata, builder->Build()); ASSERT_EQ(metadata->snapshots.size(), 2); diff --git a/src/iceberg/test/update_schema_test.cc b/src/iceberg/test/update_schema_test.cc index 4057c52c80..474699135d 100644 --- a/src/iceberg/test/update_schema_test.cc +++ b/src/iceberg/test/update_schema_test.cc @@ -159,7 +159,7 @@ class UpdateSchemaDefaultValueTest : public UpdateSchemaTest { ICEBERG_UNWRAP_OR_FAIL(auto metadata, ReadTableMetadataFromResource("TableMetadataV2Valid.json")); - metadata->format_version = TableMetadata::kSupportedTableFormatVersion; + metadata->format_version = TableMetadata::kMinFormatVersionDefaultValues; metadata->next_row_id = TableMetadata::kInitialRowId; RegisterTable(std::move(metadata)); } diff --git a/src/iceberg/update/expire_snapshots.cc b/src/iceberg/update/expire_snapshots.cc index fd14308e88..420137cadc 100644 --- a/src/iceberg/update/expire_snapshots.cc +++ b/src/iceberg/update/expire_snapshots.cc @@ -966,7 +966,19 @@ Result ExpireSnapshots::Apply() { } }); + if (cleanup_level_ != CleanupLevel::kNone && !result.snapshot_ids_to_remove.empty() && + base.HasRootManifest()) { + return NotSupported( + "Snapshot expiration file cleanup with root manifests " + "is not supported yet; use CleanupLevel::kNone"); + } + if (clean_expired_metadata_) { + if (base.HasRootManifest()) { + return NotSupported( + "Cleaning expired schemas and partition specs with root manifests " + "is not supported yet; disable CleanExpiredMetadata to expire snapshots"); + } ICEBERG_ASSIGN_OR_RAISE( auto reachable_ids, ParallelCollect( @@ -1026,6 +1038,17 @@ Status ExpireSnapshots::Finalize(const TableMetadata& metadata_after_expiration) const TableMetadata& metadata_before_expiration = *apply_result->metadata_before_expiration; + // Later transaction updates or the catalog's committed result may introduce + // root manifests after Apply(). Never treat untraversable roots as empty. + // The commit has succeeded, so retain files and signal the skipped cleanup. + if (metadata_before_expiration.HasRootManifest() || + metadata_after_expiration.HasRootManifest()) { + ICEBERG_LOG_WARN( + "Skipped snapshot expiration file cleanup: root manifests prevent " + "reachability checks; expired snapshot files were retained"); + return {}; + } + // Pick incremental cleanup when the expiration is a simple linear-ancestry walk: // no explicit snapshot IDs, no removed snapshots outside main ancestry, and no // retained snapshots outside main ancestry.