Compare commits

...

1 Commits

Author SHA1 Message Date
GatewayJ c95022ce54 fix(table-catalog): retain a branch for published snapshot roots (#9766) 2026-12-03 13:53:24 +08:00
3 changed files with 505 additions and 3 deletions
@@ -4468,6 +4468,7 @@ fn apply_table_updates_at(
}
}
snapshot_roots.validate_publication(&metadata)?;
prune_intermediate_snapshot_log_entries(&mut metadata, &snapshot_roots.added)?;
if metadata.get("format-version").is_some() {
@@ -5785,6 +5786,11 @@ struct SnapshotCommitRoots {
by_snapshot: BTreeMap<i64, SnapshotHistory>,
by_branch: BTreeMap<String, i64>,
added: BTreeSet<i64>,
// Branch targets assigned in this commit. A parentless snapshot may be staged with no ref.
// Once a branch points at that new history, or a tag names it, the final metadata must still
// have a branch on the same history. Removing or retargeting the only branch would leave the
// root detached on a populated table.
published_branch_snapshots: BTreeSet<i64>,
}
impl SnapshotCommitRoots {
@@ -5858,6 +5864,65 @@ impl SnapshotCommitRoots {
if is_branch || current.is_some() {
self.by_branch.insert(name.to_owned(), id);
}
if is_branch {
self.published_branch_snapshots.insert(id);
}
Ok(())
}
fn added_history_root(&self, snapshot_id: i64) -> Option<i64> {
let root = self.by_snapshot.get(&snapshot_id)?.root?;
self.added.contains(&root).then_some(root)
}
fn validate_publication(&self, metadata: &serde_json::Value) -> S3Result<()> {
let retained = metadata
.get("snapshots")
.and_then(serde_json::Value::as_array)
.map(|snapshots| {
snapshots
.iter()
.filter_map(|snapshot| snapshot.get("snapshot-id").and_then(serde_json::Value::as_i64))
.collect::<BTreeSet<_>>()
})
.unwrap_or_default();
let history_retained = |root: i64| {
self.by_snapshot
.iter()
.any(|(id, history)| history.root == Some(root) && self.added.contains(id) && retained.contains(id))
};
let mut surviving_branch_roots = BTreeSet::new();
let mut required_roots = BTreeSet::new();
if let Some(refs) = metadata.get("refs").and_then(serde_json::Value::as_object) {
for reference in refs.values() {
let Some(snapshot_id) = reference.get("snapshot-id").and_then(serde_json::Value::as_i64) else {
continue;
};
let Some(root) = self.added_history_root(snapshot_id) else {
continue;
};
match reference.get("type").and_then(serde_json::Value::as_str) {
Some("branch") => {
surviving_branch_roots.insert(root);
}
Some("tag") => {
required_roots.insert(root);
}
_ => {}
}
}
}
for snapshot_id in &self.published_branch_snapshots {
let Some(root) = self.added_history_root(*snapshot_id) else {
continue;
};
if history_retained(root) {
required_roots.insert(root);
}
}
if required_roots.iter().any(|root| !surviving_branch_roots.contains(root)) {
return Err(s3_error!(InvalidRequest, "cannot publish a snapshot history without a surviving branch"));
}
Ok(())
}
}
@@ -2,6 +2,8 @@
mod catalog_migration_scope;
#[path = "tests/real_catalog_failures.rs"]
mod real_catalog_failures;
#[path = "tests/row_level_snapshot_commits.rs"]
mod row_level_snapshot_commits;
use super::*;
use crate::admin::operation::test_support::TestRequest;
@@ -11908,7 +11910,11 @@ fn manifest_rewrite_metadata_bytes(bytes: Vec<u8>, case: &str) -> Vec<u8> {
{"name": "key", "type": "int"}, {"name": "value", "type": if is_bound { "bytes" } else { "long" }}
]
}}]),
Value::Union(1, Box::new(Value::Array(entries))),
match case {
"null_metrics" => Value::Union(0, Box::new(Value::Null)),
"append_empty_metrics" => Value::Union(1, Box::new(Value::Array(Vec::new()))),
_ => Value::Union(1, Box::new(Value::Array(entries))),
},
));
}
}
@@ -12116,6 +12122,7 @@ async fn manifest_rewrite_commit_preserves_live_files() {
"equality_ids",
"custom_metadata",
"missing_metric",
"append_empty_metrics",
"reordered_metadata",
"optional_null",
"duplicate_file",
@@ -12158,7 +12165,11 @@ async fn manifest_rewrite_commit_preserves_live_files() {
let manifest = format!("{location}/metadata/manifest-{snapshot_id}-{index}.avro");
let bytes = manifest_rewrite_metadata_bytes(
test_manifest_avro_bytes(&[(file, *file_content, *status, *entry_snapshot, *entry_sequence)]),
"unchanged",
if case == "append_empty_metrics" && *file == &added && *status == 1 {
"null_metrics"
} else {
"unchanged"
},
);
manifests.push((manifest.clone(), bytes.len(), i32::from(*file_content != 0), *entry_sequence));
backend
@@ -12251,6 +12262,10 @@ async fn manifest_rewrite_commit_preserves_live_files() {
"omitted_file" | "inherited_manifest" | "inherited_partition_spec" => {
rewritten.pop();
}
"append_empty_metrics" => {
seed_test_manifest_data_files(&backend, "warehouse", &[(&extra, 0, 1, 12, 3)]).await;
rewritten.push((extra.as_str(), 0, 1, 12, Some(3), Some(3)));
}
"extra_file" => {
backend
.put_bytes("warehouse", &test_snapshot_object_key("warehouse", &extra), b"extra".to_vec())
@@ -12346,6 +12361,9 @@ async fn manifest_rewrite_commit_preserves_live_files() {
{"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 12, "type": "branch"}
]
});
if case == "append_empty_metrics" {
request_json["updates"][0]["snapshot"]["summary"]["operation"] = "append".into();
}
if case == "intermediate_duplicate" {
let final_list = format!("{location}/metadata/snap-13.avro");
backend
@@ -12421,6 +12439,7 @@ async fn manifest_rewrite_commit_preserves_live_files() {
| "inherited_manifest"
| "staged_retry"
| "reordered_metadata"
| "append_empty_metrics"
| "optional_null"
| "format_case"
) {
@@ -12430,7 +12449,9 @@ async fn manifest_rewrite_commit_preserves_live_files() {
let live = load_snapshot_live_files(&backend, "warehouse", &after, &response.metadata, Some(12))
.await
.unwrap();
assert_eq!(live.data_files.len() + live.delete_files.len(), 2);
let is_append = case == "append_empty_metrics";
assert_eq!(live.data_files.len() + live.delete_files.len(), 2 + usize::from(is_append));
assert_eq!(live.data_files.contains_key(&extra), is_append);
assert_eq!(live.data_files[&retained].sequence_number, Some(1));
let kind = if content == 0 {
crate::table_catalog::TableMetadataMaintenanceObjectKind::DataFile
@@ -12975,6 +12996,176 @@ async fn row_level_conflict_allows_add_only_overwrite_snapshot() {
assert_eq!(commit.metadata["last-sequence-number"], 2);
}
#[tokio::test]
async fn noop_overwrite_snapshot_expiration_retains_shared_manifests_and_live_data_files() {
let backend = TestTableCatalogObjectBackend::content_addressed();
let store = crate::table_catalog::ObjectTableCatalogStore::new(backend.clone());
let bucket = "warehouse";
let namespace = crate::table_catalog::Namespace::parse("analytics").expect("namespace should parse");
let created = create_standard_events_table(&store, &backend, &namespace).await;
let location = created.metadata["location"].as_str().expect("table location");
let data_file = format!("{location}/data/part-10.parquet");
let manifest_10 = format!("{location}/metadata/manifest-10.avro");
let snap_10 = format!("{location}/metadata/snap-10.avro");
let snap_11 = format!("{location}/metadata/snap-11.avro");
seed_test_manifest(&backend, bucket, &manifest_10, &[(&data_file, 0, 1, 10, 1)]).await;
seed_test_manifest_list(&backend, bucket, &snap_10, &[&manifest_10], 1, 10).await;
commit_table_response(
&store,
&trusted_table_commit_backend(&backend),
bucket,
&namespace,
"events",
serde_json::from_value(serde_json::json!({
"updates": [
{
"action": "add-snapshot",
"snapshot": {
"snapshot-id": 10,
"sequence-number": 1,
"timestamp-ms": 1000,
"manifest-list": snap_10,
"summary": {"operation": "append"}
}
},
{"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 10, "type": "branch"}
]
}))
.expect("append request should parse"),
)
.await
.expect("append should commit");
seed_test_manifest_list_entries(&backend, bucket, &snap_11, &[(&manifest_10, 1, 10)]).await;
commit_table_response(
&store,
&trusted_table_commit_backend(&backend),
bucket,
&namespace,
"events",
serde_json::from_value(serde_json::json!({
"requirements": [{"type": "assert-ref-snapshot-id", "ref": "main", "snapshot-id": 10}],
"updates": [
{
"action": "add-snapshot",
"snapshot": {
"snapshot-id": 11,
"parent-snapshot-id": 10,
"sequence-number": 2,
"timestamp-ms": 2000,
"manifest-list": snap_11,
"summary": {"operation": "overwrite"}
}
},
{"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 11, "type": "branch"}
]
}))
.expect("no-op overwrite request should parse"),
)
.await
.expect("no-op overwrite should commit");
let expiration = table_metadata_maintenance_response(
&store,
&backend,
bucket,
&namespace,
"events",
TableMetadataMaintenanceRequest {
retain_recent_metadata_files: 0,
delete: false,
snapshot_expiration: Some(crate::table_catalog::TableSnapshotExpirationConfig {
min_snapshots_to_keep: 1,
max_snapshot_age_ms: 1,
}),
commit_snapshot_expiration: true,
compaction: None,
commit_compaction: false,
},
)
.await
.expect("snapshot expiration after no-op overwrite should succeed");
assert_eq!(
expiration
.snapshot_expiration
.as_ref()
.expect("expiration report")
.expired_snapshot_ids,
vec![10]
);
// Prune `metadata-log` on the current metadata (as `write.metadata.previous-versions-max` would)
// and backdate objects past the safety window so cleanup evaluates Snapshot 11's live graph alone.
let current_entry = store
.load_table(bucket, "analytics", "events")
.await
.expect("table lookup")
.expect("table exists");
let current_meta_obj = backend
.read_object(bucket, &current_entry.metadata_location)
.await
.expect("read current metadata")
.expect("current metadata exists");
let mut pruned_metadata: serde_json::Value = serde_json::from_slice(&current_meta_obj.data).expect("decode current metadata");
pruned_metadata["metadata-log"] = serde_json::json!([]);
backend
.put_json(bucket, &current_entry.metadata_location, pruned_metadata)
.await;
store
.put_table_maintenance_config(
bucket,
"analytics",
"events",
crate::table_catalog::TableMaintenanceConfig {
version: crate::table_catalog::TABLE_MAINTENANCE_CONFIG_VERSION,
retain_recent_metadata_files: 0,
delete_enabled: true,
..Default::default()
},
)
.await
.expect("maintenance delete config should persist");
for record in backend.state.lock().await.objects.values_mut() {
record.mod_time = Some(OffsetDateTime::UNIX_EPOCH);
}
let cleanup = table_metadata_maintenance_response(
&store,
&backend,
bucket,
&namespace,
"events",
TableMetadataMaintenanceRequest {
retain_recent_metadata_files: 0,
delete: true,
snapshot_expiration: None,
commit_snapshot_expiration: false,
compaction: None,
commit_compaction: false,
},
)
.await
.expect("metadata cleanup after parent snapshot expiration should succeed");
assert_eq!(cleanup.job.status, crate::table_catalog::TableMetadataMaintenanceJobStatus::Successful);
assert!(!cleanup.deletable_metadata_locations.is_empty());
let snap_10_key = test_snapshot_object_key(bucket, &snap_10);
let snap_11_key = test_snapshot_object_key(bucket, &snap_11);
let manifest_10_key = test_snapshot_object_key(bucket, &manifest_10);
let data_file_key = test_snapshot_object_key(bucket, &data_file);
assert_eq!(cleanup.deletable_object_locations, vec![snap_10_key.clone()]);
assert!(
!backend.object_exists(bucket, &snap_10_key).await.expect("snap-10 lookup"),
"expired parent snapshot's manifest-list should be reclaimed once unreferenced"
);
for retained_key in [&snap_11_key, &manifest_10_key, &data_file_key] {
assert!(
backend.object_exists(bucket, retained_key).await.expect("retained lookup"),
"shared object referenced by surviving no-op overwrite snapshot must remain retained: {retained_key}"
);
}
}
#[tokio::test]
async fn row_level_conflict_rejects_delete_of_non_current_file() {
let store = TestTableCatalogStore::default();
@@ -0,0 +1,246 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use super::*;
use serde_json::{Value, json};
const DETACHED_HISTORY: &str = "cannot publish a snapshot history without a surviving branch";
const EXISTING_BRANCH: &str = "cannot publish a new snapshot history over an existing branch";
struct Table {
store: TestTableCatalogStore,
backend: TestTableCatalogObjectBackend,
namespace: crate::table_catalog::Namespace,
location: String,
}
impl Table {
async fn empty() -> Self {
let store = TestTableCatalogStore::default();
let backend = TestTableCatalogObjectBackend::content_addressed();
let namespace = crate::table_catalog::Namespace::parse("analytics").unwrap();
let created = create_standard_events_table(&store, &backend, &namespace).await;
Self {
location: created.metadata["location"].as_str().unwrap().to_owned(),
store,
backend,
namespace,
}
}
async fn populated() -> Self {
let table = Self::empty().await;
for name in ["a", "b"] {
seed_test_manifest(&table.backend, "warehouse", &table.manifest(name), &[(&table.data(name), 0, 1, 10, 1)]).await;
}
let list = table
.list("initial", &[(&table.manifest("a"), 1, 10), (&table.manifest("b"), 1, 10)])
.await;
table
.commit(json!({"updates": [snapshot("append", 10, 1, None, &list), branch("main", 10), branch("audit", 10)]}))
.await
.unwrap();
table
}
fn data(&self, name: &str) -> String {
format!("{}/data/{name}.parquet", self.location)
}
fn manifest(&self, name: &str) -> String {
format!("{}/metadata/manifest-{name}.avro", self.location)
}
async fn list(&self, name: &str, entries: &[(&str, i64, i64)]) -> String {
let location = format!("{}/metadata/snap-{name}.avro", self.location);
seed_test_manifest_list_entries(&self.backend, "warehouse", &location, entries).await;
location
}
async fn commit(&self, request: Value) -> S3Result<RestCommitTableResponse> {
commit_table_response(
&self.store,
&trusted_table_commit_backend(&self.backend),
"warehouse",
&self.namespace,
"events",
serde_json::from_value(request).unwrap(),
)
.await
}
async fn entry(&self) -> crate::table_catalog::TableEntry {
self.store
.load_table("warehouse", "analytics", "events")
.await
.unwrap()
.unwrap()
}
async fn reject(&self, updates: Value, message: &str) {
let before = self.entry().await;
let error = self
.commit(json!({"updates": updates}))
.await
.expect_err("commit should fail");
assert_eq!(error.code(), &S3ErrorCode::InvalidRequest);
assert_eq!(error.message(), Some(message));
let after = self.entry().await;
assert_eq!(after.metadata_location, before.metadata_location);
assert_eq!(after.version_token, before.version_token);
assert_eq!(after.generation, before.generation);
let metadata = read_persisted_table_metadata_for_entry(&self.backend, &after, &after.metadata_location, true)
.await
.unwrap();
assert_eq!(metadata["current-snapshot-id"], 10);
assert_eq!(metadata["refs"]["main"]["snapshot-id"], 10);
assert_eq!(metadata["refs"]["audit"]["snapshot-id"], 10);
assert!(metadata["refs"].get("temporary").is_none());
let live = load_snapshot_live_files(&self.backend, "warehouse", &after, &metadata, Some(10))
.await
.unwrap();
assert!(live.data_files.contains_key(&self.data("a")));
assert!(live.data_files.contains_key(&self.data("b")));
}
}
fn snapshot(operation: &str, id: i64, sequence: i64, parent: Option<i64>, list: &str) -> Value {
let mut snapshot = json!({
"snapshot-id": id,
"sequence-number": sequence,
"timestamp-ms": 1000 * sequence,
"manifest-list": list,
"summary": {"operation": operation}
});
if let Some(parent) = parent {
snapshot["parent-snapshot-id"] = parent.into();
}
json!({"action": "add-snapshot", "snapshot": snapshot})
}
fn branch(name: &str, id: i64) -> Value {
json!({"action": "set-snapshot-ref", "ref-name": name, "type": "branch", "snapshot-id": id})
}
fn tag(name: &str, id: i64) -> Value {
json!({"action": "set-snapshot-ref", "ref-name": name, "type": "tag", "snapshot-id": id})
}
fn remove_ref(name: &str) -> Value {
json!({"action": "remove-snapshot-ref", "ref-name": name})
}
#[tokio::test]
async fn temporary_branch_cannot_publish_a_root_on_a_populated_table() {
let table = Table::populated().await;
let list = table.list("empty", &[]).await;
let root = snapshot("overwrite", 11, 2, None, &list);
let child = snapshot("append", 12, 3, Some(11), &list);
table
.reject(json!([root, branch("temporary", 11), remove_ref("temporary")]), DETACHED_HISTORY)
.await;
table
.reject(json!([root, branch("temporary", 11), branch("temporary", 10)]), EXISTING_BRANCH)
.await;
table
.reject(json!([root, child, branch("temporary", 12), remove_ref("temporary")]), DETACHED_HISTORY)
.await;
// The same root may be staged with no ref, or published on a branch that survives.
let staged = table.commit(json!({"updates": [root]})).await.unwrap();
assert_eq!(staged.metadata["current-snapshot-id"], 10);
assert!(staged.metadata["refs"].get("temporary").is_none());
assert_eq!(staged.metadata["refs"]["main"]["snapshot-id"], 10);
let published = table
.commit(json!({"updates": [
snapshot("overwrite", 13, 3, None, &list),
tag("initial", 13),
snapshot("append", 14, 4, Some(13), &list),
branch("feature", 14),
tag("release", 14),
branch("temporary", 13),
remove_ref("temporary"),
]}))
.await
.unwrap();
assert_eq!(published.metadata["current-snapshot-id"], 10);
assert_eq!(published.metadata["refs"]["feature"]["snapshot-id"], 14);
assert_eq!(published.metadata["refs"]["initial"]["snapshot-id"], 13);
assert_eq!(published.metadata["refs"]["release"]["snapshot-id"], 14);
assert_eq!(published.metadata["refs"]["main"]["snapshot-id"], 10);
assert_eq!(published.metadata["refs"]["audit"]["snapshot-id"], 10);
}
#[tokio::test]
async fn a_tagged_root_requires_a_branch_for_its_own_history() {
let table = Table::empty().await;
let list = table.list("empty", &[]).await;
let root = snapshot("delete", 10, 1, None, &list);
for updates in [
json!([root, tag("release", 10)]),
json!([root, branch("temporary", 10), tag("release", 10), remove_ref("temporary")]),
json!([
root,
tag("release", 10),
snapshot("overwrite", 11, 2, None, &list),
branch("main", 11)
]),
] {
let before = table.entry().await;
let error = table
.commit(json!({"updates": updates}))
.await
.expect_err("commit should fail");
assert_eq!(error.code(), &S3ErrorCode::InvalidRequest);
assert_eq!(error.message(), Some(DETACHED_HISTORY));
let after = table.entry().await;
assert_eq!(after.metadata_location, before.metadata_location);
assert_eq!(after.version_token, before.version_token);
assert_eq!(after.generation, before.generation);
}
let committed = table
.commit(json!({"updates": [root, branch("main", 10), tag("release", 10)]}))
.await
.unwrap();
assert_eq!(committed.metadata["current-snapshot-id"], 10);
assert_eq!(committed.metadata["refs"]["release"]["snapshot-id"], 10);
assert_eq!(committed.metadata["refs"]["main"]["snapshot-id"], 10);
}
#[tokio::test]
async fn empty_inline_manifests_are_rejected_on_v2_tables() {
let table = Table::empty().await;
let before = table.entry().await;
let error = table
.commit(json!({"updates": [
{
"action": "add-snapshot",
"snapshot": {
"snapshot-id": 10,
"sequence-number": 1,
"timestamp-ms": 1000,
"manifests": [],
"summary": {"operation": "overwrite"}
}
},
branch("main", 10)
]}))
.await
.expect_err("v2 empty inline manifests should fail");
assert_eq!(error.code(), &S3ErrorCode::InvalidRequest);
assert_eq!(error.message(), Some("Iceberg v2 snapshots require manifest-list"));
let after = table.entry().await;
assert_eq!(after.metadata_location, before.metadata_location);
assert_eq!(after.generation, before.generation);
}