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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/iceberg/json_serde.cc
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ constexpr std::string_view kSortOrders = "sort-orders";
constexpr std::string_view kDefaultSortOrderId = "default-sort-order-id";
constexpr std::string_view kRefs = "refs";
constexpr std::string_view kStatistics = "statistics";
constexpr std::string_view kStatsFields = "stats-fields";
constexpr std::string_view kPartitionStatistics = "partition-statistics";
constexpr std::string_view kNextRowId = "next-row-id";
constexpr std::string_view kEncryptionKeys = "encryption-keys";
Expand Down Expand Up @@ -1345,6 +1346,7 @@ Result<EncryptedKey> EncryptedKeyFromJson(const nlohmann::json& json) {
}

Result<nlohmann::json> ToJson(const TableMetadata& table_metadata) {
ICEBERG_RETURN_UNEXPECTED(table_metadata.ValidateStatsFieldsForWrite());
nlohmann::json json;

json[kFormatVersion] = table_metadata.format_version;
Expand Down Expand Up @@ -1693,6 +1695,12 @@ Result<std::unique_ptr<TableMetadata>> TableMetadataFromJson(const nlohmann::jso
ICEBERG_ASSIGN_OR_RAISE(
table_metadata->encryption_keys,
FromJsonList<EncryptedKey>(json, kEncryptionKeys, EncryptedKeyFromJson));
if (table_metadata->format_version >= TableMetadata::kMinFormatVersionStatsFields) {
ICEBERG_ASSIGN_OR_RAISE(
auto stats_fields,
GetJsonValueOptional<nlohmann::json::array_t>(json, kStatsFields));
table_metadata->has_stats_fields = stats_fields.has_value() && !stats_fields->empty();
}
ICEBERG_ASSIGN_OR_RAISE(
table_metadata->snapshot_log,
FromJsonList<SnapshotLogEntry>(json, kSnapshotLog, SnapshotLogEntryFromJson));
Expand Down
13 changes: 12 additions & 1 deletion src/iceberg/table_metadata.cc
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,14 @@ int64_t TableMetadata::NextSequenceNumber() const {
return format_version > 1 ? last_sequence_number + 1 : kInitialSequenceNumber;
}

Status TableMetadata::ValidateStatsFieldsForWrite() const {
if (has_stats_fields) {
return NotSupported(
"Writing metadata with nonempty stats-fields is not supported yet");
}
return {};
}

namespace {

template <typename T>
Expand Down Expand Up @@ -381,7 +389,9 @@ bool operator==(const TableMetadata& lhs, const TableMetadata& rhs) {
SnapshotRefEquals(lhs.refs, rhs.refs) &&
SharedPtrVectorEquals(lhs.statistics, rhs.statistics) &&
SharedPtrVectorEquals(lhs.partition_statistics, rhs.partition_statistics) &&
lhs.next_row_id == rhs.next_row_id && lhs.encryption_keys == rhs.encryption_keys;
lhs.next_row_id == rhs.next_row_id &&
lhs.encryption_keys == rhs.encryption_keys &&
lhs.has_stats_fields == rhs.has_stats_fields;
}

// TableMetadataCache implementation
Expand Down Expand Up @@ -1401,6 +1411,7 @@ Result<std::unique_ptr<TableMetadata>> TableMetadataBuilder::Impl::Build() {
// 1. Validate the format version.
ICEBERG_PRECHECK(TableMetadata::IsSupportedFormatVersion(metadata_.format_version),
"Unsupported table format version: {}", metadata_.format_version);
ICEBERG_RETURN_UNEXPECTED(metadata_.ValidateStatsFieldsForWrite());

// 2. Update last_updated_ms if there are changes
if (metadata_.last_updated_ms == kInvalidLastUpdatedMs) {
Expand Down
7 changes: 7 additions & 0 deletions src/iceberg/table_metadata.h
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ struct ICEBERG_EXPORT MetadataLogEntry {
struct ICEBERG_EXPORT TableMetadata {
static constexpr int8_t kDefaultTableFormatVersion = 2;
static constexpr int8_t kSupportedTableFormatVersion = 3;
static constexpr int8_t kMinFormatVersionStatsFields = 3;
static constexpr int8_t kMinFormatVersionRowLineage = 3;
static constexpr int8_t kMinFormatVersionDefaultValues = 3;
static constexpr int64_t kInitialSequenceNumber = 0;
Expand Down Expand Up @@ -136,6 +137,12 @@ struct ICEBERG_EXPORT TableMetadata {
int64_t next_row_id;
/// A list of encrypted table key entries
std::vector<EncryptedKey> encryption_keys;
/// Whether stats-only field definitions were loaded. They are not retained,
/// so metadata writes must be rejected when this is true.
bool has_stats_fields = false;

/// \brief Reject writes that would discard stats-only field definitions.
Status ValidateStatsFieldsForWrite() const;

/// \brief Create table metadata from user-supplied properties.
/// \note The reserved format-version property selects the table format version,
Expand Down
42 changes: 42 additions & 0 deletions src/iceberg/test/metadata_serde_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,48 @@ TEST(MetadataSerdeTest, DeserializeUnsupportedVersion) {
"Cannot read unsupported version");
}

TEST(MetadataSerdeTest, StatsFieldsPreventMetadataWrites) {
ICEBERG_UNWRAP_OR_FAIL(
auto metadata, ReadTableMetadataFromResource("TableMetadataV3ValidMinimal.json"));
ICEBERG_UNWRAP_OR_FAIL(auto json, ToJson(*metadata));
json["last-column-id"] = 4;
for (const auto* type : {"partition-value", "future-value"}) {
SCOPED_TRACE(type);
json["stats-fields"] = nlohmann::json::array(
{{{"field-id", 4}, {"type", type}, {"partition-field-id", 1000}}});
ICEBERG_UNWRAP_OR_FAIL(auto parsed, TableMetadataFromJson(json));
EXPECT_THAT(ToJson(*parsed), IsError(ErrorKind::kNotSupported));
EXPECT_THAT(ToJson(*parsed), HasErrorMessage("stats-fields"));
auto builder = TableMetadataBuilder::BuildFrom(parsed.get());
EXPECT_THAT(builder->Build(), IsError(ErrorKind::kNotSupported));
}
}

TEST(MetadataSerdeTest, EmptyStatsFieldsAllowMetadataWrites) {
ICEBERG_UNWRAP_OR_FAIL(
auto metadata, ReadTableMetadataFromResource("TableMetadataV3ValidMinimal.json"));
ICEBERG_UNWRAP_OR_FAIL(auto json, ToJson(*metadata));
for (const auto& value : {nlohmann::json(nullptr), nlohmann::json::array()}) {
SCOPED_TRACE(value.dump());
json["stats-fields"] = value;
ICEBERG_UNWRAP_OR_FAIL(auto parsed, TableMetadataFromJson(json));
EXPECT_THAT(ToJson(*parsed), IsOk());
EXPECT_THAT(TableMetadataBuilder::BuildFrom(parsed.get())->Build(), IsOk());
}
}

TEST(MetadataSerdeTest, StatsFieldsRequireAnArray) {
ICEBERG_UNWRAP_OR_FAIL(
auto metadata, ReadTableMetadataFromResource("TableMetadataV3ValidMinimal.json"));
ICEBERG_UNWRAP_OR_FAIL(auto json, ToJson(*metadata));
for (const auto& value : {nlohmann::json::object(), nlohmann::json("fields"),
nlohmann::json(true), nlohmann::json(1)}) {
SCOPED_TRACE(value.dump());
json["stats-fields"] = value;
EXPECT_THAT(TableMetadataFromJson(json), IsError(ErrorKind::kJsonParseError));
}
}

TEST(MetadataSerdeTest, RejectsNarrowedFormatVersions) {
for (const auto* resource : {"TableMetadataV1Valid.json", "TableMetadataV2Valid.json",
"TableMetadataV3ValidMinimal.json"}) {
Expand Down
51 changes: 51 additions & 0 deletions src/iceberg/test/sql_catalog_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@
#include <unordered_map>
#include <vector>

#include <arrow/result.h>
#include <arrow/util/uri.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <nlohmann/json.hpp>
Expand All @@ -39,14 +41,18 @@
#include "iceberg/catalog/sql/catalog_store.h"
#include "iceberg/catalog/sql/config.h"
#include "iceberg/catalog/sql/connection_uri_internal.h"
#include "iceberg/partition_field.h"
#include "iceberg/partition_spec.h"
#include "iceberg/schema.h"
#include "iceberg/sort_order.h"
#include "iceberg/table.h"
#include "iceberg/table_identifier.h"
#include "iceberg/table_metadata.h"
#include "iceberg/table_requirement.h"
#include "iceberg/table_update.h"
#include "iceberg/test/matchers.h"
#include "iceberg/transaction.h"
#include "iceberg/transform.h"
#include "iceberg/type.h"
#include "iceberg/update/update_properties.h"

Expand Down Expand Up @@ -297,6 +303,51 @@ TEST_F(SqlCatalogTest, TableLifecycle) {
EXPECT_THAT(catalog_->DropTable(renamed, false), IsError(ErrorKind::kNoSuchTable));
}

TEST_F(SqlCatalogTest, PropertyUpdatePreservesStatsDefinitionsByRejectingWrites) {
Namespace ns{{"db"}};
ASSERT_THAT(catalog_->CreateNamespace(ns, {}), IsOk());
for (int version = TableMetadata::kMinFormatVersionStatsFields;
version <= TableMetadata::kSupportedTableFormatVersion; ++version) {
SCOPED_TRACE(version);
TableIdentifier ident{.ns = ns, .name = "stats_" + std::to_string(version)};
auto location = ::arrow::util::UriFromAbsolutePath(MakeTableLocation(ident.name));
ASSERT_TRUE(location.ok()) << location.status().ToString();
ICEBERG_UNWRAP_OR_FAIL(
std::shared_ptr<PartitionSpec> spec,
PartitionSpec::Make(
0, {PartitionField(1, 1000, "x_bucket", Transform::Bucket(16))}));
ICEBERG_UNWRAP_OR_FAIL(
auto created,
catalog_->CreateTable(
ident, MakeSchema(), spec, SortOrder::Unsorted(), *location,
{{"format-version", std::to_string(version)}, {"owner", "alice"}}));
const auto metadata_location = std::string(created->metadata_file_location());
ICEBERG_UNWRAP_OR_FAIL(auto content,
file_io_->ReadFile(metadata_location, std::nullopt));
auto json = nlohmann::json::parse(content);
json["last-column-id"] = 2;
json["stats-fields"] = nlohmann::json::array(
{{{"field-id", 2}, {"type", "partition-value"}, {"partition-field-id", 1000}}});
const auto original = json.dump();
ASSERT_THAT(file_io_->WriteFile(metadata_location, original), IsOk());
// Read succeeds, but SQL must not rewrite definitions it cannot preserve.
EXPECT_THAT(catalog_->LoadTable(ident), IsOk());
std::vector<std::unique_ptr<TableUpdate>> updates;
updates.push_back(std::make_unique<table::SetProperties>(
std::unordered_map<std::string, std::string>{{"owner", "bob"}}));
auto result = catalog_->UpdateTable(ident, {}, updates);
EXPECT_THAT(result, IsError(ErrorKind::kNotSupported));
EXPECT_THAT(result, HasErrorMessage("stats-fields"));
ICEBERG_UNWRAP_OR_FAIL(auto loaded, catalog_->LoadTable(ident));
EXPECT_EQ(loaded->metadata_file_location(), metadata_location);
EXPECT_THAT(loaded->properties().configs(),
::testing::Contains(::testing::Pair("owner", "alice")));
ICEBERG_UNWRAP_OR_FAIL(auto retained,
file_io_->ReadFile(metadata_location, std::nullopt));
EXPECT_EQ(retained, original);
}
}

class SqlCatalogFormatVersionTest
: public SqlCatalogTest,
public ::testing::WithParamInterface<std::tuple<bool, int>> {};
Expand Down
Loading