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
10 changes: 10 additions & 0 deletions src/iceberg/catalog/rest/rest_catalog.cc
Original file line number Diff line number Diff line change
Expand Up @@ -856,6 +856,16 @@ Result<CommitTableResponse> RestCatalog::UpdateTableInternal(
const std::vector<std::unique_ptr<TableUpdate>>& 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};
Expand Down
25 changes: 16 additions & 9 deletions src/iceberg/inspect/snapshots_table.cc
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ class SnapshotsScan final : public MetadataScan {
const std::shared_ptr<MetadataScanTask> task_;
};

constexpr std::array<internal::MetadataTableColumn<Snapshot>, 6> kSnapshotColumns = {
constexpr std::array<internal::MetadataTableColumn<Snapshot>, 7> kSnapshotColumns = {
{{.field_id = 1,
.append =
[](ArrowArray* column, const Snapshot& row) {
Expand All @@ -83,13 +83,19 @@ constexpr std::array<internal::MetadataTableColumn<Snapshot>, 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
Expand All @@ -112,7 +118,8 @@ const std::shared_ptr<Schema>& SnapshotsTable::CanonicalSchema() {
SchemaField::MakeOptional(
6, "summary",
std::make_shared<MapType>(SchemaField::MakeRequired(7, "key", string()),
SchemaField::MakeRequired(8, "value", string())))});
SchemaField::MakeRequired(8, "value", string()))),
SchemaField::MakeOptional(9, "root_manifest", string())});
return schema;
}

Expand Down
124 changes: 94 additions & 30 deletions src/iceberg/json_serde.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -1130,7 +1135,19 @@ Result<std::unique_ptr<Snapshot>> SnapshotFromJson(const nlohmann::json& json) {
ICEBERG_ASSIGN_OR_RAISE(auto unix_ms, GetJsonValue<int64_t>(json, kTimestampMs));
auto timestamp_ms = TimePointMsFromUnixMs(unix_ms);
ICEBERG_ASSIGN_OR_RAISE(auto manifest_list,
GetJsonValue<std::string>(json, kManifestList));
GetJsonValueOptional<std::string>(json, kManifestList));
ICEBERG_ASSIGN_OR_RAISE(auto root_manifest,
GetJsonValueOptional<std::string>(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<nlohmann::json::object_t>(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<int64_t>(json, kParentSnapshotId));
Expand All @@ -1148,46 +1165,50 @@ Result<std::unique_ptr<Snapshot>> 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<std::string>())) {
return JsonParseError("Invalid snapshot operation in snapshot summary");
}
summary[key] = value.get<std::string>();
}
// 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,
GetJsonValueOptional<int64_t>(json, kFirstRowId));
ICEBERG_ASSIGN_OR_RAISE(auto added_rows,
GetJsonValueOptional<int64_t>(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<int32_t>(json, kSchemaId));
ICEBERG_ASSIGN_OR_RAISE(auto key_id, GetJsonValueOptional<std::string>(json, kKeyId));

return std::make_unique<Snapshot>(
auto snapshot = std::make_unique<Snapshot>(
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) {
Expand Down Expand Up @@ -1345,10 +1366,14 @@ Result<EncryptedKey> EncryptedKeyFromJson(const nlohmann::json& json) {
}

Result<nlohmann::json> 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;
Expand All @@ -1372,6 +1397,7 @@ Result<nlohmann::json> 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));
Expand Down Expand Up @@ -1455,9 +1481,19 @@ Result<std::shared_ptr<Schema>> ParseSchemas(

ICEBERG_ASSIGN_OR_RAISE(current_schema_id,
GetJsonInteger<int32_t>(json, kCurrentSchemaId));
const auto parse_schema =
[format_version](
const nlohmann::json& schema_json) -> Result<std::unique_ptr<Schema>> {
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> schema,
SchemaFromJson(schema_json));
ICEBERG_ASSIGN_OR_RAISE(std::shared_ptr<Schema> schema, parse_schema(schema_json));
ICEBERG_RETURN_UNEXPECTED(schema->Validate(format_version));
if (schema->schema_id() == current_schema_id) {
current_schema = schema;
Expand Down Expand Up @@ -1604,8 +1640,33 @@ Result<std::unique_ptr<TableMetadata>> TableMetadataFromJson(const nlohmann::jso

ICEBERG_ASSIGN_OR_RAISE(table_metadata->table_uuid,
GetJsonValueOrDefault<std::string>(json, kTableUuid));
ICEBERG_ASSIGN_OR_RAISE(table_metadata->location,
GetJsonValue<std::string>(json, kLocation));
if (table_metadata->format_version >= TableMetadata::kMinFormatVersionConstraints) {
ICEBERG_ASSIGN_OR_RAISE(
auto constraints,
GetJsonValueOptional<nlohmann::json::array_t>(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<int32_t>(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<std::string>(json, kLocation));
} else {
ICEBERG_ASSIGN_OR_RAISE(table_metadata->location,
GetJsonValue<std::string>(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,
Expand Down Expand Up @@ -1684,6 +1745,9 @@ Result<std::unique_ptr<TableMetadata>> TableMetadataFromJson(const nlohmann::jso

ICEBERG_ASSIGN_OR_RAISE(table_metadata->snapshots,
FromJsonList<Snapshot>(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<StatisticsFile>(json, kStatistics, StatisticsFileFromJson));
Expand Down
37 changes: 36 additions & 1 deletion src/iceberg/snapshot.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -165,6 +166,36 @@ Result<std::optional<int64_t>> Snapshot::FirstRowId() const { return first_row_i

Result<std::optional<int64_t>> 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;
Expand All @@ -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<std::unique_ptr<Snapshot>> Snapshot::Make(
Expand Down Expand Up @@ -205,6 +237,9 @@ Result<std::unique_ptr<Snapshot>> Snapshot::Make(

Result<SnapshotReader::ManifestsCache> SnapshotReader::InitManifestsCache(
const Snapshot* snapshot, std::shared_ptr<FileIO> 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");
}
Expand Down
13 changes: 13 additions & 0 deletions src/iceberg/snapshot.h
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,19 @@ struct ICEBERG_EXPORT Snapshot {
/// encrypted key metadata of the manifest list. Set only for encrypted tables.
std::optional<std::string> 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<std::string> 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<std::unique_ptr<Snapshot>> Make(
int64_t sequence_number, int64_t snapshot_id,
Expand Down
Loading