This is an automated email from the ASF dual-hosted git repository.
JingsongLi pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/paimon-rust.git
The following commit(s) were added to refs/heads/main by this push:
new 818e47a8 fix(table): preserve files after replayed snapshot
publication (#1417)
818e47a8 is described below
commit 818e47a8c480946558557a34d46e7a71051328a0
Author: QuakeWang <[email protected]>
AuthorDate: Tue Nov 17 23:36:12 2026 +0800
fix(table): preserve files after replayed snapshot publication (#1417)
---
crates/paimon/src/io/file_io.rs | 47 +-
crates/paimon/src/io/storage_oss.rs | 50 ++-
crates/paimon/src/table/snapshot_commit.rs | 8 +-
crates/paimon/src/table/snapshot_manager.rs | 20 +-
crates/paimon/src/table/table_commit.rs | 29 +-
.../src/table/table_commit/auto_index_tests.rs | 25 +-
.../paimon/src/table/table_commit/parity_tests.rs | 12 +-
.../src/table/table_commit/pk_dv_retry_tests.rs | 477 ++++++++++++++++++++-
.../src/table/table_commit/recovery_tests.rs | 12 +-
9 files changed, 628 insertions(+), 52 deletions(-)
diff --git a/crates/paimon/src/io/file_io.rs b/crates/paimon/src/io/file_io.rs
index edc472a1..bd4d9558 100644
--- a/crates/paimon/src/io/file_io.rs
+++ b/crates/paimon/src/io/file_io.rs
@@ -942,8 +942,9 @@ impl FileIO {
}
/// Publish a complete immutable file only if the target does not exist.
- /// Returns `false` only for a definite publication conflict. Other
failures
- /// may have an unknown outcome and must never trigger an unconditional
write.
+ /// Returns `false` when a conditional write is rejected. The target may
+ /// have been published by an earlier attempt of the same request.
+ /// Errors can also leave the publication outcome unknown.
pub(crate) async fn write_atomic_if_not_exists(
&self,
path: &str,
@@ -1780,6 +1781,21 @@ pub struct InputFile {
}
impl InputFile {
+ pub(crate) async fn invalidate_cache(&self) -> crate::Result<()> {
+ if let Some(cache) = &self.cache {
+ let (_, _, cache_path) = self.source.resolve(&self.path).await?;
+ if let Some(cache_path) = cache_path {
+ cache.invalidate_path(&cache_path).await?;
+ }
+ }
+ Ok(())
+ }
+
+ pub(crate) fn without_cache(mut self) -> Self {
+ self.cache = None;
+ self
+ }
+
pub fn location(&self) -> &str {
&self.path
}
@@ -3752,6 +3768,33 @@ mod input_output_test {
);
}
+ #[cfg(not(windows))]
+ #[tokio::test]
+ async fn test_input_file_cache_invalidation_refreshes_shared_readers() {
+ let source_directory = tempfile::tempdir().unwrap();
+ let cache_directory = tempfile::tempdir().unwrap();
+ let source_path = source_directory.path().join("snapshot-1");
+ std::fs::write(&source_path, b"old metadata").unwrap();
+ let file_io = setup_cached_fs_file_io(cache_directory.path());
+ let input = file_io
+ .new_input(&format!("file:{}", source_path.display()))
+ .unwrap();
+ let peer = file_io
+ .clone()
+ .new_input(&source_path.to_string_lossy())
+ .unwrap();
+ let old = Bytes::from_static(b"old metadata");
+ assert_eq!(input.read().await.unwrap(), old);
+ assert_eq!(peer.read().await.unwrap(), old);
+
+ let replacement = Bytes::from_static(b"replacement metadata is
longer");
+ std::fs::write(&source_path, &replacement).unwrap();
+ assert_eq!(input.read().await.unwrap(), old);
+ peer.invalidate_cache().await.unwrap();
+ assert_eq!(input.read().await.unwrap(), replacement);
+ assert_eq!(peer.read().await.unwrap(), replacement);
+ }
+
#[cfg(not(windows))]
#[tokio::test]
async fn test_file_io_local_cache_invalidates_after_successful_write() {
diff --git a/crates/paimon/src/io/storage_oss.rs
b/crates/paimon/src/io/storage_oss.rs
index 17b99bea..c531fd47 100644
--- a/crates/paimon/src/io/storage_oss.rs
+++ b/crates/paimon/src/io/storage_oss.rs
@@ -154,8 +154,9 @@ mod tests {
use axum::body::Body;
use axum::extract::State;
use axum::http::{header, HeaderMap, Response, StatusCode};
- use axum::routing::get;
+ use axum::routing::{get, put};
use axum::Router;
+ use bytes::Bytes;
use super::*;
@@ -286,6 +287,53 @@ mod tests {
assert_eq!(attempts.load(Ordering::SeqCst), 2);
}
+ #[tokio::test]
+ async fn
test_oss_replayed_conditional_put_reports_conflict_after_publication() {
+ let attempts = Arc::new(AtomicUsize::new(0));
+ let object = Arc::new(Mutex::new(None));
+ let app = Router::new().fallback(put({
+ let attempts = attempts.clone();
+ let object = object.clone();
+ move |headers: HeaderMap, body: Bytes| {
+ let object = object.clone();
+ let attempts = attempts.clone();
+ async move {
+ assert_eq!(headers["x-oss-forbid-overwrite"], "true");
+ attempts.fetch_add(1, Ordering::SeqCst);
+ let mut object = object.lock().unwrap();
+ if let Some(published) = object.as_ref() {
+ assert_eq!(published, &body);
+ return Response::builder()
+ .status(StatusCode::CONFLICT)
+
.body(Body::from("<Error><Code>FileAlreadyExists</Code><Message>exists</Message></Error>"))
+ .unwrap();
+ }
+ *object = Some(body);
+ temporary_failure()
+ }
+ }
+ }));
+ let listener =
tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let mut cfg = OssConfig::default();
+ cfg.endpoint = Some(format!("http://{}",
listener.local_addr().unwrap()));
+ cfg.addressing_style = Some("path".into());
+ cfg.skip_signature = true;
+ let server = tokio::spawn(async move { axum::serve(listener,
app).await.unwrap() });
+ let operator = oss_config_build(&storage_config(cfg),
"oss://bucket/table").unwrap();
+ let io = crate::io::FileIOBuilder::new("file")
+ .with_fs_operator(operator)
+ .build()
+ .unwrap();
+ let body = Bytes::from_static(b"snapshot contents");
+ let published = io
+ .write_atomic_if_not_exists("/table/snapshot/snapshot-1",
body.clone())
+ .await;
+ server.abort();
+ assert!(!published.unwrap());
+ assert_eq!(attempts.load(Ordering::SeqCst), 2);
+ assert_eq!(object.lock().unwrap().as_ref(), Some(&body));
+ }
+
#[tokio::test]
async fn test_oss_retry_count_is_additional_attempts() {
let attempts = Arc::new(AtomicUsize::new(0));
diff --git a/crates/paimon/src/table/snapshot_commit.rs
b/crates/paimon/src/table/snapshot_commit.rs
index 7d49a62b..61831685 100644
--- a/crates/paimon/src/table/snapshot_commit.rs
+++ b/crates/paimon/src/table/snapshot_commit.rs
@@ -34,9 +34,11 @@ use std::sync::Arc;
/// - `RESTSnapshotCommit` — via Catalog API (e.g. REST)
#[async_trait]
pub trait SnapshotCommit: Send + Sync {
- /// Commit the given snapshot. Returns true if successful, false if
- /// another writer won the race. `branch` selects the snapshot namespace;
- /// data files and manifests remain shared under the table location.
+ /// Commit the given snapshot. Returns true on success and false if
publication
+ /// was rejected. REST rejection is definite; file publication can reject a
+ /// replay after an earlier storage attempt succeeded.
+ /// `branch` selects the snapshot namespace; data files and manifests
remain
+ /// shared under the table location.
async fn commit(
&self,
base_snapshot_uuid: Option<&str>,
diff --git a/crates/paimon/src/table/snapshot_manager.rs
b/crates/paimon/src/table/snapshot_manager.rs
index 1c35cb70..d308ea51 100644
--- a/crates/paimon/src/table/snapshot_manager.rs
+++ b/crates/paimon/src/table/snapshot_manager.rs
@@ -19,7 +19,7 @@
//!
//!
Reference:[org.apache.paimon.utils.SnapshotManager](https://github.com/apache/paimon/blob/release-1.3/paimon-core/src/main/java/org/apache/paimon/utils/SnapshotManager.java).
use crate::catalog::DEFAULT_MAIN_BRANCH;
-use crate::io::FileIO;
+use crate::io::{FileIO, InputFile};
use crate::spec::Snapshot;
use futures::future::try_join_all;
use std::str;
@@ -225,8 +225,20 @@ impl SnapshotManager {
/// Get a snapshot by id.
pub async fn get_snapshot(&self, snapshot_id: i64) ->
crate::Result<Snapshot> {
- let snapshot_path = self.snapshot_path(snapshot_id);
- let snap_input = self.file_io.new_input(&snapshot_path)?;
+ let input = self.file_io.new_input(&self.snapshot_path(snapshot_id))?;
+ Self::read_snapshot(snapshot_id, input).await
+ }
+
+ /// Read file snapshot identity directly from storage for publication
checks.
+ /// An external rollback can reuse an ID whose old snapshot is cached.
+ /// Invalidate that entry so subsequent ordinary reads see the verified
state.
+ pub(super) async fn get_snapshot_uncached(&self, snapshot_id: i64) ->
crate::Result<Snapshot> {
+ let input = self.file_io.new_input(&self.snapshot_path(snapshot_id))?;
+ input.invalidate_cache().await?;
+ Self::read_snapshot(snapshot_id, input.without_cache()).await
+ }
+
+ async fn read_snapshot(snapshot_id: i64, snap_input: InputFile) ->
crate::Result<Snapshot> {
if !snap_input.exists().await? {
return Err(crate::Error::SnapshotNotExist { snapshot_id });
}
@@ -266,7 +278,7 @@ impl SnapshotManager {
/// Atomically commit a snapshot.
///
/// Writes the snapshot JSON to the target path. Returns `false` if the
- /// target already exists (another writer won the race).
+ /// target already exists. A storage retry can encounter its own
publication.
///
/// Uses atomic no-replace publication: a staged file on the local
filesystem,
/// conditional rename, or a conditional object write. Backends without a
diff --git a/crates/paimon/src/table/table_commit.rs
b/crates/paimon/src/table/table_commit.rs
index 47ce9ba7..3b72e8d7 100644
--- a/crates/paimon/src/table/table_commit.rs
+++ b/crates/paimon/src/table/table_commit.rs
@@ -1423,7 +1423,7 @@ impl TableCommit {
// Once publication starts its outcome may be unknown. These files must
// remain available even if the response is lost or a later retry
fails.
let base_snapshot_uuid =
latest_snapshot.as_ref().and_then(Snapshot::uuid);
- let publication_error = match self
+ let publication = self
.snapshot_commit
.commit(
base_snapshot_uuid,
@@ -1431,8 +1431,31 @@ impl TableCommit {
self.table.branch(),
&statistics,
)
- .await
- {
+ .await;
+ // Storage may replay a successful conditional write after losing its
+ // response. REST POSTs are not replayed; success=false is a definite
+ // server rejection and must retain its cleanup semantics.
+ let publication = match publication {
+ Ok(false) if self.table.rest_env.is_some() => Ok(false),
+ Ok(false) => match
self.snapshot_manager.get_snapshot_uncached(snapshot.id()).await {
+ Ok(current) if current.uuid() == snapshot.uuid() => Ok(true),
+ // Older writers can omit the UUID. Each attempt writes a
+ // unique delta manifest list before publication.
+ Ok(current) if current.delta_manifest_list() !=
snapshot.delta_manifest_list() => {
+ Ok(false)
+ }
+ Ok(_) => Err(crate::Error::DataInvalid {
+ message: format!(
+ "Cannot verify ownership of snapshot {} after
conditional publication was rejected",
+ snapshot.id()
+ ),
+ source: None,
+ }),
+ Err(error) => Err(error),
+ },
+ result => result,
+ };
+ let publication_error = match publication {
Ok(true) => {
if !self.commit_callbacks.is_empty() {
self.notify_commit_callbacks(snapshot.clone(),
resolved.entries)
diff --git a/crates/paimon/src/table/table_commit/auto_index_tests.rs
b/crates/paimon/src/table/table_commit/auto_index_tests.rs
index 267dbe33..3c7e662c 100644
--- a/crates/paimon/src/table/table_commit/auto_index_tests.rs
+++ b/crates/paimon/src/table/table_commit/auto_index_tests.rs
@@ -726,6 +726,7 @@ async fn
recovery_finishes_indexing_after_data_publication_for_append_and_overwr
enum Publication {
Conflict,
LoseResponse,
+ Replay,
FailBeforePublish,
}
@@ -754,13 +755,12 @@ impl SnapshotCommit for InjectIndexPublication {
other.commit(messages(&self.table, vec![99]).await).await?;
return Ok(false);
}
- Publication::LoseResponse => {
- assert!(
- self.table
- .snapshot_manager()
- .commit_snapshot(snapshot)
- .await?
- );
+ Publication::LoseResponse | Publication::Replay => {
+ let manager = self.table.snapshot_manager();
+ assert!(manager.commit_snapshot(snapshot).await?);
+ if matches!(self.mode, Publication::Replay) {
+ return manager.commit_snapshot(snapshot).await;
+ }
return Err(crate::Error::UnexpectedError {
message: "lost index response".into(),
source: None,
@@ -852,11 +852,20 @@ async fn
conflicting_replacement_replans_instead_of_deleting_a_competitors_paylo
#[tokio::test]
async fn lost_index_response_is_recovered_without_deleting_published_files() {
+ check_index_publication_recovery(Publication::LoseResponse).await;
+}
+
+#[tokio::test]
+async fn replayed_index_publication_preserves_published_files() {
+ check_index_publication_recovery(Publication::Replay).await;
+}
+
+async fn check_index_publication_recovery(mode: Publication) {
let table = table(Some(true), false).await;
let mut commit = TableCommit::new(table.clone(), "writer".into());
commit.snapshot_commit = Arc::new(InjectIndexPublication {
table: table.clone(),
- mode: Publication::LoseResponse,
+ mode,
fired: AtomicBool::new(false),
});
let input = messages(&table, vec![1, 2]).await;
diff --git a/crates/paimon/src/table/table_commit/parity_tests.rs
b/crates/paimon/src/table/table_commit/parity_tests.rs
index 6f5c1024..4a59c986 100644
--- a/crates/paimon/src/table/table_commit/parity_tests.rs
+++ b/crates/paimon/src/table/table_commit/parity_tests.rs
@@ -1117,7 +1117,8 @@ async fn
rest_commit_uses_catalog_snapshot_schema_and_retry_identity() {
use crate::common::Options;
use axum::{
body::Bytes,
- http::{Method, Uri},
+ http::{Method, StatusCode, Uri},
+ response::IntoResponse,
Json, Router,
};
use std::sync::Mutex;
@@ -1144,14 +1145,17 @@ async fn
rest_commit_uses_catalog_snapshot_schema_and_retry_identity() {
let next: Snapshot =
serde_json::from_value(request["snapshot"].clone()).unwrap();
assert_eq!(next.id(), snapshot.lock().unwrap().id() + 1);
*snapshot.lock().unwrap() = next;
- // Force the retry/deduplication path after catalog
publication.
- serde_json::json!({"success": false})
+ // The publication succeeded, but its response was lost.
+ return (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(serde_json::json!({"code": 500, "message": "lost
commit response"})),
+ ).into_response();
} else if uri.path().ends_with("/snapshot") {
serde_json::json!({"snapshot": {"snapshot":
*snapshot.lock().unwrap(), "recordCount": 10}})
} else {
serde_json::json!({"schemaId": 3})
};
- Json(response)
+ Json(response).into_response()
}
});
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
diff --git a/crates/paimon/src/table/table_commit/pk_dv_retry_tests.rs
b/crates/paimon/src/table/table_commit/pk_dv_retry_tests.rs
index d6bd4dab..958df729 100644
--- a/crates/paimon/src/table/table_commit/pk_dv_retry_tests.rs
+++ b/crates/paimon/src/table/table_commit/pk_dv_retry_tests.rs
@@ -18,11 +18,21 @@
mod pk_dv_retry {
use super::*;
use arrow_array::{Int32Array, RecordBatch};
+ use futures::TryStreamExt;
use indexmap::IndexMap;
use roaring::RoaringBitmap;
use std::sync::atomic::{AtomicUsize, Ordering};
async fn write(table: &Table, ids: Vec<i32>, level: i32) -> (Vec<u8>,
DataFileMeta) {
+ write_with_snapshot_format(table, ids, level, false).await
+ }
+
+ async fn write_with_snapshot_format(
+ table: &Table,
+ ids: Vec<i32>,
+ level: i32,
+ legacy: bool,
+ ) -> (Vec<u8>, DataFileMeta) {
let batch = RecordBatch::try_from_iter([
(
"id",
@@ -49,7 +59,11 @@ mod pk_dv_retry {
messages[0].partition.clone(),
messages[0].new_files[0].clone(),
);
- builder.new_commit().commit(messages).await.unwrap();
+ let mut commit = builder.new_commit();
+ if legacy {
+ commit.snapshot_commit =
Arc::new(LegacySnapshotCommit(table.snapshot_manager()));
+ }
+ commit.commit(messages).await.unwrap();
output
}
@@ -76,6 +90,25 @@ mod pk_dv_retry {
.unwrap()
}
+ async fn count_rows(table: &Table, id: i32) -> usize {
+ let mut read = table.new_read_builder();
+ read.with_filter(
+ crate::spec::PredicateBuilder::new(table.schema().fields())
+ .equal("id", Datum::Int(id))
+ .unwrap(),
+ );
+ let plan = read.new_scan().plan().await.unwrap();
+ let batches: Vec<RecordBatch> = read
+ .new_read()
+ .unwrap()
+ .to_arrow(plan.splits())
+ .unwrap()
+ .try_collect()
+ .await
+ .unwrap();
+ batches.iter().map(RecordBatch::num_rows).sum()
+ }
+
async fn replace_vectors(table: &Table, masks: &[(&str, &[u32])]) {
let mut message = CommitMessage::new(EMPTY_SERIALIZED_ROW.to_vec(), 0,
vec![]);
message.deleted_index_files = vectors(table).await.1;
@@ -103,7 +136,10 @@ mod pk_dv_retry {
}
async fn fixture() -> (Table, String, String) {
- let path = format!("memory:/pk-dv-retry/{}", uuid::Uuid::new_v4());
+ fixture_at(format!("memory:/pk-dv-retry/{}",
uuid::Uuid::new_v4())).await
+ }
+
+ async fn fixture_at(path: String) -> (Table, String, String) {
let mut options = crate::Options::new();
options.set("warehouse", &path);
options.set("local-cache.enabled", "true");
@@ -171,10 +207,42 @@ mod pk_dv_retry {
.collect()
}
+ fn snapshot_without_uuid(snapshot: &Snapshot) -> Snapshot {
+ let mut json = serde_json::to_value(snapshot).unwrap();
+ assert!(json.as_object_mut().unwrap().remove("uuid").is_some());
+ serde_json::from_value(json).unwrap()
+ }
+
+ struct LegacySnapshotCommit(SnapshotManager);
+
+ #[async_trait::async_trait]
+ impl SnapshotCommit for LegacySnapshotCommit {
+ async fn commit(
+ &self,
+ _: Option<&str>,
+ snapshot: &Snapshot,
+ _: &str,
+ _: &[PartitionStatistics],
+ ) -> Result<bool> {
+ self.0
+ .commit_snapshot(&snapshot_without_uuid(snapshot))
+ .await
+ }
+ }
+
+ #[derive(Clone, Copy)]
+ enum FirstPublication {
+ Conflict { legacy: bool },
+ LostResponse,
+ Replay { legacy: bool },
+ Deferred,
+ }
+
struct RacingCommit {
table: Table,
calls: AtomicUsize,
- publish_first: bool,
+ first: FirstPublication,
+ deferred: std::sync::Mutex<Option<Snapshot>>,
paths: std::sync::Mutex<Vec<Vec<String>>>,
}
@@ -189,31 +257,365 @@ mod pk_dv_retry {
) -> Result<bool> {
let paths = dv_paths(&self.table, snapshot).await;
self.paths.lock().unwrap().push(paths);
+ let manager = self.table.snapshot_manager();
if self.calls.fetch_add(1, Ordering::SeqCst) == 0 {
- if self.publish_first {
- assert!(
- self.table
- .snapshot_manager()
- .commit_snapshot(snapshot)
- .await?
- );
- return Err(crate::Error::IoUnsupported {
- message: "lost compact response".into(),
- });
+ match self.first {
+ FirstPublication::Conflict { legacy } => {
+ write_with_snapshot_format(&self.table, vec![4000], 0,
legacy).await;
+ assert_eq!(
+
manager.get_snapshot(snapshot.id()).await?.uuid().is_none(),
+ legacy
+ );
+ return Ok(false);
+ }
+ FirstPublication::LostResponse => {
+ assert!(manager.commit_snapshot(snapshot).await?);
+ return Err(crate::Error::IoUnsupported {
+ message: "lost compact response".into(),
+ });
+ }
+ FirstPublication::Replay { legacy } => {
+ let stored = legacy.then(||
snapshot_without_uuid(snapshot));
+ assert!(
+ manager
+
.commit_snapshot(stored.as_ref().unwrap_or(snapshot))
+ .await?
+ );
+ }
+ FirstPublication::Deferred => {
+ *self.deferred.lock().unwrap() =
Some(snapshot.clone());
+ return Ok(false);
+ }
}
- write(&self.table, vec![4000], 0).await;
- return Ok(false);
}
- self.table
+ manager.commit_snapshot(snapshot).await
+ }
+ }
+
+ #[tokio::test]
+ async fn
compact_cas_loss_cleans_only_new_dv_but_publication_error_preserves_it() {
+ check_compact_publications(&[
+ FirstPublication::Conflict { legacy: false },
+ FirstPublication::LostResponse,
+ ])
+ .await;
+ }
+
+ #[tokio::test]
+ async fn compact_cas_loss_cleans_new_dv_when_a_legacy_writer_wins() {
+ check_compact_publications(&[FirstPublication::Conflict { legacy: true
}]).await;
+ }
+
+ #[tokio::test]
+ async fn compact_replayed_publication_preserves_published_dv() {
+ check_compact_publications(&[FirstPublication::Replay { legacy: false
}]).await;
+ }
+
+ #[tokio::test]
+ async fn
rest_compact_conflict_cleans_unpublished_dv_without_snapshot_file() {
+ check_rest_compact_publication(RestPublication::Conflict).await;
+ }
+
+ #[tokio::test]
+ async fn
rest_compact_rejection_with_catalog_only_base_cleans_unpublished_dv() {
+ check_rest_compact_publication(RestPublication::Rejection).await;
+ }
+
+ #[tokio::test]
+ async fn rest_compact_lost_response_preserves_published_dv() {
+ check_rest_compact_publication(RestPublication::LostResponse).await;
+ }
+
+ #[derive(Clone, Copy)]
+ enum RestPublication {
+ Conflict,
+ Rejection,
+ LostResponse,
+ }
+
+ async fn check_rest_compact_publication(mode: RestPublication) {
+ use crate::api::rest_api::RESTApi;
+ use axum::{
+ body::Bytes,
+ http::{Method, StatusCode, Uri},
+ response::IntoResponse,
+ Json, Router,
+ };
+ use std::sync::Mutex;
+
+ let (table, anchor, _) = fixture().await;
+ write(&table, vec![42], 0).await;
+ let current = Arc::new(Mutex::new(
+ table
.snapshot_manager()
- .commit_snapshot(snapshot)
+ .get_latest_snapshot()
+ .await
+ .unwrap()
+ .unwrap(),
+ ));
+ let submitted = Arc::new(Mutex::new(Vec::<Snapshot>::new()));
+ let app = Router::new().fallback({
+ let current = current.clone();
+ let submitted = submitted.clone();
+ let table = table.clone();
+ move |method: Method, uri: Uri, body: Bytes| {
+ let current = current.clone();
+ let submitted = submitted.clone();
+ let table = table.clone();
+ async move {
+ let response = if method == Method::POST &&
uri.path().ends_with("/commit") {
+ let request: serde_json::Value =
serde_json::from_slice(&body).unwrap();
+ let next: Snapshot =
serde_json::from_value(request["snapshot"].clone()).unwrap();
+ assert_eq!(next.id(), current.lock().unwrap().id() +
1);
+ let first = {
+ let mut submitted = submitted.lock().unwrap();
+ submitted.push(next.clone());
+ submitted.len() == 1
+ };
+ if first && matches!(mode, RestPublication::Conflict) {
+ write(&table, vec![4000], 0).await;
+ let manager = table.snapshot_manager();
+ let winner =
manager.get_latest_snapshot().await.unwrap().unwrap();
+ assert_eq!(winner.id(), next.id());
+ // The catalog keeps the snapshot; clients only
need its manifests.
+
manager.delete_snapshot(winner.id()).await.unwrap();
+ *current.lock().unwrap() = winner;
+ } else if !first || matches!(mode,
RestPublication::LostResponse) {
+ *current.lock().unwrap() = next;
+ }
+ if first && matches!(mode,
RestPublication::LostResponse) {
+ return (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(serde_json::json!({"code": 500,
"message": "lost commit response"})),
+ ).into_response();
+ }
+ serde_json::json!({"success": !first})
+ } else if uri.path().ends_with("/snapshot") {
+ serde_json::json!({"snapshot": {"snapshot":
*current.lock().unwrap(), "recordCount": 0}})
+ } else {
+ serde_json::json!({"schemaId": table.schema().id()})
+ };
+ Json(response).into_response()
+ }
+ }
+ });
+ let listener =
tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let mut options = crate::Options::new();
+ options.set("uri", format!("http://{}",
listener.local_addr().unwrap()));
+ options.set("prefix", "test");
+ options.set("token.provider", "bear");
+ options.set("token", "test-token");
+ let server = tokio::spawn(async move { axum::serve(listener,
app).await.unwrap() });
+ let env = crate::table::RESTEnv::new(
+ table.identifier().clone(),
+ "uuid".into(),
+ Arc::new(RESTApi::new(options.clone(), false).await.unwrap()),
+ options.clone(),
+ false,
+ None,
+
crate::io::FileIOCacheContext::from_props(options.to_map()).unwrap(),
+ );
+ let rest = Table::new(
+ table.file_io().clone(),
+ table.identifier().clone(),
+ table.location().into(),
+ table.schema().clone(),
+ Some(env),
+ );
+ let builder = rest.new_compact_builder();
+ let plan = builder.new_planner().unwrap().plan().await.unwrap();
+ let result = builder
+ .new_executor()
+ .unwrap()
+ .execute(&plan.tasks()[0])
+ .await
+ .unwrap();
+ if matches!(mode, RestPublication::Rejection) {
+ write(&table, vec![4000], 0).await;
+ let manager = table.snapshot_manager();
+ let advanced =
manager.get_latest_snapshot().await.unwrap().unwrap();
+ manager.delete_snapshot(advanced.id()).await.unwrap();
+ *current.lock().unwrap() = advanced;
+ }
+ let mut commit = TableCommit::new(rest.clone(),
"rest-compactor".into());
+ commit.commit_min_retry_wait_ms = 0;
+ commit.commit_max_retry_wait_ms = 0;
+ let unknown = matches!(mode, RestPublication::LostResponse);
+ if !matches!(mode, RestPublication::Conflict) {
+ commit.commit_max_retries = 0;
+ let error = commit
+ .commit_compact(vec![result.clone()])
.await
+ .unwrap_err();
+ assert_eq!(
+ error.to_string().contains("Commit outcome may be unknown"),
+ unknown,
+ "{error}",
+ );
+ let first = submitted.lock().unwrap()[0].clone();
+ for path in dv_paths(&rest, &first).await {
+ assert_eq!(rest.file_io().exists(&path).await.unwrap(),
unknown);
+ }
+ }
+ let metrics =
commit.commit_compact(vec![result.clone()]).await.unwrap();
+ let attempts = submitted.lock().unwrap().clone();
+ assert_eq!(attempts.len(), if unknown { 1 } else { 2 });
+ let first_paths = dv_paths(&rest, &attempts[0]).await;
+ let published_paths = dv_paths(&rest, attempts.last().unwrap()).await;
+ assert_eq!(first_paths.len(), 1);
+ assert_eq!(published_paths.contains(&first_paths[0]), unknown);
+ assert_eq!(
+ rest.file_io().exists(&first_paths[0]).await.unwrap(),
+ unknown
+ );
+ for path in &published_paths {
+ assert!(rest.file_io().exists(path).await.unwrap());
+ }
+ for snapshot in &attempts {
+ assert!(!rest
+ .file_io()
+ .exists(&rest.snapshot_manager().snapshot_path(snapshot.id()))
+ .await
+ .unwrap());
+ }
+ assert_eq!(
+ vectors(&rest).await.0[&anchor],
+ [42, 500].into_iter().collect()
+ );
+ let readable = rest.copy_with_options(HashMap::from([(
+ "deletion-vectors.merge-on-read".into(),
+ "true".into(),
+ )]));
+ assert_eq!(count_rows(&readable, 4000).await, usize::from(!unknown));
+ assert_eq!(count_rows(&readable, 42).await, 1);
+ assert_eq!(commit.commit_compact(vec![result]).await.unwrap(),
metrics);
+ assert_eq!(submitted.lock().unwrap().len(), attempts.len());
+ server.abort();
+ }
+
+ #[cfg(feature = "storage-fs")]
+ struct ReplayAfterRollback {
+ table: Table,
+ storage: SnapshotManager,
+ }
+
+ #[cfg(feature = "storage-fs")]
+ #[async_trait::async_trait]
+ impl SnapshotCommit for ReplayAfterRollback {
+ async fn commit(
+ &self,
+ _: Option<&str>,
+ snapshot: &Snapshot,
+ _: &str,
+ _: &[PartitionStatistics],
+ ) -> Result<bool> {
+ write(&self.table, vec![4000], 0).await;
+ let cached = self
+ .table
+ .snapshot_manager()
+ .get_snapshot(snapshot.id())
+ .await?;
+ assert_ne!(cached.uuid(), snapshot.uuid());
+ // A different client rolls back without invalidating our local
cache.
+ self.storage.write_latest_hint(snapshot.id() - 1).await?;
+ self.storage.delete_snapshot(snapshot.id()).await?;
+ assert!(self.storage.commit_snapshot(snapshot).await?);
+ self.storage.commit_snapshot(snapshot).await
}
}
+ #[cfg(feature = "storage-fs")]
#[tokio::test]
- async fn
compact_cas_loss_cleans_only_new_dv_but_publication_error_preserves_it() {
- for publish_first in [false, true] {
+ async fn
compact_replayed_publication_ignores_snapshot_cached_before_rollback() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().to_string_lossy().into_owned();
+ let (table, anchor, _) = fixture_at(path.clone()).await;
+ let storage =
+
SnapshotManager::new(FileIO::from_path(&path).unwrap().build().unwrap(), path);
+ assert!(table.file_io().has_local_cache());
+ write(&table, vec![42], 0).await;
+ let builder = table.new_compact_builder();
+ let plan = builder.new_planner().unwrap().plan().await.unwrap();
+ let result = builder
+ .new_executor()
+ .unwrap()
+ .execute(&plan.tasks()[0])
+ .await
+ .unwrap();
+ let mut commit = builder.new_commit().unwrap();
+ commit.snapshot_commit = Arc::new(ReplayAfterRollback {
+ table: table.clone(),
+ storage: storage.clone(),
+ });
+ commit.commit_max_retries = 0;
+ let outcome = commit.commit_compact(vec![result]).await;
+
+ let published = storage
+ .get_snapshot(plan.snapshot_id().unwrap() + 1)
+ .await
+ .unwrap();
+ assert_eq!(published.commit_kind(), &CommitKind::COMPACT);
+ let (masks, _) = crate::table::deletion_vector_index::read_bucket(
+ &table,
+ &EMPTY_SERIALIZED_ROW,
+ 0,
+ &published,
+ None,
+ )
+ .await
+ .expect("the published deletion-vector file must survive the replay");
+ assert_eq!(masks[&anchor], [42, 500].into_iter().collect());
+ outcome.unwrap();
+
+ let cached = table.copy_with_options(HashMap::from([(
+ "deletion-vectors.merge-on-read".into(),
+ "true".into(),
+ )]));
+ let fresh = Table::new(
+ storage.file_io().clone(),
+ cached.identifier().clone(),
+ cached.location().into(),
+ cached.schema().clone(),
+ None,
+ );
+ assert!(!fresh.file_io().has_local_cache());
+ for (reader, name) in [(&fresh, "fresh"), (&cached, "committing")] {
+ for (id, expected_rows) in [(4000, 0), (2001, 1)] {
+ assert_eq!(
+ count_rows(reader, id).await,
+ expected_rows,
+ "{name} reader, id={id}",
+ );
+ }
+ }
+ assert_eq!(
+ table
+ .snapshot_manager()
+ .get_latest_snapshot()
+ .await
+ .unwrap()
+ .unwrap()
+ .uuid(),
+ published.uuid(),
+ );
+ }
+
+ #[tokio::test]
+ async fn compact_unverified_publication_preserves_dv_for_recovery() {
+ check_compact_publications(&[
+ FirstPublication::Replay { legacy: true },
+ FirstPublication::Deferred,
+ ])
+ .await;
+ }
+
+ async fn check_compact_publications(cases: &[FirstPublication]) {
+ for &first in cases {
+ let conflict = matches!(first, FirstPublication::Conflict { .. });
+ let unverifiable = matches!(
+ first,
+ FirstPublication::Replay { legacy: true } |
FirstPublication::Deferred
+ );
let (table, anchor, unrelated) = fixture().await;
let old = table
.snapshot_manager()
@@ -238,24 +640,46 @@ mod pk_dv_retry {
let publisher = Arc::new(RacingCommit {
table: table.clone(),
calls: AtomicUsize::new(0),
- publish_first,
+ first,
+ deferred: std::sync::Mutex::new(None),
paths: std::sync::Mutex::new(vec![]),
});
let mut commit = builder.new_commit().unwrap();
commit.snapshot_commit = publisher.clone();
commit.commit_min_retry_wait_ms = 0;
commit.commit_max_retry_wait_ms = 0;
- let metrics =
commit.commit_compact(vec![result.clone()]).await.unwrap();
+ if unverifiable {
+ commit.commit_max_retries = 0;
+ }
+ let outcome = commit.commit_compact(vec![result.clone()]).await;
+ let manager = table.snapshot_manager();
+ let metrics = if unverifiable {
+ let error = outcome.unwrap_err();
+ assert!(
+ error.to_string().contains("Commit outcome may be
unknown"),
+ "{error}"
+ );
+ let deferred = publisher.deferred.lock().unwrap().take();
+ if let Some(snapshot) = deferred {
+ assert!(manager.commit_snapshot(&snapshot).await.unwrap());
+ }
+ let before = manager.get_latest_snapshot_id().await.unwrap();
+ let metrics =
commit.commit_compact(vec![result.clone()]).await.unwrap();
+ assert_eq!(manager.get_latest_snapshot_id().await.unwrap(),
before);
+ metrics
+ } else {
+ outcome.unwrap()
+ };
assert_eq!(
publisher.calls.load(Ordering::SeqCst),
- if publish_first { 1 } else { 2 }
+ if conflict { 2 } else { 1 }
);
let attempts = publisher.paths.lock().unwrap().clone();
assert_eq!(attempts[0].len(), 1);
assert!(!original_paths.contains(&attempts[0][0]));
assert_eq!(
table.file_io().exists(&attempts[0][0]).await.unwrap(),
- publish_first
+ !conflict
);
for path in original_paths.iter().chain(attempts.last().unwrap()) {
assert!(
@@ -269,6 +693,13 @@ mod pk_dv_retry {
assert!(table.file_io().exists(&path).await.unwrap());
}
}
+ let published =
manager.get_latest_snapshot().await.unwrap().unwrap();
+ assert_eq!(*published.commit_kind(), CommitKind::COMPACT);
+ assert!(!commit
+ .read_delta_entries(None, &published)
+ .await
+ .unwrap()
+ .is_empty());
let masks = vectors(&table).await.0;
assert_eq!(masks[&anchor], [42, 500].into_iter().collect());
assert_eq!(masks[&unrelated], [0].into_iter().collect());
diff --git a/crates/paimon/src/table/table_commit/recovery_tests.rs
b/crates/paimon/src/table/table_commit/recovery_tests.rs
index 8210166d..a50efee4 100644
--- a/crates/paimon/src/table/table_commit/recovery_tests.rs
+++ b/crates/paimon/src/table/table_commit/recovery_tests.rs
@@ -588,7 +588,8 @@ async fn
rest_delete_writer_pins_catalog_snapshot_and_preserves_vectors() {
use arrow_array::{Array, Int32Array, RecordBatch, StringArray};
use axum::{
body::Bytes,
- http::{Method, Uri},
+ http::{Method, StatusCode, Uri},
+ response::IntoResponse,
Json, Router,
};
use futures::TryStreamExt;
@@ -645,15 +646,18 @@ async fn
rest_delete_writer_pins_catalog_snapshot_and_preserves_vectors() {
let next: Snapshot =
serde_json::from_value(request["snapshot"].clone()).unwrap();
assert_eq!(next.id(), snapshot.lock().unwrap().id() + 1);
*snapshot.lock().unwrap() = next;
- // Force the retry/deduplication path after catalog
publication.
- serde_json::json!({"success": false})
+ // The publication succeeded, but its response was lost.
+ return (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(serde_json::json!({"code": 500, "message": "lost
commit response"})),
+ ).into_response();
} else if uri.path().ends_with("/snapshot") {
loads.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
serde_json::json!({"snapshot": {"snapshot":
*snapshot.lock().unwrap(), "recordCount": 10}})
} else {
serde_json::json!({"schemaId": 0})
};
- Json(response)
+ Json(response).into_response()
}
});
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();