Repository navigation
fix(metadata): validate snapshot integers and allocation bounds #1169
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
8eb70fa
26d5c14
53a4253
37f6c1f
350cce0
ce2b35b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -1128,16 +1128,16 @@ Result<std::unique_ptr<SnapshotRef>> SnapshotRefFromJson(const nlohmann::json& j | |
| } | ||
|
|
||
| Result<std::unique_ptr<Snapshot>> SnapshotFromJson(const nlohmann::json& json) { | ||
| ICEBERG_ASSIGN_OR_RAISE(auto snapshot_id, GetJsonValue<int64_t>(json, kSnapshotId)); | ||
| ICEBERG_ASSIGN_OR_RAISE(auto snapshot_id, GetJsonInteger<int64_t>(json, kSnapshotId)); | ||
| ICEBERG_ASSIGN_OR_RAISE(auto sequence_number, | ||
| GetJsonValueOptional<int64_t>(json, kSequenceNumber)); | ||
| ICEBERG_ASSIGN_OR_RAISE(auto unix_ms, GetJsonValue<int64_t>(json, kTimestampMs)); | ||
| GetJsonIntegerOptional<int64_t>(json, kSequenceNumber)); | ||
| ICEBERG_ASSIGN_OR_RAISE(auto unix_ms, GetJsonInteger<int64_t>(json, kTimestampMs)); | ||
| auto timestamp_ms = TimePointMsFromUnixMs(unix_ms); | ||
| ICEBERG_ASSIGN_OR_RAISE(auto manifest_list, | ||
| GetJsonValue<std::string>(json, kManifestList)); | ||
|
|
||
| ICEBERG_ASSIGN_OR_RAISE(auto parent_snapshot_id, | ||
| GetJsonValueOptional<int64_t>(json, kParentSnapshotId)); | ||
| GetJsonIntegerOptional<int64_t>(json, kParentSnapshotId)); | ||
|
|
||
| ICEBERG_ASSIGN_OR_RAISE(auto summary_json, | ||
| GetJsonValueOptional<nlohmann::json>(json, kSummary)); | ||
|
|
@@ -1165,9 +1165,9 @@ Result<std::unique_ptr<Snapshot>> SnapshotFromJson(const nlohmann::json& json) { | |
| } | ||
|
|
||
| ICEBERG_ASSIGN_OR_RAISE(auto first_row_id, | ||
| GetJsonValueOptional<int64_t>(json, kFirstRowId)); | ||
| GetJsonIntegerOptional<int64_t>(json, kFirstRowId)); | ||
| ICEBERG_ASSIGN_OR_RAISE(auto added_rows, | ||
| GetJsonValueOptional<int64_t>(json, kAddedRows)); | ||
| GetJsonIntegerOptional<int64_t>(json, kAddedRows)); | ||
|
|
||
| if (first_row_id.has_value() && first_row_id.value() < 0) { | ||
| return JsonParseError("Invalid first-row-id (cannot be negative): {}", | ||
|
|
@@ -1184,7 +1184,8 @@ Result<std::unique_ptr<Snapshot>> SnapshotFromJson(const nlohmann::json& json) { | |
| added_rows = std::nullopt; | ||
| } | ||
|
|
||
| ICEBERG_ASSIGN_OR_RAISE(auto schema_id, GetJsonValueOptional<int32_t>(json, kSchemaId)); | ||
| ICEBERG_ASSIGN_OR_RAISE(auto schema_id, | ||
| GetJsonIntegerOptional<int32_t>(json, kSchemaId)); | ||
| ICEBERG_ASSIGN_OR_RAISE(auto key_id, GetJsonValueOptional<std::string>(json, kKeyId)); | ||
|
|
||
| return std::make_unique<Snapshot>( | ||
|
|
@@ -1349,6 +1350,9 @@ Result<EncryptedKey> EncryptedKeyFromJson(const nlohmann::json& json) { | |
| } | ||
|
|
||
| Result<nlohmann::json> ToJson(const TableMetadata& table_metadata) { | ||
| if (auto status = table_metadata.Validate(); !status) { | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do we actually need to call this inside
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'd keep it to enforce checks at writer side. |
||
| return InvalidArgument("Invalid table metadata: {}", status.error().message); | ||
| } | ||
| nlohmann::json json; | ||
|
|
||
| json[kFormatVersion] = table_metadata.format_version; | ||
|
|
@@ -1567,7 +1571,7 @@ Status ParseSortOrders(const nlohmann::json& json, int8_t format_version, | |
| std::vector<std::shared_ptr<SortOrder>>& sort_orders) { | ||
| if (json.contains(kSortOrders)) { | ||
| ICEBERG_ASSIGN_OR_RAISE(default_sort_order_id, | ||
| GetJsonValue<int32_t>(json, kDefaultSortOrderId)); | ||
| GetJsonInteger<int32_t>(json, kDefaultSortOrderId)); | ||
| ICEBERG_ASSIGN_OR_RAISE(auto sort_order_array, | ||
| GetJsonValue<nlohmann::json>(json, kSortOrders)); | ||
| for (const auto& sort_order_json : sort_order_array) { | ||
|
|
@@ -1612,12 +1616,12 @@ Result<std::unique_ptr<TableMetadata>> TableMetadataFromJson(const nlohmann::jso | |
|
|
||
| if (table_metadata->format_version > 1) { | ||
| ICEBERG_ASSIGN_OR_RAISE(table_metadata->last_sequence_number, | ||
| GetJsonValue<int64_t>(json, kLastSequenceNumber)); | ||
| GetJsonInteger<int64_t>(json, kLastSequenceNumber)); | ||
| } else { | ||
| table_metadata->last_sequence_number = TableMetadata::kInitialSequenceNumber; | ||
| } | ||
| ICEBERG_ASSIGN_OR_RAISE(table_metadata->last_column_id, | ||
| GetJsonValue<int32_t>(json, kLastColumnId)); | ||
| GetJsonInteger<int32_t>(json, kLastColumnId)); | ||
|
|
||
| ICEBERG_ASSIGN_OR_RAISE( | ||
| auto current_schema, | ||
|
|
@@ -1630,7 +1634,7 @@ Result<std::unique_ptr<TableMetadata>> TableMetadataFromJson(const nlohmann::jso | |
|
|
||
| if (json.contains(kLastPartitionId)) { | ||
| ICEBERG_ASSIGN_OR_RAISE(table_metadata->last_partition_id, | ||
| GetJsonValue<int32_t>(json, kLastPartitionId)); | ||
| GetJsonInteger<int32_t>(json, kLastPartitionId)); | ||
| } else { | ||
| if (table_metadata->format_version > 1) { | ||
| return JsonParseError("{} must exist in format v{}", kLastPartitionId, | ||
|
|
@@ -1660,17 +1664,17 @@ Result<std::unique_ptr<TableMetadata>> TableMetadataFromJson(const nlohmann::jso | |
| // This field is optional, but internally we set this to -1 when not set | ||
| ICEBERG_ASSIGN_OR_RAISE( | ||
| table_metadata->current_snapshot_id, | ||
| GetJsonValueOrDefault<int64_t>(json, kCurrentSnapshotId, kInvalidSnapshotId)); | ||
| GetJsonIntegerOrDefault(json, kCurrentSnapshotId, kInvalidSnapshotId)); | ||
|
|
||
| if (table_metadata->format_version >= 3) { | ||
| ICEBERG_ASSIGN_OR_RAISE(table_metadata->next_row_id, | ||
| GetJsonValue<int64_t>(json, kNextRowId)); | ||
| GetJsonInteger<int64_t>(json, kNextRowId)); | ||
| } else { | ||
| table_metadata->next_row_id = TableMetadata::kInitialRowId; | ||
| } | ||
|
|
||
| ICEBERG_ASSIGN_OR_RAISE(auto last_updated_ms, | ||
| GetJsonValue<int64_t>(json, kLastUpdatedMs)); | ||
| GetJsonInteger<int64_t>(json, kLastUpdatedMs)); | ||
| table_metadata->last_updated_ms = | ||
| TimePointMs{std::chrono::milliseconds(last_updated_ms)}; | ||
|
|
||
|
|
@@ -1704,6 +1708,9 @@ Result<std::unique_ptr<TableMetadata>> TableMetadataFromJson(const nlohmann::jso | |
| table_metadata->metadata_log, | ||
| FromJsonList<MetadataLogEntry>(json, kMetadataLog, MetadataLogEntryFromJson)); | ||
|
|
||
| if (auto status = table_metadata->Validate(); !status) { | ||
| return JsonParseError("Invalid table metadata: {}", status.error().message); | ||
| } | ||
| return table_metadata; | ||
| } | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -321,6 +321,45 @@ Result<std::shared_ptr<Snapshot>> TableMetadata::SnapshotById(int64_t snapshot_i | |
| return *iter; | ||
| } | ||
|
|
||
| Status TableMetadata::Validate() const { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There are many more invariants check we can be added here. We can do it in a separate follow up. Can you please file an issue?
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. For example - current-snapshot-id must exist, main branch must match current-snapshot-id, etc. but can be done in a follow up.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Opened #1200 to track. |
||
| if (format_version > 1) { | ||
| ICEBERG_CHECK(last_sequence_number >= kInitialSequenceNumber, | ||
| "last-sequence-number cannot be negative: {}", last_sequence_number); | ||
| } | ||
| if (format_version >= kMinFormatVersionRowLineage) { | ||
| ICEBERG_CHECK(next_row_id >= kInitialRowId, "next-row-id cannot be negative: {}", | ||
| next_row_id); | ||
| } | ||
|
manuzhang marked this conversation as resolved.
Resolved
|
||
| for (const auto& snapshot : snapshots) { | ||
| ICEBERG_CHECK(snapshot != nullptr, "Cannot validate a null snapshot"); | ||
| if (format_version > 1) { | ||
| ICEBERG_CHECK(snapshot->sequence_number >= kInitialSequenceNumber, | ||
| "Snapshot {} sequence-number cannot be negative: {}", | ||
| snapshot->snapshot_id, snapshot->sequence_number); | ||
| 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); | ||
| } | ||
| if (format_version >= kMinFormatVersionRowLineage && | ||
| snapshot->first_row_id.has_value()) { | ||
| ICEBERG_CHECK(snapshot->added_rows.has_value(), | ||
| "Snapshot {} has first-row-id but no added-rows", | ||
| snapshot->snapshot_id); | ||
| const auto first_row_id = snapshot->first_row_id.value(); | ||
| ICEBERG_CHECK(first_row_id >= 0 && snapshot->added_rows.value() >= 0, | ||
| "Snapshot {} row lineage fields must be non-negative", | ||
| snapshot->snapshot_id); | ||
| // added-rows is an upper bound. Writers may advance next-row-id using the | ||
| // number of IDs actually assigned. | ||
| ICEBERG_CHECK(first_row_id <= next_row_id, | ||
| "next-row-id {} is below retained snapshot {} first-row-id {}", | ||
| next_row_id, snapshot->snapshot_id, first_row_id); | ||
| } | ||
| } | ||
| return {}; | ||
| } | ||
|
|
||
| int64_t TableMetadata::NextSequenceNumber() const { | ||
| return format_version > 1 ? last_sequence_number + 1 : kInitialSequenceNumber; | ||
| } | ||
|
|
@@ -1398,9 +1437,10 @@ Result<std::vector<SnapshotLogEntry>> TableMetadataBuilder::Impl::UpdateSnapshot | |
| } | ||
|
|
||
| Result<std::unique_ptr<TableMetadata>> TableMetadataBuilder::Impl::Build() { | ||
| // 1. Validate the format version. | ||
| // 1. Validate the format version and metadata consistency. | ||
| ICEBERG_PRECHECK(TableMetadata::IsSupportedFormatVersion(metadata_.format_version), | ||
| "Unsupported table format version: {}", metadata_.format_version); | ||
| ICEBERG_RETURN_UNEXPECTED(metadata_.Validate()); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. to my understanding,
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks for raising the issue. I've opened #1199 to track and would like to fix it after a more thorough discussion.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. yes sounds good |
||
|
|
||
| // 2. Update last_updated_ms if there are changes | ||
| if (metadata_.last_updated_ms == kInvalidLastUpdatedMs) { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -499,6 +499,155 @@ TEST(MetadataSerdeTest, V3DefaultValuesRoundTrip) { | |
| EXPECT_EQ(*reparsed, *metadata); | ||
| } | ||
|
|
||
| TEST(MetadataSerdeTest, TableSequenceAndRowIdBoundsCoverRetainedSnapshots) { | ||
| for (const auto* resource : | ||
| {"TableMetadataV2ValidMinimal.json", "TableMetadataV3ValidMinimal.json"}) { | ||
| SCOPED_TRACE(resource); | ||
| ICEBERG_UNWRAP_OR_FAIL(auto empty, ReadTableMetadataFromResource(resource)); | ||
| ICEBERG_UNWRAP_OR_FAIL(auto json, ToJson(*empty)); | ||
| json["snapshots"] = nlohmann::json::parse(R"([{ | ||
| "snapshot-id": 1, "sequence-number": 1, "timestamp-ms": 1000, | ||
| "manifest-list": "metadata/manifest-list.avro", "summary": {"operation": "append"}, | ||
| "schema-id": 0, "first-row-id": 1, "added-rows": 10 | ||
| }])"); | ||
| json["last-sequence-number"] = 1; | ||
| json["next-row-id"] = 11; | ||
| ICEBERG_UNWRAP_OR_FAIL(auto valid, TableMetadataFromJson(json)); | ||
| for (const auto* field : {"last-sequence-number", "next-row-id"}) { | ||
| const bool is_next_row_id = std::string_view(field) == "next-row-id"; | ||
| if (is_next_row_id && empty->format_version < 3) { | ||
| continue; | ||
| } | ||
| SCOPED_TRACE(field); | ||
| auto invalid = json; | ||
| invalid[field] = 0; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. setting this to
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in new tests. |
||
| EXPECT_THAT(TableMetadataFromJson(invalid), IsError(ErrorKind::kJsonParseError)); | ||
| auto metadata = *valid; | ||
| if (is_next_row_id) { | ||
| metadata.next_row_id = 0; | ||
| } else { | ||
| metadata.last_sequence_number = 0; | ||
| } | ||
| EXPECT_THAT(ToJson(metadata), IsError(ErrorKind::kInvalidArgument)); | ||
| auto builder = TableMetadataBuilder::BuildFrom(&metadata); | ||
| EXPECT_THAT(builder->Build(), IsError(ErrorKind::kValidationFailed)); | ||
| } | ||
| json["last-sequence-number"] = 5; | ||
| json["next-row-id"] = 20; | ||
| ICEBERG_UNWRAP_OR_FAIL(auto higher, TableMetadataFromJson(json)); | ||
| EXPECT_THAT(ToJson(*higher), IsOk()); | ||
| EXPECT_THAT(TableMetadataBuilder::BuildFrom(higher.get())->Build(), IsOk()); | ||
|
|
||
| json["snapshots"][0]["sequence-number"] = -1; | ||
| auto parsed = TableMetadataFromJson(json); | ||
| EXPECT_THAT(parsed, IsError(ErrorKind::kJsonParseError)); | ||
| EXPECT_THAT(parsed, HasErrorMessage("Snapshot 1 sequence-number cannot be negative")); | ||
| higher->snapshots.front()->sequence_number = -1; | ||
| EXPECT_THAT(ToJson(*higher), IsError(ErrorKind::kInvalidArgument)); | ||
| EXPECT_THAT(TableMetadataBuilder::BuildFrom(higher.get())->Build(), | ||
| IsError(ErrorKind::kValidationFailed)); | ||
| } | ||
| } | ||
|
|
||
| TEST(MetadataSerdeTest, V3AllowsConservativeAddedRows) { | ||
| ICEBERG_UNWRAP_OR_FAIL( | ||
| auto metadata, ReadTableMetadataFromResource("TableMetadataV3ValidMinimal.json")); | ||
| ICEBERG_UNWRAP_OR_FAIL(auto json, ToJson(*metadata)); | ||
| json["snapshots"] = nlohmann::json::parse(R"([{ | ||
| "snapshot-id": 1, "sequence-number": 1, "timestamp-ms": 1000, | ||
| "manifest-list": "metadata/manifest-list.avro", "summary": {"operation": "append"}, | ||
| "schema-id": 0, "first-row-id": 100, "added-rows": 20 | ||
| }])"); | ||
| json["last-sequence-number"] = 1; | ||
| // The writer assigned ten row IDs starting at 100 and stored an upper bound of 20. | ||
| json["next-row-id"] = 110; | ||
| ICEBERG_UNWRAP_OR_FAIL(auto parsed, TableMetadataFromJson(json)); | ||
| ICEBERG_UNWRAP_OR_FAIL(auto built, | ||
| TableMetadataBuilder::BuildFrom(parsed.get())->Build()); | ||
| ICEBERG_UNWRAP_OR_FAIL(auto serialized, ToJson(*built)); | ||
| EXPECT_EQ(serialized["next-row-id"], 110); | ||
| EXPECT_EQ(serialized["snapshots"][0]["added-rows"], 20); | ||
| } | ||
|
|
||
| TEST(MetadataSerdeTest, V3BuildValidatesRetainedSnapshotRowLineage) { | ||
| ICEBERG_UNWRAP_OR_FAIL( | ||
| auto metadata, ReadTableMetadataFromResource("TableMetadataV3ValidMinimal.json")); | ||
| metadata->next_row_id = 100; | ||
| auto build = [&](int64_t first_row_id, std::optional<int64_t> added_rows) { | ||
| metadata->snapshots = {std::make_shared<Snapshot>(Snapshot{ | ||
| .snapshot_id = 1, | ||
| .sequence_number = metadata->last_sequence_number, | ||
| .manifest_list = "metadata/manifest-list.avro", | ||
| .first_row_id = first_row_id, | ||
| .added_rows = added_rows, | ||
| })}; | ||
| return TableMetadataBuilder::BuildFrom(metadata.get())->Build(); | ||
| }; | ||
| EXPECT_THAT(build(metadata->next_row_id, 0), IsOk()); | ||
| EXPECT_THAT(build(0, std::nullopt), IsError(ErrorKind::kValidationFailed)); | ||
| EXPECT_THAT(build(-1, 0), IsError(ErrorKind::kValidationFailed)); | ||
| EXPECT_THAT(build(0, -1), IsError(ErrorKind::kValidationFailed)); | ||
| } | ||
|
|
||
| TEST(MetadataSerdeTest, TableSequenceAndRowIdBoundsRejectInvalidJsonIntegers) { | ||
| for (const auto* resource : | ||
| {"TableMetadataV2ValidMinimal.json", "TableMetadataV3ValidMinimal.json"}) { | ||
| SCOPED_TRACE(resource); | ||
| ICEBERG_UNWRAP_OR_FAIL(auto metadata, ReadTableMetadataFromResource(resource)); | ||
| ASSERT_TRUE(metadata->snapshots.empty()); | ||
| ICEBERG_UNWRAP_OR_FAIL(auto valid_json, ToJson(*metadata)); | ||
| for (const auto* field : {"last-sequence-number", "next-row-id"}) { | ||
| if (std::string_view(field) == "next-row-id" && metadata->format_version < 3) { | ||
| continue; | ||
| } | ||
| SCOPED_TRACE(field); | ||
| for (const auto& invalid : | ||
| std::vector<nlohmann::json>{int64_t{-1}, 10.5, 10.0, -0.5, true, "10", | ||
| std::numeric_limits<uint64_t>::max(), | ||
| nlohmann::json::parse("-9223372036854775809")}) { | ||
| SCOPED_TRACE(invalid.dump()); | ||
| auto json = valid_json; | ||
| json[field] = invalid; | ||
| auto result = TableMetadataFromJson(json); | ||
| EXPECT_THAT(result, IsError(ErrorKind::kJsonParseError)); | ||
| EXPECT_THAT(result, HasErrorMessage(field)); | ||
| } | ||
| for (int64_t value : {int64_t{0}, std::numeric_limits<int64_t>::max()}) { | ||
| auto json = valid_json; | ||
| json[field] = value; | ||
| ICEBERG_UNWRAP_OR_FAIL(auto parsed, TableMetadataFromJson(json)); | ||
| EXPECT_EQ(std::string_view(field) == "next-row-id" ? parsed->next_row_id | ||
| : parsed->last_sequence_number, | ||
| value); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| TEST(MetadataSerdeTest, RejectsInvalidTableMetadataIntegers) { | ||
| ICEBERG_UNWRAP_OR_FAIL( | ||
| auto metadata, ReadTableMetadataFromResource("TableMetadataV2ValidMinimal.json")); | ||
| ICEBERG_UNWRAP_OR_FAIL(auto json, ToJson(*metadata)); | ||
| auto check_field = [&](const char* field, uint64_t overflow) { | ||
| SCOPED_TRACE(field); | ||
| for (const auto& value : std::vector<nlohmann::json>{0.5, true, overflow}) { | ||
| SCOPED_TRACE(value.dump()); | ||
| auto invalid = json; | ||
| invalid[field] = value; | ||
| auto result = TableMetadataFromJson(invalid); | ||
| EXPECT_THAT(result, IsError(ErrorKind::kJsonParseError)); | ||
| EXPECT_THAT(result, HasErrorMessage(field)); | ||
| } | ||
| }; | ||
| for (const auto* field : | ||
| {"last-column-id", "last-partition-id", "default-sort-order-id"}) { | ||
| check_field(field, uint64_t{1} << 31); | ||
| } | ||
| for (const auto* field : {"current-snapshot-id", "last-updated-ms"}) { | ||
| check_field(field, uint64_t{1} << 63); | ||
| } | ||
| } | ||
|
|
||
| TEST(MetadataSerdeTest, DeserializeUnsupportedVersion) { | ||
| ReadTableMetadataExpectError("TableMetadataUnsupportedVersion.json", | ||
| "Cannot read unsupported version"); | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
pls apply the similar fix to other integer fields - last-column-id, last-partition-id, default-sort-order-id, current-snapshot-id and last-updated-ms.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed now