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 1a14e364 fix: route REST table tag procedures and reads through
catalog (#1348)
1a14e364 is described below
commit 1a14e364585c9d1e19a400b5e5dc5e1a2912254f
Author: Nicholas Jiang <[email protected]>
AuthorDate: Wed Nov 11 11:01:36 2026 +0800
fix: route REST table tag procedures and reads through catalog (#1348)
---
crates/integrations/datafusion/src/procedures.rs | 88 +-
.../src/system_tables/referenced_files_size.rs | 14 +-
crates/integrations/datafusion/tests/procedures.rs | 2 +-
.../datafusion/tests/rest_management_procedures.rs | 930 +++++++++++++++++++--
crates/paimon-rest-server/README.md | 7 +
crates/paimon-rest-server/src/lib.rs | 20 +
crates/paimon-rest-server/tests/e2e.rs | 51 ++
crates/paimon/src/api/rest_api.rs | 54 +-
crates/paimon/src/catalog/rest/rest_catalog.rs | 15 +-
crates/paimon/src/table/mod.rs | 3 +-
crates/paimon/src/table/referenced_files.rs | 110 ++-
crates/paimon/src/table/rest_env.rs | 62 +-
crates/paimon/src/table/tag_manager.rs | 216 ++++-
crates/paimon/src/table/time_travel.rs | 71 +-
crates/paimon/tests/mock_server.rs | 234 +++++-
crates/paimon/tests/rest_branch_test.rs | 113 ++-
.../tests/rest_catalog/read_path_completion.rs | 34 +-
docs/src/sql.md | 72 +-
18 files changed, 1894 insertions(+), 202 deletions(-)
diff --git a/crates/integrations/datafusion/src/procedures.rs
b/crates/integrations/datafusion/src/procedures.rs
index 6c614cb9..7ee17421 100644
--- a/crates/integrations/datafusion/src/procedures.rs
+++ b/crates/integrations/datafusion/src/procedures.rs
@@ -672,6 +672,27 @@ async fn proc_create_tag(
.transpose()?;
let time_retained = args.get("time_retained").map(String::as_str);
+ // The REST catalog owns tag metadata and resolves the snapshot itself,
+ // including the latest one when `snapshot_id` is omitted.
+ if let Some(rest_env) = table.rest_env() {
+ return match catalog
+ .create_tag_with_retention(
+ rest_env.identifier(),
+ tag_name,
+ snapshot_id,
+ time_retained,
+ false,
+ )
+ .await
+ {
+ Ok(()) => ok_result(ctx),
+ Err(paimon::Error::TagAlreadyExist { .. }) =>
Err(DataFusionError::Plan(format!(
+ "Tag '{tag_name}' already exists"
+ ))),
+ Err(error) => Err(to_datafusion_error(error)),
+ };
+ }
+
let (sm, tm) = managers(&table);
if tm.tag_exists(tag_name).await.map_err(to_datafusion_error)? {
return Err(DataFusionError::Plan(format!(
@@ -948,17 +969,27 @@ async fn proc_delete_tag(
) -> DFResult<DataFrame> {
let table = get_table(catalog, catalog_name, args).await?;
let tag_str = require_arg(args, "tag")?;
+ let tag_names: Vec<&str> = tag_str
+ .split(',')
+ .map(str::trim)
+ .filter(|name| !name.is_empty())
+ .collect();
+ if let Some(rest_env) = table.rest_env() {
+ for tag_name in tag_names {
+ // Skip missing tags, as the filesystem path does.
+ catalog
+ .delete_tag(rest_env.identifier(), tag_name, true)
+ .await
+ .map_err(to_datafusion_error)?;
+ }
+ return ok_result(ctx);
+ }
let (_, tm) = managers(&table);
- for tag_name in tag_str.split(',') {
- let tag_name = tag_name.trim();
- if tag_name.is_empty() {
- continue;
- }
- if !tm.tag_exists(tag_name).await.map_err(to_datafusion_error)? {
- continue;
+ for tag_name in tag_names {
+ if tm.tag_exists(tag_name).await.map_err(to_datafusion_error)? {
+ tm.delete(tag_name).await.map_err(to_datafusion_error)?;
}
- tm.delete(tag_name).await.map_err(to_datafusion_error)?;
}
ok_result(ctx)
}
@@ -973,6 +1004,14 @@ async fn proc_rename_tag(
let tag_name = require_arg(args, "tag")?;
let target_tag_name = require_arg(args, "target_tag")?;
+ // The REST catalog owns tag metadata and has no rename endpoint. Renaming
+ // storage files would leave the catalog listing the old name.
+ if table.rest_env().is_some() {
+ return Err(DataFusionError::NotImplemented(
+ "rename_tag is not supported for tables managed by a REST
catalog".to_string(),
+ ));
+ }
+
let (_, tm) = managers(&table);
tm.rename(tag_name, target_tag_name)
.await
@@ -1115,27 +1154,22 @@ async fn proc_rollback_to_timestamp(
.parse()
.map_err(|_| DataFusionError::Plan(format!("Invalid timestamp:
'{ts_str}'")))?;
+ // REST snapshots may exist only in the catalog; storage listings cannot
+ // enumerate the authoritative history needed for timestamp selection.
+ if table.rest_env().is_some() {
+ return Err(DataFusionError::NotImplemented(
+ "rollback_to_timestamp is not supported for tables managed by a
REST catalog"
+ .to_string(),
+ ));
+ }
+
let (sm, tm) = managers(&table);
let snapshot = earlier_or_equal_from_all(&sm, &tm, timestamp)
.await?
.ok_or_else(|| {
DataFusionError::Plan(format!("No snapshot found with commit time
<= {timestamp}"))
})?;
-
- if let Some(rest_env) = table.rest_env() {
- rest_env
- .api()
- .rollback_to(
- rest_env.identifier(),
- &paimon::table::Instant::snapshot(snapshot.id()),
- None,
- Some(rest_env.uuid()),
- )
- .await
- .map_err(to_datafusion_error)?;
- } else {
- clean_larger_than(&sm, &tm, snapshot.id()).await?;
- }
+ clean_larger_than(&sm, &tm, snapshot.id()).await?;
ok_result(ctx)
}
@@ -1152,6 +1186,14 @@ async fn proc_create_tag_from_timestamp(
.parse()
.map_err(|_| DataFusionError::Plan(format!("Invalid timestamp:
'{ts_str}'")))?;
+ // Same limitation as rollback_to_timestamp.
+ if table.rest_env().is_some() {
+ return Err(DataFusionError::NotImplemented(
+ "create_tag_from_timestamp is not supported for tables managed by
a REST catalog"
+ .to_string(),
+ ));
+ }
+
let (sm, tm) = managers(&table);
let snapshot = later_or_equal_from_all(&sm, &tm, timestamp)
.await?
diff --git
a/crates/integrations/datafusion/src/system_tables/referenced_files_size.rs
b/crates/integrations/datafusion/src/system_tables/referenced_files_size.rs
index db09d0e7..0ce1393f 100644
--- a/crates/integrations/datafusion/src/system_tables/referenced_files_size.rs
+++ b/crates/integrations/datafusion/src/system_tables/referenced_files_size.rs
@@ -29,7 +29,7 @@ use datafusion::error::Result as DFResult;
use datafusion::logical_expr::Expr;
use datafusion::physical_plan::ExecutionPlan;
use paimon::table::referenced_files::{
- collect_referenced_files_summary_with_options, ReferencedFilesSummary,
+ collect_table_referenced_files_summary, ReferencedFilesSummary,
};
use paimon::table::Table;
@@ -80,17 +80,7 @@ impl TableProvider for ReferencedFilesSizeTable {
) -> DFResult<Arc<dyn ExecutionPlan>> {
let table = self.table.clone();
let summaries = crate::runtime::await_with_runtime(async move {
- let schema = table.schema();
- let partition_keys = schema.partition_keys();
- let partition_fields = schema.partition_fields();
- collect_referenced_files_summary_with_options(
- table.file_io(),
- table.location(),
- partition_keys,
- &partition_fields,
- &schema.core_options(),
- )
- .await
+ collect_table_referenced_files_summary(&table).await
})
.await
.map_err(to_datafusion_error)?;
diff --git a/crates/integrations/datafusion/tests/procedures.rs
b/crates/integrations/datafusion/tests/procedures.rs
index b1594f96..70243a7c 100644
--- a/crates/integrations/datafusion/tests/procedures.rs
+++ b/crates/integrations/datafusion/tests/procedures.rs
@@ -2708,7 +2708,7 @@ async fn test_delete_multiple_tags() {
exec(
&sql_context,
- "CALL sys.delete_tag(table => 'test_db.t1', tag => 'v1,v2')",
+ "CALL sys.delete_tag(table => 'test_db.t1', tag => ' v1, missing,,v2
')",
)
.await;
diff --git a/crates/integrations/datafusion/tests/rest_management_procedures.rs
b/crates/integrations/datafusion/tests/rest_management_procedures.rs
index d3ea23e3..8c317428 100644
--- a/crates/integrations/datafusion/tests/rest_management_procedures.rs
+++ b/crates/integrations/datafusion/tests/rest_management_procedures.rs
@@ -25,7 +25,7 @@ use std::path::{Path, PathBuf};
use std::sync::Arc;
use arrow_array::{Array, RecordBatch};
-use paimon::api::ConfigResponse;
+use paimon::api::{ConfigResponse, CreateTagRequest};
use paimon::catalog::RESTCatalog;
use paimon::spec::{DataType, IntType, Schema};
use paimon::{CatalogOptions, Options};
@@ -37,20 +37,20 @@ const DATABASE: &str = "sales";
const TABLE: &str = "orders";
const WAREHOUSE: &str = "test_warehouse";
-async fn setup() -> (tempfile::TempDir, RESTServer, SQLContext) {
- let temp_dir = tempfile::tempdir().unwrap();
- let server = start_mock_server(
+async fn start_server(warehouse: &Path) -> RESTServer {
+ start_mock_server(
WAREHOUSE.to_string(),
- temp_dir.path().to_string_lossy().into_owned(),
+ warehouse.to_string_lossy().into_owned(),
ConfigResponse::new(HashMap::from([(
CatalogOptions::PREFIX.to_string(),
"mock-test".to_string(),
)])),
vec![DATABASE.to_string()],
)
- .await;
- server.add_table(DATABASE, TABLE);
+ .await
+}
+async fn connect(server: &RESTServer) -> (Arc<RESTCatalog>, SQLContext) {
let mut options = Options::new();
options.set(CatalogOptions::URI, server.url().unwrap());
options.set(CatalogOptions::WAREHOUSE, WAREHOUSE);
@@ -58,7 +58,18 @@ async fn setup() -> (tempfile::TempDir, RESTServer,
SQLContext) {
options.set(CatalogOptions::TOKEN, "test-token");
let catalog = Arc::new(RESTCatalog::new(options, true).await.unwrap());
let mut context = SQLContext::new();
- context.register_catalog("paimon", catalog).await.unwrap();
+ context
+ .register_catalog("paimon", catalog.clone())
+ .await
+ .unwrap();
+ (catalog, context)
+}
+
+async fn setup() -> (tempfile::TempDir, RESTServer, SQLContext) {
+ let temp_dir = tempfile::tempdir().unwrap();
+ let server = start_server(temp_dir.path()).await;
+ server.add_table(DATABASE, TABLE);
+ let (_, context) = connect(&server).await;
(temp_dir, server, context)
}
@@ -685,36 +696,6 @@ async fn
test_consumer_procedures_rejected_on_rest_catalog_without_changing_prog
assert_eq!(std::fs::read(&consumer_path).unwrap(), original);
}
-#[tokio::test]
-async fn test_replace_tag_rejected_on_rest_catalog_without_changing_metadata()
{
- let (tmp, server, context) = setup().await;
- let schema = Schema::builder()
- .column("id", DataType::Int(IntType::new()))
- .build()
- .unwrap();
- let path = format!("file://{}/{DATABASE}.db/{TABLE}",
tmp.path().display());
- server.add_table_with_schema(DATABASE, TABLE, schema, &path);
- let tag_dir = tmp.path().join(format!("{DATABASE}.db/{TABLE}/tag"));
- std::fs::create_dir_all(&tag_dir).unwrap();
- let tag_path = tag_dir.join("tag-release");
- // Invalid metadata must remain unread: REST rejection precedes storage
access.
- let original = b"{";
- std::fs::write(&tag_path, original).unwrap();
-
- for snapshot in ["", ", snapshot_id => 1"] {
- common::assert_sql_error(
- &context,
- &format!(
- "CALL sys.replace_tag(table => '{DATABASE}.{TABLE}', tag =>
'release'{snapshot})"
- ),
- "replace_tag is not supported for tables managed by a REST
catalog",
- )
- .await;
- assert_eq!(std::fs::read(&tag_path).unwrap(), original);
- assert_eq!(std::fs::read_dir(&tag_dir).unwrap().count(), 1);
- }
-}
-
fn register_rest_table(
tmp: &tempfile::TempDir,
server: &RESTServer,
@@ -1080,8 +1061,838 @@ async fn test_rename_branch_rejected_on_rest_catalog() {
.await;
}
+fn tag_names(server: &RESTServer) -> Vec<String> {
+ server
+ .tags(DATABASE, TABLE)
+ .into_iter()
+ .map(|tag| tag.tag_name)
+ .collect()
+}
+
+#[tokio::test]
+async fn test_create_tag_goes_through_rest_catalog() {
+ let (tmp, server, context) = setup().await;
+ let root = register_rest_table(&tmp, &server, &[]);
+ let storage_only = root.join("tag/tag-stale");
+ std::fs::create_dir_all(storage_only.parent().unwrap()).unwrap();
+ std::fs::write(&storage_only, b"{").unwrap();
+ let original_files = table_files(&root);
+ let create = |args: &str| format!("CALL sys.create_tag(table =>
'{DATABASE}.{TABLE}', {args})");
+
+ for args in [
+ "tag => 'latest'",
+ "tag => 'stale'",
+ "tag => 'retained', time_retained => ' 12 HOURS '",
+ "tag => ' keep +一', snapshot_id => 1, time_retained => '1d'",
+ ] {
+ let sql = create(args);
+ assert_ok_row(&context, &sql).await;
+ assert_eq!(table_files(&root), original_files, "{sql}");
+ }
+ let tags = server.tags(DATABASE, TABLE);
+ let summary: Vec<_> = tags
+ .iter()
+ .map(|tag| {
+ (
+ tag.tag_name.as_str(),
+ tag.snapshot.id(),
+ tag.tag_time_retained.as_deref(),
+ )
+ })
+ .collect();
+ assert_eq!(
+ summary,
+ [
+ (" keep +一", 1, Some("1d")),
+ ("latest", 1, None),
+ ("retained", 1, Some(" 12 HOURS ")),
+ ("stale", 1, None),
+ ]
+ );
+
+ for (args, message) in [
+ (
+ "tag => 'retained', snapshot_id => 1, time_retained => '2d'",
+ "Tag 'retained' already exists",
+ ),
+ (
+ "tag => 'other', snapshot_id => 2",
+ "Snapshot 2 does not exist",
+ ),
+ ("tag => '.'", "tag name must not be a dot path segment"),
+ ("tag => '..'", "tag name must not be a dot path segment"),
+ ] {
+ let sql = create(args);
+ common::assert_sql_error(&context, &sql, message).await;
+ assert_eq!(server.tags(DATABASE, TABLE), tags, "{sql}");
+ assert_eq!(table_files(&root), original_files, "{sql}");
+ }
+
+ let request = |tag: &str, snapshot_id, retention: Option<&str>| {
+ (
+ DATABASE.to_string(),
+ TABLE.to_string(),
+ CreateTagRequest {
+ tag_name: tag.to_string(),
+ snapshot_id,
+ time_retained: retention.map(str::to_string),
+ },
+ )
+ };
+ assert_eq!(
+ server.create_tag_calls(),
+ [
+ request("latest", None, None),
+ request("stale", None, None),
+ request("retained", None, Some(" 12 HOURS ")),
+ request(" keep +一", Some(1), Some("1d")),
+ request("retained", Some(1), Some("2d")),
+ request("other", Some(2), None),
+ ]
+ );
+}
+
+#[tokio::test]
+async fn test_delete_tag_goes_through_rest_catalog() {
+ let (tmp, server, context) = setup().await;
+ let root = register_rest_table(&tmp, &server, &[]);
+ for tag in ["v1", "v2", "keep", "a+b c"] {
+ server.add_tag(DATABASE, TABLE, tag);
+ }
+ let tag_dir = root.join("tag");
+ std::fs::create_dir_all(&tag_dir).unwrap();
+ std::fs::write(tag_dir.join("tag-v1"), b"{").unwrap();
+ std::fs::write(tag_dir.join("tag-storage_only"), b"{").unwrap();
+ let original_files = table_files(&root);
+ let delete =
+ |tags: &str| format!("CALL sys.delete_tag(table =>
'{DATABASE}.{TABLE}', tag => '{tags}')");
+ let call = |tag: &str| (DATABASE.to_string(), TABLE.to_string(),
tag.to_string());
+
+ assert_ok_row(&context, &delete("v1, missing,,a+b c ,v1")).await;
+ assert_eq!(tag_names(&server), ["keep", "v2"]);
+ let mut expected_calls: Vec<_> = ["v1", "missing", "a+b c",
"v1"].map(call).to_vec();
+ assert_eq!(server.delete_tag_calls(), expected_calls);
+ assert_eq!(table_files(&root), original_files);
+
+ assert_ok_row(&context, &delete("storage_only")).await;
+ expected_calls.push(call("storage_only"));
+ assert_eq!(server.delete_tag_calls(), expected_calls);
+ assert_eq!(table_files(&root), original_files);
+
+ assert_ok_row(&context, &delete(" , ,")).await;
+ assert_eq!(server.delete_tag_calls(), expected_calls);
+ assert_eq!(tag_names(&server), ["keep", "v2"]);
+ assert_eq!(table_files(&root), original_files);
+
+ common::assert_sql_error(
+ &context,
+ &delete("keep,..,v2"),
+ "tag name must not be a dot path segment",
+ )
+ .await;
+ expected_calls.push(call("keep"));
+ assert_eq!(server.delete_tag_calls(), expected_calls);
+ assert_eq!(tag_names(&server), ["v2"]);
+ assert_eq!(table_files(&root), original_files);
+}
+
+async fn rest_table_with_two_snapshots() -> (
+ tempfile::TempDir,
+ RESTServer,
+ Arc<RESTCatalog>,
+ SQLContext,
+ PathBuf,
+) {
+ use paimon::catalog::Identifier;
+ use paimon::Catalog;
+
+ let (tmp, fs_catalog) = common::create_test_env();
+ let identifier = Identifier::new(DATABASE, TABLE);
+ let schema = Schema::builder()
+ .column("id", DataType::Int(IntType::new()))
+ .build()
+ .unwrap();
+ fs_catalog
+ .create_database(DATABASE, false, HashMap::new())
+ .await
+ .unwrap();
+ fs_catalog
+ .create_table(&identifier, schema.clone(), false)
+ .await
+ .unwrap();
+ let writer = common::create_sql_context(fs_catalog.clone()).await;
+ for id in [1, 2] {
+ common::exec(
+ &writer,
+ &format!("INSERT INTO paimon.{DATABASE}.{TABLE} VALUES ({id})"),
+ )
+ .await;
+ }
+ let location = fs_catalog
+ .get_table(&identifier)
+ .await
+ .unwrap()
+ .location()
+ .to_string();
+ let root = tmp.path().join(format!("{DATABASE}.db/{TABLE}"));
+ let server = start_server(tmp.path()).await;
+ server.add_table_with_schema(DATABASE, TABLE, schema, &location);
+ let (catalog, context) = connect(&server).await;
+ (tmp, server, catalog, context, root)
+}
+
+fn write_storage_tag(root: &Path, tag: &str, snapshot_id: i64) {
+ let tag_dir = root.join("tag");
+ std::fs::create_dir_all(&tag_dir).unwrap();
+ std::fs::copy(
+ root.join(format!("snapshot/snapshot-{snapshot_id}")),
+ tag_dir.join(format!("tag-{tag}")),
+ )
+ .unwrap();
+}
+
+fn id_rows(ids: &[&str]) -> Vec<Vec<Option<String>>> {
+ ids.iter().map(|id| vec![Some(id.to_string())]).collect()
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn test_tag_reads_go_through_rest_catalog() {
+ use paimon::catalog::Identifier;
+ use paimon::Catalog;
+
+ let (_tmp, server, catalog, context, root) =
rest_table_with_two_snapshots().await;
+ write_storage_tag(&root, "release", 2);
+ write_storage_tag(&root, "storage_only", 1);
+ let catalog_latest_path = root.join("snapshot/snapshot-2");
+ let catalog_latest: paimon::spec::Snapshot =
+
serde_json::from_slice(&std::fs::read(&catalog_latest_path).unwrap()).unwrap();
+ server.set_catalog_snapshot(DATABASE, TABLE, catalog_latest.clone());
+ std::fs::remove_file(catalog_latest_path).unwrap();
+
+ let original_files = table_files(&root);
+ for args in [
+ "tag => 'release', snapshot_id => 1",
+ "tag => 'catalog_only'",
+ "tag => 'retained', snapshot_id => 1, time_retained => '1d'",
+ ] {
+ assert_ok_row(
+ &context,
+ &format!("CALL sys.create_tag(table => '{DATABASE}.{TABLE}',
{args})"),
+ )
+ .await;
+ }
+ assert_eq!(table_files(&root), original_files);
+ let catalog_only = server
+ .tags(DATABASE, TABLE)
+ .into_iter()
+ .find(|tag| tag.tag_name == "catalog_only")
+ .unwrap();
+ assert_eq!(catalog_only.snapshot, catalog_latest);
+
+ std::fs::remove_file(root.join("snapshot/snapshot-1")).unwrap();
+ let original_files = table_files(&root);
+
+ let tags_sql = format!(
+ "SELECT tag_name, CAST(snapshot_id AS VARCHAR) AS snapshot,
time_retained \
+ FROM paimon.{DATABASE}.`{TABLE}$tags` ORDER BY tag_name"
+ );
+ let row = |tag: &str, snapshot: &str, retained: Option<&str>| {
+ vec![
+ Some(tag.to_string()),
+ Some(snapshot.to_string()),
+ retained.map(str::to_string),
+ ]
+ };
+ assert_eq!(
+ rows(&call(&context, &tags_sql).await),
+ [
+ row("catalog_only", "2", None),
+ row("release", "1", None),
+ row("retained", "1", Some("PT24H")),
+ ]
+ );
+
+ let select_ids = |clause: &str| {
+ format!(
+ "SELECT CAST(id AS VARCHAR) AS id_text FROM
paimon.{DATABASE}.{TABLE} \
+ {clause} ORDER BY id_text"
+ )
+ };
+ let ids = |version: &str| select_ids(&format!("VERSION AS OF
'{version}'"));
+ assert_eq!(
+ rows(&call(&context, &ids("release")).await),
+ id_rows(&["1"])
+ );
+ assert_eq!(
+ rows(&call(&context, &ids("catalog_only")).await),
+ id_rows(&["1", "2"])
+ );
+ common::assert_sql_error(&context, &ids("storage_only"),
"storage_only").await;
+
+ call(&context, "SET 'paimon.scan.tag-name' = 'release'").await;
+ assert_eq!(
+ rows(&call(&context, &select_ids("")).await),
+ id_rows(&["1"])
+ );
+ call(&context, "RESET 'paimon.scan.tag-name'").await;
+
+ let tag_manager = catalog
+ .get_table(&Identifier::new(DATABASE, TABLE))
+ .await
+ .unwrap()
+ .tag_manager();
+ let snapshot = tag_manager.get("release").await.unwrap().unwrap();
+ assert_eq!(snapshot.id(), 1);
+ for result in [
+ tag_manager.create("blocked", &snapshot).await,
+ tag_manager.replace("release", &snapshot, None).await,
+ tag_manager.rename("release", "blocked").await,
+ tag_manager.delete("catalog_only").await,
+ ] {
+ let error = result.unwrap_err();
+ assert!(
+ matches!(error, paimon::Error::Unsupported { .. }),
+ "{error}"
+ );
+ }
+ assert_eq!(tag_names(&server), ["catalog_only", "release", "retained"]);
+ assert_eq!(table_files(&root), original_files);
+
+ assert_ok_row(
+ &context,
+ &format!("CALL sys.delete_tag(table => '{DATABASE}.{TABLE}', tag =>
'release')"),
+ )
+ .await;
+ assert_eq!(table_files(&root), original_files);
+ common::assert_sql_error(&context, &ids("release"), "release").await;
+ assert_eq!(
+ rows(&call(&context, &tags_sql).await),
+ [
+ row("catalog_only", "2", None),
+ row("retained", "1", Some("PT24H")),
+ ]
+ );
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn test_snapshot_versions_resolve_without_rest_tag_endpoint() {
+ use paimon::catalog::Identifier;
+ use paimon::Catalog;
+
+ let (_tmp, server, catalog, context, root) =
rest_table_with_two_snapshots().await;
+ for id in [1, 2] {
+ let path = root.join(format!("snapshot/snapshot-{id}"));
+ let mut snapshot: serde_json::Value =
+ serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
+ snapshot["watermark"] = serde_json::json!(id * 1000);
+ std::fs::write(path, serde_json::to_vec(&snapshot).unwrap()).unwrap();
+ }
+ for tag in ["2", "watermark-2000"] {
+ assert_ok_row(
+ &context,
+ &format!(
+ "CALL sys.create_tag(table => '{DATABASE}.{TABLE}', tag =>
'{tag}', snapshot_id => 1)"
+ ),
+ )
+ .await;
+ }
+ let original_files = table_files(&root);
+ let table = catalog
+ .get_table(&Identifier::new(DATABASE, TABLE))
+ .await
+ .unwrap();
+ for version in ["2", "watermark-2000"] {
+ let calls_before = server.get_tag_calls().len();
+ let view = table
+ .copy_with_time_travel_strict(HashMap::from([(
+ "scan.version".to_string(),
+ version.to_string(),
+ )]))
+ .await
+ .unwrap();
+ assert_eq!(
+ view.travel_snapshot().map(|snapshot| snapshot.id()),
+ Some(1)
+ );
+ assert_eq!(
+ &server.get_tag_calls()[calls_before..],
+ &[(DATABASE.to_string(), TABLE.to_string(), version.to_string())]
+ );
+ }
+ let versions = ["2", "'watermark-2000'"].map(|version| {
+ format!(
+ "SELECT CAST(id AS VARCHAR) AS id_text FROM
paimon.{DATABASE}.{TABLE} \
+ VERSION AS OF {version} ORDER BY id_text"
+ )
+ });
+
+ for sql in &versions {
+ assert_eq!(rows(&call(&context, sql).await), id_rows(&["1"]), "{sql}");
+ }
+ server.set_tag_read_error(Some(error_response(501, "tags unsupported")));
+ for sql in &versions {
+ assert_eq!(
+ rows(&call(&context, sql).await),
+ id_rows(&["1", "2"]),
+ "{sql}"
+ );
+ }
+ let error = table
+ .copy_with_time_travel_strict(HashMap::from([(
+ "scan.tag-name".to_string(),
+ "2".to_string(),
+ )]))
+ .await
+ .unwrap_err();
+ assert!(error.to_string().contains("tags unsupported"), "{error}");
+ server.set_tag_read_error(Some(error_response(403, "tag access denied")));
+ for sql in &versions {
+ common::assert_sql_error(&context, sql, "tag access denied").await;
+ }
+ assert_eq!(table_files(&root), original_files);
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn test_referenced_files_size_counts_rest_catalog_tags() {
+ let (_tmp, server, _catalog, context, root) =
rest_table_with_two_snapshots().await;
+ let sql = format!(
+ "SELECT CAST(manifest_file_count AS VARCHAR), CAST(manifest_file_size
AS VARCHAR), \
+ CAST(data_file_count AS VARCHAR), CAST(data_file_size AS VARCHAR), \
+ CAST(index_file_count AS VARCHAR), CAST(index_file_size AS VARCHAR) \
+ FROM paimon.{DATABASE}.`{TABLE}$referenced_files_size` WHERE source =
'total'"
+ );
+ let files = table_files(&root);
+ let count_and_size = |dir: &str| {
+ let sizes: Vec<_> = files
+ .iter()
+ .filter(|(path, _)| path.starts_with(root.join(dir)))
+ .map(|(_, content)| content.len())
+ .collect();
+ (sizes.len(), sizes.iter().sum::<usize>())
+ };
+ let (manifest_count, manifest_size) = count_and_size("manifest");
+ let (data_count, data_size) = count_and_size("bucket-0");
+ assert_eq!((manifest_count, data_count), (6, 2));
+ let expected = vec![[manifest_count, manifest_size, data_count, data_size,
0, 0]
+ .map(|value| Some(value.to_string()))
+ .to_vec()];
+ assert_eq!(rows(&call(&context, &sql).await), expected);
+
+ assert_ok_row(
+ &context,
+ &format!(
+ "CALL sys.create_tag(table => '{DATABASE}.{TABLE}', tag => 'keep',
snapshot_id => 1)"
+ ),
+ )
+ .await;
+ assert!(!root.join("tag/tag-keep").exists());
+ std::fs::remove_file(root.join("snapshot/snapshot-1")).unwrap();
+ let original_files = table_files(&root);
+ assert_eq!(rows(&call(&context, &sql).await), expected);
+
+ for (code, message) in [(403, "tag access denied"), (501, "tags
unsupported")] {
+ server.set_tag_read_error(Some(error_response(code, message)));
+ common::assert_sql_error(&context, &sql, message).await;
+ assert_eq!(tag_names(&server), ["keep"]);
+ assert_eq!(table_files(&root), original_files);
+ }
+ server.set_tag_read_error(None);
+ assert_eq!(rows(&call(&context, &sql).await), expected);
+ assert_eq!(table_files(&root), original_files);
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn test_referenced_files_size_counts_catalog_only_branch_tags() {
+ use paimon::catalog::Identifier;
+ use paimon::Catalog;
+
+ let (_tmp, server, catalog, context, root) =
rest_table_with_two_snapshots().await;
+ let summary = |table: &str, columns: &str, filter: &str| {
+ format!("SELECT {columns} FROM
paimon.{DATABASE}.`{table}$referenced_files_size` {filter}")
+ };
+ let counts = "CAST(manifest_file_count AS VARCHAR), CAST(data_file_count
AS VARCHAR)";
+ let sql = summary(TABLE, counts, "WHERE source = 'total'");
+ let before = rows(&call(&context, &sql).await);
+
+ let branch_table = format!("{TABLE}$branch_dev");
+ let schema = Schema::builder()
+ .column("id", DataType::Int(IntType::new()))
+ .build()
+ .unwrap();
+ server.add_table_with_schema(
+ DATABASE,
+ &branch_table,
+ schema,
+ &format!("file://{}", root.display()),
+ );
+ for name in ["dev", "main", "dev"] {
+ server.add_branch(DATABASE, TABLE, name);
+ }
+ let identifier = Identifier::new(DATABASE, &branch_table);
+ catalog
+ .create_tag(&identifier, "keep", Some(1), false)
+ .await
+ .unwrap();
+ let branch = catalog.get_table(&identifier).await.unwrap();
+ assert_eq!(
+ branch
+ .tag_manager()
+ .get("keep")
+ .await
+ .unwrap()
+ .unwrap()
+ .id(),
+ 1
+ );
+ assert!(!root.join("branch/branch-dev").exists());
+ std::fs::remove_file(root.join("snapshot/snapshot-1")).unwrap();
+
+ let stale_branch = root.join("branch/branch-stale/snapshot");
+ std::fs::create_dir_all(&stale_branch).unwrap();
+ std::fs::write(stale_branch.join("snapshot-1"), b"{").unwrap();
+ let original_files = table_files(&root);
+ let expected_scopes =
+ ["branch:dev", "branch:main", "total"].map(|source|
vec![Some(source.to_string())]);
+ for table in [TABLE, branch_table.as_str()] {
+ assert_eq!(
+ rows(&call(&context, &summary(table, counts, "WHERE source =
'total'")).await),
+ before
+ );
+ assert_eq!(
+ rows(&call(&context, &summary(table, "source", "ORDER BY
source")).await),
+ expected_scopes
+ );
+ }
+ for (code, message) in [(403, "branch access denied"), (501, "branches
unsupported")] {
+ server.set_list_branches_error(Some(error_response(code, message)));
+ common::assert_sql_error(&context, &sql, message).await;
+ }
+ assert_eq!(table_files(&root), original_files);
+}
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn test_create_tag_from_watermark_rejects_readable_rest_catalog_table() {
+async fn test_referenced_files_size_counts_catalog_only_current_snapshots() {
+ let (_tmp, server, _catalog, context, root) =
rest_table_with_two_snapshots().await;
+ let sql = format!(
+ "SELECT CAST(manifest_file_count AS VARCHAR), CAST(data_file_count AS
VARCHAR) \
+ FROM paimon.{DATABASE}.`{TABLE}$referenced_files_size` WHERE source =
'total'"
+ );
+ let before = rows(&call(&context, &sql).await);
+ let snapshot = |id| -> paimon::spec::Snapshot {
+ serde_json::from_slice(
+
&std::fs::read(root.join(format!("snapshot/snapshot-{id}"))).unwrap(),
+ )
+ .unwrap()
+ };
+ let first = snapshot(1);
+ let second = snapshot(2);
+ server.set_catalog_snapshot(DATABASE, TABLE, second.clone());
+ std::fs::remove_file(root.join("snapshot/snapshot-2")).unwrap();
+ let original_files = table_files(&root);
+ assert_eq!(rows(&call(&context, &sql).await), before);
+
+ let branch_table = format!("{TABLE}$branch_dev");
+ let schema = Schema::builder()
+ .column("id", DataType::Int(IntType::new()))
+ .build()
+ .unwrap();
+ server.add_table_with_schema(
+ DATABASE,
+ &branch_table,
+ schema,
+ &format!("file://{}", root.display()),
+ );
+ server.add_branch(DATABASE, TABLE, "dev");
+ server.set_catalog_snapshot(DATABASE, TABLE, first);
+ server.set_catalog_snapshot(DATABASE, &branch_table, second);
+ assert!(!root.join("branch/branch-dev").exists());
+ assert_eq!(rows(&call(&context, &sql).await), before);
+ assert_eq!(table_files(&root), original_files);
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn test_referenced_files_size_rejects_unaddressable_catalog_branches() {
+ for (name, message) in [
+ ("..", "branch name cannot be '.' or '..'"),
+ ("../escape", "branch name cannot contain path separators"),
+ ("dev$tags", "unaddressable branch name"),
+ ] {
+ let (tmp, server, context) = setup().await;
+ let root = register_rest_table(&tmp, &server, &[]);
+ server.add_branch(DATABASE, TABLE, name);
+ let original_files = table_files(&root);
+ let sql = format!("SELECT * FROM
paimon.{DATABASE}.`{TABLE}$referenced_files_size`");
+ common::assert_sql_error(&context, &sql, message).await;
+ assert_eq!(table_files(&root), original_files);
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn test_legacy_dot_segment_tags_on_rest_tables() {
+ use paimon::catalog::Identifier;
+ use paimon::Catalog;
+
+ const DOT_SEGMENT: &str = "tag name must not be a dot path segment";
+ let (_tmp, server, catalog, context, root) =
rest_table_with_two_snapshots().await;
+ write_storage_tag(&root, "..", 2);
+ std::fs::write(root.join("tag/tag-."), b"{").unwrap();
+ let original_files = table_files(&root);
+ let tag_manager = catalog
+ .get_table(&Identifier::new(DATABASE, TABLE))
+ .await
+ .unwrap()
+ .tag_manager();
+ let tags = |filter: &str| {
+ format!(
+ "SELECT tag_name, CAST(snapshot_id AS VARCHAR) AS snapshot \
+ FROM paimon.{DATABASE}.`{TABLE}$tags` {filter} ORDER BY tag_name"
+ )
+ };
+ let release = vec![Some("release".to_string()), Some("1".to_string())];
+
+ for (catalog_tags, readable) in [
+ (vec![], vec![]),
+ (vec![".", "..", "release"], vec![release]),
+ ] {
+ for tag in &catalog_tags {
+ server.add_tag(DATABASE, TABLE, tag);
+ }
+ assert_eq!(tag_manager.list_all_names().await.unwrap(), catalog_tags);
+ let listed: Vec<_> = tag_manager
+ .list_all()
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|(name, snapshot)| vec![Some(name),
Some(snapshot.id().to_string())])
+ .collect();
+ assert_eq!(listed, readable);
+ assert_eq!(rows(&call(&context, &tags("")).await), readable);
+ assert_eq!(
+ rows(&call(&context, &tags("WHERE tag_name = 'release'")).await),
+ readable
+ );
+
+ for name in [".", ".."] {
+ for error in [
+ tag_manager.tag_exists(name).await.unwrap_err(),
+ tag_manager.get(name).await.unwrap_err(),
+ tag_manager.get_with_metadata(name).await.unwrap_err(),
+ ] {
+ assert!(error.to_string().contains(DOT_SEGMENT), "{error}");
+ }
+ let sql = format!("SELECT * FROM paimon.{DATABASE}.{TABLE} VERSION
AS OF '{name}'");
+ common::assert_sql_error(&context, &sql, DOT_SEGMENT).await;
+ call(&context, &format!("SET 'paimon.scan.tag-name' =
'{name}'")).await;
+ common::assert_sql_error(
+ &context,
+ &format!("SELECT * FROM paimon.{DATABASE}.{TABLE}"),
+ DOT_SEGMENT,
+ )
+ .await;
+ call(&context, "RESET 'paimon.scan.tag-name'").await;
+ }
+ }
+ common::assert_sql_error(
+ &context,
+ &format!("SELECT * FROM
paimon.{DATABASE}.`{TABLE}$referenced_files_size`"),
+ DOT_SEGMENT,
+ )
+ .await;
+ assert_eq!(table_files(&root), original_files);
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn test_rest_tag_metadata_uses_local_timestamp_and_branch() {
+ use arrow_array::{StringArray, TimestampMillisecondArray};
+ use chrono::TimeZone;
+ use paimon::catalog::Identifier;
+ use paimon::Catalog;
+
+ let (tmp, server, _) = setup().await;
+ let root = register_rest_table(&tmp, &server, &[]);
+ let schema = Schema::builder()
+ .column("id", DataType::Int(IntType::new()))
+ .build()
+ .unwrap();
+ let branch_table = format!("{TABLE}$branch_dev");
+ server.add_table_with_schema(
+ DATABASE,
+ &branch_table,
+ schema,
+ &format!("file://{}", root.display()),
+ );
+ let (catalog, context) = connect(&server).await;
+ for (table_name, only_tag, epoch_millis, retention, seconds) in [
+ (TABLE, "main_only", 1_704_067_200_000, "PT24H", 86_400.0),
+ (
+ branch_table.as_str(),
+ "branch_only",
+ 1_704_153_600_000,
+ "PT2H",
+ 7_200.0,
+ ),
+ ] {
+ server.add_tag(DATABASE, table_name, "release");
+ server.add_tag(DATABASE, table_name, only_tag);
+ server.set_tag_metadata(
+ DATABASE,
+ table_name,
+ "release",
+ Some(epoch_millis),
+ Some(retention),
+ );
+ let table = catalog
+ .get_table(&Identifier::new(DATABASE, table_name))
+ .await
+ .unwrap();
+ let tag_manager = table.tag_manager();
+ assert_eq!(
+ tag_manager.list_all_names().await.unwrap(),
+ [only_tag, "release"]
+ );
+ let offset = chrono::Local
+ .timestamp_millis_opt(epoch_millis)
+ .single()
+ .unwrap()
+ .offset()
+ .local_minus_utc();
+ let expected_time = epoch_millis + i64::from(offset) * 1_000;
+ let (_, created, retained) = tag_manager
+ .get_with_metadata("release")
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(created, Some(expected_time));
+ assert_eq!(retained, Some(seconds));
+ assert_eq!(
+ server
+ .tags(DATABASE, table_name)
+ .iter()
+ .find(|tag| tag.tag_name == "release")
+ .unwrap()
+ .tag_create_time,
+ Some(epoch_millis)
+ );
+
+ let batches = call(
+ &context,
+ &format!(
+ "SELECT tag_name, create_time, time_retained FROM
paimon.{DATABASE}.`{table_name}$tags` ORDER BY tag_name"
+ ),
+ ).await;
+ let batch = &batches[0];
+ assert_eq!(batch.num_rows(), 2);
+ let names = batch
+ .column(0)
+ .as_any()
+ .downcast_ref::<StringArray>()
+ .unwrap();
+ assert_eq!(names.value(0), only_tag);
+ assert_eq!(names.value(1), "release");
+ let times = batch
+ .column(1)
+ .as_any()
+ .downcast_ref::<TimestampMillisecondArray>()
+ .unwrap();
+ assert!(times.is_null(0));
+ assert_eq!(times.value(1), expected_time);
+ let retentions = batch
+ .column(2)
+ .as_any()
+ .downcast_ref::<StringArray>()
+ .unwrap();
+ assert!(retentions.is_null(0));
+ assert_eq!(retentions.value(1), retention);
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn test_tag_catalog_errors_do_not_fall_back_to_storage() {
+ let (tmp, server, context) = setup().await;
+ let root = register_rest_table(&tmp, &server, &[]);
+ server.add_tag(DATABASE, TABLE, "release");
+ let tag_path = root.join("tag/tag-release");
+ std::fs::create_dir_all(tag_path.parent().unwrap()).unwrap();
+ std::fs::write(tag_path, b"{").unwrap();
+ let original_files = table_files(&root);
+ let reads = [
+ format!("SELECT * FROM paimon.{DATABASE}.`{TABLE}$tags`"),
+ format!("SELECT * FROM paimon.{DATABASE}.{TABLE} VERSION AS OF
'release'"),
+ ];
+ let snapshot_read = format!("SELECT * FROM paimon.{DATABASE}.{TABLE}
VERSION AS OF 1");
+ let mutations = [
+ format!("CALL sys.create_tag(table => '{DATABASE}.{TABLE}', tag =>
'new')"),
+ format!("CALL sys.delete_tag(table => '{DATABASE}.{TABLE}', tag =>
'release')"),
+ ];
+
+ for (code, message) in [
+ (400, "invalid request"),
+ (403, "denied"),
+ (404, "Table sales.orders does not exist"),
+ (501, "remote operation unsupported"),
+ ] {
+ let error = Some(error_response(code, message));
+ server.set_tag_read_error(error.clone());
+ for sql in &reads {
+ common::assert_sql_error(&context, sql, message).await;
+ }
+ if code != 501 {
+ common::assert_sql_error(&context, &snapshot_read, message).await;
+ }
+ server.set_tag_read_error(None);
+ server.set_tag_mutation_error(error);
+ for sql in &mutations {
+ common::assert_sql_error(&context, sql, message).await;
+ }
+ server.set_tag_mutation_error(None);
+ assert_eq!(tag_names(&server), ["release"]);
+ assert_eq!(table_files(&root), original_files);
+ }
+ assert_eq!(server.create_tag_calls().len(), 4);
+ assert_eq!(server.delete_tag_calls().len(), 4);
+}
+
+#[tokio::test]
+async fn test_unsupported_tag_procedures_rejected_on_rest_catalog() {
+ let (tmp, server, context) = setup().await;
+ let root = register_rest_table(&tmp, &server, &[]);
+ server.add_tag(DATABASE, TABLE, "v1");
+ for file in ["tag/tag-v1", "snapshot/snapshot-1", "snapshot/LATEST"] {
+ let path = root.join(file);
+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
+ std::fs::write(path, b"{").unwrap();
+ }
+ let original_files = table_files(&root);
+ let table = format!("{DATABASE}.{TABLE}");
+
+ for (procedure, args) in [
+ ("replace_tag", "tag => 'v1'"),
+ ("replace_tag", "tag => 'v1', snapshot_id => 1"),
+ ("rename_tag", "tag => 'v1', target_tag => 'v2'"),
+ ("create_tag_from_timestamp", "tag => 'v2', timestamp => 0"),
+ ("rollback_to_timestamp", "timestamp => 0"),
+ ] {
+ let sql = format!("CALL sys.{procedure}(table => '{table}', {args})");
+ let error = context.sql(&sql).await.unwrap_err();
+ assert!(
+ matches!(error,
datafusion::error::DataFusionError::NotImplemented(_)),
+ "{sql}: {error}"
+ );
+ assert!(
+ error.to_string().contains(&format!(
+ "{procedure} is not supported for tables managed by a REST
catalog"
+ )),
+ "{sql}: {error}"
+ );
+ assert_eq!(tag_names(&server), ["v1"], "{sql}");
+ assert_eq!(table_files(&root), original_files, "{sql}");
+ }
+ assert!(server.create_tag_calls().is_empty());
+ assert!(server.delete_tag_calls().is_empty());
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn
test_snapshot_selection_procedures_reject_readable_rest_catalog_table() {
use arrow_array::Int32Array;
use axum::http::{Method, StatusCode, Uri};
use axum::{Json, Router};
@@ -1111,8 +1922,6 @@ async fn
test_create_tag_from_watermark_rejects_readable_rest_catalog_table() {
"CALL sys.create_tag(table => 'test_db.t1', tag => 'keep', snapshot_id
=> 1, time_retained => '1d')",
)
.await;
- let tag_path = table_dir.join("tag/tag-keep");
- let original_tag = std::fs::read(&tag_path).unwrap();
let table = catalog
.get_table(&Identifier::new("test_db", "t1"))
.await
@@ -1200,23 +2009,40 @@ async fn
test_create_tag_from_watermark_rejects_readable_rest_catalog_table() {
.any(|(_, path)| path.ends_with("/snapshot")));
requests.lock().unwrap().clear();
- for (watermark, tag) in [(2000, "checkpoint"), (1000, "older"), (1000,
"keep")] {
- let error = context.sql(&format!(
- "CALL sys.create_tag_from_watermark(table => 'test_db.t1', tag =>
'{tag}', watermark => {watermark})"
- )).await.unwrap_err();
+ let original_files = table_files(&table_dir);
+ for (procedure, args) in [
+ (
+ "create_tag_from_watermark",
+ "tag => 'checkpoint', watermark => 2000",
+ ),
+ (
+ "create_tag_from_watermark",
+ "tag => 'older', watermark => 1000",
+ ),
+ (
+ "create_tag_from_watermark",
+ "tag => 'keep', watermark => 1000",
+ ),
+ (
+ "create_tag_from_timestamp",
+ "tag => 'checkpoint', timestamp => 0",
+ ),
+ ("rollback_to_timestamp", "timestamp => 9223372036854775807"),
+ ] {
+ let sql = format!("CALL sys.{procedure}(table => 'test_db.t1',
{args})");
+ let error = context.sql(&sql).await.unwrap_err();
assert!(
matches!(error,
datafusion::error::DataFusionError::NotImplemented(_)),
- "{error}"
+ "{sql}: {error}"
);
assert!(
- error.to_string().contains(
- "create_tag_from_watermark is not supported for tables managed
by a REST catalog"
- ),
- "{error}"
+ error.to_string().contains(&format!(
+ "{procedure} is not supported for tables managed by a REST
catalog"
+ )),
+ "{sql}: {error}"
);
+ assert_eq!(table_files(&table_dir), original_files, "{sql}");
}
- assert_eq!(std::fs::read(tag_path).unwrap(), original_tag);
- assert_eq!(std::fs::read_dir(table_dir.join("tag")).unwrap().count(), 1);
let requests = requests.lock().unwrap();
assert!(!requests.is_empty());
assert!(requests
diff --git a/crates/paimon-rest-server/README.md
b/crates/paimon-rest-server/README.md
index d2757a15..bb8312d7 100644
--- a/crates/paimon-rest-server/README.md
+++ b/crates/paimon-rest-server/README.md
@@ -75,8 +75,15 @@ Served under the configured prefix (`/v1/...` by default):
| POST | `/tables/rename` | rename table |
| POST | `/databases/{db}/tables/{table}/commit` | commit a snapshot |
| GET | `/databases/{db}/tables/{table}/partitions` | list partitions |
+| GET / POST | `/databases/{db}/tables/{table}/tags` | returns `501` (tags
unsupported) |
+| GET / DELETE | `/databases/{db}/tables/{table}/tags/{tag}` | returns `501`
(tags unsupported) |
The data-token endpoint returns `501`; it is never called when
`data-token.enabled=false` (the default).
+Tag operations return `501` without accessing tag files. Numeric and watermark
+`scan.version` selectors can still resolve snapshots from table storage when
the
+tag endpoint is unsupported. Explicit `scan.tag-name` selectors and tag
operations
+return the unsupported error.
+
[`FileSystemCatalog`]: https://docs.rs/paimon
diff --git a/crates/paimon-rest-server/src/lib.rs
b/crates/paimon-rest-server/src/lib.rs
index aef406b7..d823e03c 100644
--- a/crates/paimon-rest-server/src/lib.rs
+++ b/crates/paimon-rest-server/src/lib.rs
@@ -185,6 +185,16 @@ fn build_router(prefix: &str, state: Arc<AppState>) ->
Router {
&format!("{base}/databases/:db/tables/:table/token"),
get(table_token_stub),
)
+ // Tags are not served yet. Answer 501 rather than an untyped 404,
which
+ // a client would read as a missing table.
+ .route(
+ &format!("{base}/databases/:db/tables/:table/tags"),
+ get(tags_stub).post(tags_stub),
+ )
+ .route(
+ &format!("{base}/databases/:db/tables/:table/tags/:tag"),
+ get(tags_stub).delete(tags_stub),
+ )
.layer(Extension(state))
}
@@ -622,6 +632,16 @@ async fn table_token_stub() -> Response {
(StatusCode::NOT_IMPLEMENTED, Json(body)).into_response()
}
+async fn tags_stub() -> Response {
+ let body = ErrorResponse::new(
+ None,
+ None,
+ Some("Tags are not supported by paimon-rest-server.".to_string()),
+ Some(StatusCode::NOT_IMPLEMENTED.as_u16() as i32),
+ );
+ (StatusCode::NOT_IMPLEMENTED, Json(body)).into_response()
+}
+
fn empty_audit() -> AuditRESTResponse {
AuditRESTResponse::new(None, None, None, None, None)
}
diff --git a/crates/paimon-rest-server/tests/e2e.rs
b/crates/paimon-rest-server/tests/e2e.rs
index 9082b275..48916b68 100644
--- a/crates/paimon-rest-server/tests/e2e.rs
+++ b/crates/paimon-rest-server/tests/e2e.rs
@@ -258,6 +258,57 @@ async fn test_write_commit_read_roundtrip() {
assert_eq!(total, 3, "expected 3 rows read back, got {total}");
}
+#[tokio::test]
+async fn test_scan_version_without_tag_endpoint() {
+ let ctx = setup().await;
+ let cat = &ctx.catalog;
+
+ cat.create_database("tt_db", false, HashMap::new())
+ .await
+ .unwrap();
+ let ident = Identifier::new("tt_db", "users");
+ cat.create_table(&ident, append_only_schema(), false)
+ .await
+ .unwrap();
+ for _ in 0..2 {
+ let table = cat.get_table(&ident).await.unwrap();
+ let write_builder = table.new_write_builder();
+ let mut writer = write_builder.new_write().unwrap();
+ writer.write_arrow_batch(&sample_batch()).await.unwrap();
+ let messages = writer.prepare_commit().await.unwrap();
+ write_builder.new_commit().commit(messages).await.unwrap();
+ }
+
+ let table = cat.get_table(&ident).await.unwrap();
+ let travel = |version: &str| {
+ table.copy_with_time_travel_strict(HashMap::from([(
+ "scan.version".to_string(),
+ version.to_string(),
+ )]))
+ };
+ let snapshot_1 = travel("1").await.unwrap();
+ let read_builder = snapshot_1.new_read_builder();
+ let plan = read_builder.new_scan().plan().await.unwrap();
+ let read = read_builder.new_read().unwrap();
+ let mut stream = read.to_arrow(plan.splits()).unwrap();
+ let mut total = 0usize;
+ while let Some(batch) = stream.try_next().await.unwrap() {
+ total += batch.num_rows();
+ }
+ assert_eq!(total, 3, "snapshot 1 holds one of the two batches");
+
+ for error in [
+ travel("release").await.unwrap_err(),
+ cat.create_tag(&ident, "release", None, false)
+ .await
+ .unwrap_err(),
+ cat.delete_tag(&ident, "release", true).await.unwrap_err(),
+ ] {
+ let error = error.to_string();
+ assert!(error.contains("Tags are not supported"), "{error}");
+ }
+}
+
// ==================== alter table over REST ====================
#[tokio::test]
diff --git a/crates/paimon/src/api/rest_api.rs
b/crates/paimon/src/api/rest_api.rs
index af3529f1..8752fe0d 100644
--- a/crates/paimon/src/api/rest_api.rs
+++ b/crates/paimon/src/api/rest_api.rs
@@ -1059,8 +1059,12 @@ impl RESTApi {
) -> Result<()> {
let database = identifier.database();
let table = identifier.object();
- validate_resource_path(&[(database, "database name"), (table, "table
name")])?;
- validate_non_empty(tag_name, "tag name")?;
+ // Get and delete put the name in the URL path, so reject dot segments
here too.
+ validate_resource_path(&[
+ (database, "database name"),
+ (table, "table name"),
+ (tag_name, "tag name"),
+ ])?;
let path = self.resource_paths.tags(database, table);
let mut request = CreateTagRequest::new(tag_name.to_string(),
snapshot_id);
request.time_retained = time_retained.map(str::to_string);
@@ -1076,7 +1080,51 @@ impl RESTApi {
(tag_name, "tag name"),
])?;
let path = self.resource_paths.tag(database, table, tag_name);
- self.client.get(&path, None::<&[(&str, &str)]>).await
+ let response: GetTagResponse = self.client.get(&path, None::<&[(&str,
&str)]>).await?;
+ if response.tag_name != tag_name {
+ return Err(crate::Error::DataInvalid {
+ message: format!(
+ "REST catalog returned tag '{}' for requested tag
'{tag_name}'",
+ response.tag_name
+ ),
+ source: None,
+ });
+ }
+ Ok(response)
+ }
+
+ /// List every tag name of a table, following nonempty continuation tokens.
+ /// Empty pages end listing, as in Java's `PagedList.listAllFromPagedApi`.
+ /// Repeated tokens are rejected so a malformed response cannot loop
forever.
+ pub async fn list_tags(&self, identifier: &Identifier) ->
Result<Vec<String>> {
+ let mut results = Vec::new();
+ let mut page_token: Option<String> = None;
+ let mut seen_page_tokens = HashSet::new();
+ loop {
+ let paged = self
+ .list_tags_paged(identifier, None, page_token.as_deref(), None)
+ .await?;
+ if paged.elements.is_empty() {
+ break;
+ }
+ results.extend(paged.elements);
+ let Some(next_page_token) = paged.next_page_token.filter(|token|
!token.is_empty())
+ else {
+ break;
+ };
+ if !seen_page_tokens.insert(next_page_token.clone()) {
+ return Err(crate::Error::UnexpectedError {
+ message: format!(
+ "REST catalog returned tag page token
'{next_page_token}' more than \
+ once for table {}",
+ identifier.full_name()
+ ),
+ source: None,
+ });
+ }
+ page_token = Some(next_page_token);
+ }
+ Ok(results)
}
/// Fetch one tag-name page, preserving server ordering and opaque tokens.
diff --git a/crates/paimon/src/catalog/rest/rest_catalog.rs
b/crates/paimon/src/catalog/rest/rest_catalog.rs
index 4efca0b7..81bb5c09 100644
--- a/crates/paimon/src/catalog/rest/rest_catalog.rs
+++ b/crates/paimon/src/catalog/rest/rest_catalog.rs
@@ -480,21 +480,10 @@ impl Catalog for RESTCatalog {
}
async fn get_tag(&self, identifier: &Identifier, tag_name: &str) ->
Result<GetTagResponse> {
- let response = self
- .api
+ self.api
.get_tag(identifier, tag_name)
.await
- .map_err(|error| map_rest_error_for_tag(error, identifier,
tag_name, None))?;
- if response.tag_name != tag_name {
- return Err(Error::DataInvalid {
- message: format!(
- "REST catalog returned tag '{}' for requested tag
'{tag_name}'",
- response.tag_name
- ),
- source: None,
- });
- }
- Ok(response)
+ .map_err(|error| map_rest_error_for_tag(error, identifier,
tag_name, None))
}
async fn delete_tag(
diff --git a/crates/paimon/src/table/mod.rs b/crates/paimon/src/table/mod.rs
index e3ed2374..b0371b82 100644
--- a/crates/paimon/src/table/mod.rs
+++ b/crates/paimon/src/table/mod.rs
@@ -501,7 +501,8 @@ impl Table {
}
pub fn tag_manager(&self) -> TagManager {
- let manager = TagManager::new(self.file_io.clone(),
self.location.clone());
+ let manager = TagManager::new(self.file_io.clone(),
self.location.clone())
+ .with_rest_env(self.rest_env.clone());
if self.is_main_branch() {
manager
} else {
diff --git a/crates/paimon/src/table/referenced_files.rs
b/crates/paimon/src/table/referenced_files.rs
index 9b5470c4..0f63bd78 100644
--- a/crates/paimon/src/table/referenced_files.rs
+++ b/crates/paimon/src/table/referenced_files.rs
@@ -32,7 +32,7 @@ use crate::spec::{
bucket_dir_name, BinaryRow, CoreOptions, DataField, DataFileMeta,
IndexManifest, Manifest,
ManifestEntry, ManifestFileMeta, PartitionComputer,
};
-use crate::table::{BranchManager, SnapshotManager, TagManager};
+use crate::table::{BranchManager, RESTEnv, SnapshotManager, Table, TagManager};
use futures::future::try_join_all;
use futures::stream::{self, StreamExt, TryStreamExt};
@@ -164,6 +164,9 @@ impl ExtraFileResolver {
/// Collect per-scope deduplicated referenced file size summaries for a table.
///
+/// Branches, snapshots and tags are read from table storage only. For a table
+/// managed by a REST catalog, use [`collect_table_referenced_files_summary`].
+///
/// Returns rows:
/// 1. `"total"` — union of all referenced files from main branch, tags, and
branches
/// 2. `"branch:main"` — main branch snapshots + tag snapshots
@@ -199,6 +202,8 @@ pub async fn collect_referenced_files_summary(
}
/// Collect referenced sizes using the table's data-directory and partition
options.
+///
+/// Like [`collect_referenced_files_summary`], this reads table storage only.
pub async fn collect_referenced_files_summary_with_options(
file_io: &FileIO,
table_location: &str,
@@ -206,6 +211,53 @@ pub async fn collect_referenced_files_summary_with_options(
schema_fields: &[DataField],
options: &CoreOptions<'_>,
) -> crate::Result<Vec<ReferencedFilesSummary>> {
+ collect_summary(
+ file_io,
+ table_location,
+ partition_keys,
+ schema_fields,
+ options,
+ None,
+ )
+ .await
+}
+
+/// Collect referenced sizes for a table with its data-directory and partition
options.
+///
+/// For a table managed by a REST catalog, branches, tags and each branch's
current
+/// snapshot come from the catalog, together with the snapshot files in
storage.
+/// REST metadata failures propagate: unknown metadata must not be reported as
an
+/// empty set of references. Other tables read table storage only.
+pub async fn collect_table_referenced_files_summary(
+ table: &Table,
+) -> crate::Result<Vec<ReferencedFilesSummary>> {
+ let schema = table.schema();
+ collect_summary(
+ table.file_io(),
+ table.location(),
+ schema.partition_keys(),
+ &schema.partition_fields(),
+ &schema.core_options(),
+ table.rest_env().cloned(),
+ )
+ .await
+}
+
+async fn collect_summary(
+ file_io: &FileIO,
+ table_location: &str,
+ partition_keys: &[String],
+ schema_fields: &[DataField],
+ options: &CoreOptions<'_>,
+ rest_env: Option<RESTEnv>,
+) -> crate::Result<Vec<ReferencedFilesSummary>> {
+ let branch_names = if let Some(rest) = &rest_env {
+ rest.list_branch_names().await?
+ } else {
+ BranchManager::new(file_io.clone(), table_location.to_string())
+ .list_all()
+ .await?
+ };
let manifest_cache: ManifestCache = Mutex::new(HashMap::new());
let manifest_cache_ref = &manifest_cache;
let mut extra_resolver = ExtraFileResolver::new(
@@ -223,29 +275,29 @@ pub async fn
collect_referenced_files_summary_with_options(
}
let extra_resolver_ref = &extra_resolver;
- let sm = SnapshotManager::new(file_io.clone(), table_location.to_string());
- let tm = TagManager::new(file_io.clone(), table_location.to_string());
+ let include_catalog_snapshot = rest_env.is_some();
+ // Collection always starts at the table root, even for a branch table.
+ let sm = SnapshotManager::new(file_io.clone(), table_location.to_string())
+ .with_rest_env(rest_env.clone());
+ let tm = TagManager::new(file_io.clone(),
table_location.to_string()).with_rest_env(rest_env);
// 1. Main branch snapshots + tags (concurrently)
// For main branch, snapshot reading and manifest resolution both use root
SM.
let (main_files, tag_files) = tokio::try_join!(
- collect_scope_files(file_io, &sm, &sm, manifest_cache_ref,
extra_resolver_ref),
- collect_tag_files(
+ collect_scope_files(
file_io,
&sm,
&sm,
- &tm,
manifest_cache_ref,
- extra_resolver_ref
+ extra_resolver_ref,
+ include_catalog_snapshot
),
+ collect_tag_files(file_io, &sm, &tm, manifest_cache_ref,
extra_resolver_ref),
)?;
let mut main_files = main_files;
main_files.merge(&tag_files);
- // 2. Branch file sets
- let bm = BranchManager::new(file_io.clone(), table_location.to_string());
- let branch_names = bm.list_all().await?;
-
+ // 2. Branch file sets, using the catalog's branch list for REST tables.
let mut total_files = ScopeFileSet::default();
total_files.merge(&main_files);
let mut branch_summaries = Vec::with_capacity(branch_names.len());
@@ -253,20 +305,21 @@ pub async fn
collect_referenced_files_summary_with_options(
let branch_sm = sm.with_branch(branch_name);
let branch_tm = tm.with_branch(branch_name);
- // Branch SM reads snapshot/tag files from branch path, but manifest
paths
- // are always resolved from the table root. Process one branch at a
time
- // so completed branch file sets can be summarized and released.
+ // Historical snapshot files use the branch path; current snapshots and
+ // tags also consult the catalog for REST tables. Manifest paths use
the
+ // table root. Process one branch at a time so completed file sets can
+ // be summarized and released.
let (mut branch_files, branch_tag_files) = tokio::try_join!(
collect_scope_files(
file_io,
&branch_sm,
&sm,
manifest_cache_ref,
- extra_resolver_ref
+ extra_resolver_ref,
+ include_catalog_snapshot
),
collect_tag_files(
file_io,
- &branch_sm,
&sm,
&branch_tm,
manifest_cache_ref,
@@ -307,10 +360,11 @@ async fn collect_scope_files(
manifest_sm: &SnapshotManager,
manifest_cache: &ManifestCache,
extra_resolver: &ExtraFileResolver,
+ include_catalog_snapshot: bool,
) -> crate::Result<ScopeFileSet> {
let snapshot_ids = sm.list_all_ids().await?;
- merge_scope_file_sets(
+ let mut files = merge_scope_file_sets(
stream::iter(snapshot_ids)
.map(|snapshot_id| {
let sm = sm.clone();
@@ -328,12 +382,30 @@ async fn collect_scope_files(
})
.buffer_unordered(SNAPSHOT_CONCURRENCY),
)
- .await
+ .await?;
+
+ // A REST branch can have a current snapshot with no visible snapshot file.
+ // Merge it by file name, since it may also be present in the stored
history.
+ if include_catalog_snapshot {
+ if let Some(snapshot) = sm.get_latest_snapshot().await? {
+ if let Some(current) = collect_snapshot_files(
+ file_io,
+ manifest_sm,
+ &snapshot,
+ manifest_cache,
+ extra_resolver,
+ )
+ .await?
+ {
+ files.merge(¤t);
+ }
+ }
+ }
+ Ok(files)
}
async fn collect_tag_files(
file_io: &FileIO,
- _sm: &SnapshotManager,
manifest_sm: &SnapshotManager,
tm: &TagManager,
manifest_cache: &ManifestCache,
diff --git a/crates/paimon/src/table/rest_env.rs
b/crates/paimon/src/table/rest_env.rs
index 8417fa65..f37dbb3a 100644
--- a/crates/paimon/src/table/rest_env.rs
+++ b/crates/paimon/src/table/rest_env.rs
@@ -20,7 +20,9 @@
use crate::api::rest_api::RESTApi;
use crate::api::rest_error::RestError;
use crate::api::GetTableResponse;
-use crate::catalog::{FusePathResolver, Identifier, RESTToken, RESTTokenFileIO};
+use crate::catalog::{
+ FusePathResolver, Identifier, RESTToken, RESTTokenFileIO,
DEFAULT_MAIN_BRANCH,
+};
use crate::common::{CatalogOptions, Options};
use crate::error::Error;
use crate::io::cache::{create_local_cache_with_namespace_async, LocalCache};
@@ -622,6 +624,64 @@ impl RESTEnv {
}
}
+ /// Load a tag of this table's branch from the catalog, or None when the
+ /// catalog has no such tag.
+ pub(crate) async fn get_tag(
+ &self,
+ branch: &str,
+ tag_name: &str,
+ ) -> Result<Option<crate::api::GetTagResponse>> {
+ let identifier = self.identifier.with_branch(branch)?;
+ match self.api.get_tag(&identifier, tag_name).await {
+ Ok(response) => Ok(Some(response)),
+ Err(Error::RestApi {
+ source: RestError::NoSuchResource { resource_type, .. },
+ }) if resource_type.as_deref() == Some("TAG") => Ok(None),
+ Err(error) => Err(map_rest_error_for_table(error, &identifier)),
+ }
+ }
+
+ /// List the tag names of this table's branch from the catalog, sorted.
+ pub(crate) async fn list_tag_names(&self, branch: &str) ->
Result<Vec<String>> {
+ let identifier = self.identifier.with_branch(branch)?;
+ let mut names = self
+ .api
+ .list_tags(&identifier)
+ .await
+ .map_err(|error| map_rest_error_for_table(error, &identifier))?;
+ names.sort_unstable();
+ names.dedup();
+ Ok(names)
+ }
+
+ /// List the table's non-main branches from the catalog, even when this
+ /// environment belongs to a branch. Validate names and suffix parsing
before
+ /// using storage paths or addressing branch-scoped tag metadata.
+ pub(crate) async fn list_branch_names(&self) -> Result<Vec<String>> {
+ let identifier = self.identifier.with_branch(DEFAULT_MAIN_BRANCH)?;
+ let mut names = self
+ .api
+ .list_branches(&identifier)
+ .await
+ .map_err(|error| map_rest_error_for_table(error, &identifier))?;
+ names.retain(|name| name != DEFAULT_MAIN_BRANCH);
+ for name in &names {
+ let parsed = identifier.with_branch(name)?.parsed_object_name()?;
+ if parsed.branch() != Some(name.as_str()) ||
parsed.system_table().is_some() {
+ return Err(Error::DataInvalid {
+ message: format!(
+ "REST catalog returned an unaddressable branch name
{name:?} for table {}",
+ identifier.full_name()
+ ),
+ source: None,
+ });
+ }
+ }
+ names.sort_unstable();
+ names.dedup();
+ Ok(names)
+ }
+
/// Create a `RESTSnapshotCommit` from this environment.
pub fn snapshot_commit(&self) -> Arc<dyn SnapshotCommit> {
Arc::new(RESTSnapshotCommit::new(
diff --git a/crates/paimon/src/table/tag_manager.rs
b/crates/paimon/src/table/tag_manager.rs
index a9dce5db..75e47c1d 100644
--- a/crates/paimon/src/table/tag_manager.rs
+++ b/crates/paimon/src/table/tag_manager.rs
@@ -15,32 +15,47 @@
// specific language governing permissions and limitations
// under the License.
-//! Tag manager for reading and writing tag metadata using FileIO.
+//! Tag metadata from table files or the owning REST catalog.
//!
//! Reference:
[org.apache.paimon.utils.TagManager](https://github.com/apache/paimon/blob/master/paimon-core/src/main/java/org/apache/paimon/utils/TagManager.java)
//! and
[pypaimon.tag.tag_manager.TagManager](https://github.com/apache/paimon/blob/master/paimon-python/pypaimon/tag/tag_manager.py).
+use crate::catalog::DEFAULT_MAIN_BRANCH;
use crate::io::FileIO;
use crate::spec::Snapshot;
+use crate::table::RESTEnv;
use chrono::{Datelike, Timelike};
-use futures::future::try_join_all;
+use futures::stream::{self, StreamExt, TryStreamExt};
use opendal::raw::get_basename;
use std::time::Duration;
const TAG_DIR: &str = "tag";
const TAG_PREFIX: &str = "tag-";
+// A large tag listing must not issue an unbounded number of catalog requests.
+const TAG_READ_CONCURRENCY: usize = 32;
-/// Manager for tag files using unified FileIO.
+/// Manager for tag metadata in table files or a REST catalog.
///
-/// Tags are named snapshots stored as JSON files at
`{table_path}/tag/tag-{name}`.
+/// Filesystem tags are named snapshots stored as JSON at
`{table_path}/tag/tag-{name}`.
/// Tags without retention use Snapshot JSON. Retained tags also include
Java-compatible
/// creation time and retention metadata.
///
+/// For a table managed by a REST catalog, the catalog owns tags: reads go to
+/// the catalog and storage writes are refused.
+///
/// Reference:
[org.apache.paimon.utils.TagManager](https://github.com/apache/paimon/blob/master/paimon-core/src/main/java/org/apache/paimon/utils/TagManager.java)
#[derive(Debug, Clone)]
pub struct TagManager {
file_io: FileIO,
table_path: String,
+ rest: Option<RestTags>,
+}
+
+/// The catalog that owns a REST table's tags, and the branch they belong to.
+#[derive(Debug, Clone)]
+struct RestTags {
+ env: RESTEnv,
+ branch: String,
}
impl TagManager {
@@ -48,9 +63,53 @@ impl TagManager {
Self {
file_io,
table_path,
+ rest: None,
}
}
+ pub(crate) fn with_rest_env(mut self, rest_env: Option<RESTEnv>) -> Self {
+ self.rest = rest_env.map(|env| RestTags {
+ env,
+ branch: DEFAULT_MAIN_BRANCH.to_string(),
+ });
+ self
+ }
+
+ fn ensure_storage_owned(&self, action: &str) -> crate::Result<()> {
+ if self.rest.is_some() {
+ return Err(crate::Error::Unsupported {
+ message: format!(
+ "cannot {action} a tag in table storage: the REST catalog
owns this table's tags"
+ ),
+ });
+ }
+ Ok(())
+ }
+
+ /// Omit catalog tags that cannot be addressed safely by the REST API from
+ /// metadata listings. Never substitute a potentially stale storage file.
+ /// Keep these names in `list_all_names` so callers that need a complete
tag
+ /// set, such as referenced-file collection, fail rather than undercount.
+ async fn list_readable_names(&self) -> crate::Result<Vec<String>> {
+ let mut names = self.list_all_names().await?;
+ if let Some(rest) = &self.rest {
+ names.retain(|name| {
+ if is_dot_path_segment(name) {
+ log::warn!(
+ "Skipping legacy tag {name:?} in the tag listing for
table {} on \
+ branch {:?}: the REST API cannot address a dot path
segment",
+ rest.env.identifier().full_name(),
+ rest.branch,
+ );
+ false
+ } else {
+ true
+ }
+ });
+ }
+ Ok(names)
+ }
+
/// Path to the tag directory (e.g. `table_path/tag`).
pub fn tag_directory(&self) -> String {
format!("{}/{}", self.table_path, TAG_DIR)
@@ -59,7 +118,14 @@ impl TagManager {
/// Create a TagManager for a branch of this table.
pub fn with_branch(&self, branch_name: &str) -> Self {
let branch_path = format!("{}/branch/branch-{}", self.table_path,
branch_name);
- Self::new(self.file_io.clone(), branch_path)
+ Self {
+ file_io: self.file_io.clone(),
+ table_path: branch_path,
+ rest: self.rest.as_ref().map(|rest| RestTags {
+ env: rest.env.clone(),
+ branch: branch_name.to_string(),
+ }),
+ }
}
/// Path to the tag file for the given name (e.g. `tag/tag-my_tag`).
@@ -69,17 +135,24 @@ impl TagManager {
/// Check if a tag exists.
pub async fn tag_exists(&self, tag_name: &str) -> crate::Result<bool> {
+ if let Some(rest) = &self.rest {
+ return Ok(rest.env.get_tag(&rest.branch,
tag_name).await?.is_some());
+ }
validate_tag_name(tag_name)?;
let path = self.tag_path(tag_name);
let input = self.file_io.new_input(&path)?;
input.exists().await
}
- /// Get the snapshot for a tag, or None if the tag file does not exist.
+ /// Get the snapshot for a tag, or None if the tag does not exist.
///
- /// Tag files are JSON with the same schema as Snapshot.
- /// Reads directly and catches NotFound to avoid a separate exists() IO
round-trip.
+ /// REST tables resolve the tag through the catalog. Filesystem tables read
+ /// snapshot JSON directly, catching NotFound without an exists() IO
round-trip.
pub async fn get(&self, tag_name: &str) -> crate::Result<Option<Snapshot>>
{
+ if let Some(rest) = &self.rest {
+ let tag = rest.env.get_tag(&rest.branch, tag_name).await?;
+ return Ok(tag.map(|tag| tag.snapshot));
+ }
validate_tag_name(tag_name)?;
let path = self.tag_path(tag_name);
let input = self.file_io.new_input(&path)?;
@@ -100,10 +173,12 @@ impl TagManager {
Ok(Some(snapshot))
}
- /// Get a tag's snapshot together with the two tag-only fields Java writes
- /// alongside it: the creation time as epoch millis and the retention as
- /// seconds. Returns `None` when the tag file does not exist; either
metadata
- /// field is `None` when absent or unparsable.
+ /// Get a tag's snapshot, creation time and retention in seconds.
+ ///
+ /// The creation time is local wall-clock time encoded like Arrow's
timezone-less
+ /// TIMESTAMP_MILLIS, not a Unix epoch instant: REST epoch millis are
converted to
+ /// local time, while tag files already store local time. Returns `None`
when the
+ /// tag does not exist; either metadata field is `None` when absent or
unparsable.
pub async fn get_with_metadata(
&self,
tag_name: &str,
@@ -129,6 +204,20 @@ impl TagManager {
Option<serde_json::Number>,
)>,
> {
+ if let Some(rest) = &self.rest {
+ let Some(tag) = rest.env.get_tag(&rest.branch, tag_name).await?
else {
+ return Ok(None);
+ };
+ let create_time = tag
+ .tag_create_time
+ .and_then(chrono::DateTime::from_timestamp_millis)
+ .map(|time| time.with_timezone(&chrono::Local).naive_local());
+ let time_retained = tag
+ .tag_time_retained
+ .as_deref()
+ .and_then(rest_time_retained_seconds);
+ return Ok(Some((tag.snapshot, create_time, time_retained)));
+ }
validate_tag_name(tag_name)?;
let path = self.tag_path(tag_name);
let input = self.file_io.new_input(&path)?;
@@ -161,29 +250,37 @@ impl TagManager {
Ok(Some((snapshot, create_time, time_retained)))
}
- /// Like [`Self::list_all`], but each row also carries the tag creation
time
- /// in epoch millis and the retention in seconds.
+ /// Like [`Self::list_all`], with the local creation time encoding and
+ /// retention in seconds described by [`Self::get_with_metadata`].
#[allow(clippy::type_complexity)]
pub async fn list_all_with_metadata(
&self,
) -> crate::Result<Vec<(String, Snapshot, Option<i64>, Option<f64>)>> {
- let names = self.list_all_names().await?;
- try_join_all(names.into_iter().map(|name| async move {
- let (snap, create_time, retained) =
- self.get_with_metadata(&name)
+ let names = self.list_readable_names().await?;
+ stream::iter(names)
+ .map(|name| async move {
+ let (snapshot, create_time, retained) = self
+ .get_with_metadata(&name)
.await?
.ok_or_else(|| crate::Error::DataInvalid {
message: format!("tag '{name}' disappeared during
listing"),
source: None,
})?;
- Ok::<_, crate::Error>((name, snap, create_time, retained))
- }))
- .await
+ Ok::<_, crate::Error>((name, snapshot, create_time, retained))
+ })
+ .buffered(TAG_READ_CONCURRENCY)
+ .try_collect()
+ .await
}
- /// List all tag names sorted ascending. Returns an empty vector when the
- /// tag directory does not exist.
+ /// List all tag names sorted ascending, from the catalog for REST tables
+ /// or from tag files otherwise. For filesystem tables, a missing tag
directory
+ /// yields an empty list. REST names are returned even if an older client
+ /// created a dot-segment tag that cannot be read through the REST API.
pub async fn list_all_names(&self) -> crate::Result<Vec<String>> {
+ if let Some(rest) = &self.rest {
+ return rest.env.list_tag_names(&rest.branch).await;
+ }
let tag_dir = self.tag_directory();
let statuses = match self.file_io.list_status(&tag_dir).await {
Ok(s) => s,
@@ -220,6 +317,7 @@ impl TagManager {
snapshot: &Snapshot,
time_retained: Option<&str>,
) -> crate::Result<()> {
+ self.ensure_storage_owned("create")?;
validate_tag_name(tag_name)?;
let path = self.tag_path(tag_name);
let serialize_error = |e| crate::Error::DataInvalid {
@@ -273,6 +371,7 @@ impl TagManager {
snapshot: &Snapshot,
time_retained: Option<&str>,
) -> crate::Result<()> {
+ self.ensure_storage_owned("replace")?;
if !self.tag_exists(tag_name).await? {
return Err(crate::Error::TagNotExist {
tag_name: tag_name.to_string(),
@@ -284,6 +383,7 @@ impl TagManager {
/// Delete a tag file.
pub async fn delete(&self, tag_name: &str) -> crate::Result<()> {
+ self.ensure_storage_owned("delete")?;
validate_tag_name(tag_name)?;
let path = self.tag_path(tag_name);
self.file_io.delete_file(&path).await
@@ -296,6 +396,7 @@ impl TagManager {
/// Uses copy-then-delete rather than a native rename: object stores and
the
/// in-memory backend do not support rename.
pub async fn rename(&self, tag_name: &str, target_tag_name: &str) ->
crate::Result<()> {
+ self.ensure_storage_owned("rename")?;
validate_tag_name(tag_name)?;
validate_tag_name(target_tag_name)?;
let src = self.tag_path(tag_name);
@@ -317,19 +418,24 @@ impl TagManager {
}
/// List all tags as `(name, snapshot)` pairs sorted by name ascending.
+ /// Legacy REST tags named `.` or `..` are skipped with a warning; their
+ /// storage files cannot establish the catalog's snapshot for those tags.
pub async fn list_all(&self) -> crate::Result<Vec<(String, Snapshot)>> {
- let names = self.list_all_names().await?;
- try_join_all(names.into_iter().map(|name| async move {
- let snap = self
- .get(&name)
- .await?
- .ok_or_else(|| crate::Error::DataInvalid {
- message: format!("tag '{name}' disappeared during
listing"),
- source: None,
- })?;
- Ok::<_, crate::Error>((name, snap))
- }))
- .await
+ let names = self.list_readable_names().await?;
+ stream::iter(names)
+ .map(|name| async move {
+ let snapshot = self
+ .get(&name)
+ .await?
+ .ok_or_else(|| crate::Error::DataInvalid {
+ message: format!("tag '{name}' disappeared during
listing"),
+ source: None,
+ })?;
+ Ok::<_, crate::Error>((name, snapshot))
+ })
+ .buffered(TAG_READ_CONCURRENCY)
+ .try_collect()
+ .await
}
}
@@ -371,6 +477,28 @@ fn parse_tag_time_retained(value: &str) ->
Option<Duration> {
(duration.as_secs() <= i64::MAX as u64).then_some(duration)
}
+/// Retention seconds of a catalog tag, in the decimal form tag files use.
+///
+/// Java sends an ISO-8601 `Duration` such as `"PT24H"`; a retention string
+/// such as `"1d"` is also accepted. Anything else is treated as absent, like
+/// an unparsable tag file.
+fn rest_time_retained_seconds(value: &str) -> Option<serde_json::Number> {
+ let value = value.trim();
+ let duration = value
+ .parse::<jiff::SignedDuration>()
+ .ok()
+ .and_then(|duration| Duration::try_from(duration).ok())
+ .or_else(|| parse_tag_time_retained(value))?;
+ format!("{}.{:09}", duration.as_secs(), duration.subsec_nanos())
+ .parse()
+ .ok()
+}
+
+/// `.` and `..` cannot appear as a URL path segment.
+fn is_dot_path_segment(tag_name: &str) -> bool {
+ matches!(tag_name, "." | "..")
+}
+
fn validate_tag_name(tag_name: &str) -> crate::Result<()> {
let invalid = tag_name.trim().is_empty()
|| tag_name.trim_end() != tag_name
@@ -745,6 +873,24 @@ mod tests {
);
}
+ #[test]
+ fn test_rest_time_retained_accepts_java_duration_and_retention() {
+ for (value, expected) in [
+ ("PT24H", Some("86400.000000000")),
+ ("PT1.5S", Some("1.500000000")),
+ ("1d", Some("86400.000000000")),
+ (" 12 HOURS ", Some("43200.000000000")),
+ ("-PT1S", None),
+ ("soon", None),
+ ] {
+ assert_eq!(
+ rest_time_retained_seconds(value).map(|seconds|
seconds.to_string()),
+ expected.map(str::to_string),
+ "{value}"
+ );
+ }
+ }
+
#[tokio::test]
async fn test_create_tag_with_invalid_retention_does_not_write() {
let file_io = test_file_io();
diff --git a/crates/paimon/src/table/time_travel.rs
b/crates/paimon/src/table/time_travel.rs
index a7e2216d..0f8d52e4 100644
--- a/crates/paimon/src/table/time_travel.rs
+++ b/crates/paimon/src/table/time_travel.rs
@@ -17,6 +17,7 @@
//! Snapshot resolution for time travel, mirroring Java `TimeTravelUtil`.
+use crate::api::RestError;
use crate::spec::{CoreOptions, Snapshot, TimeTravelSelector};
use crate::table::{SnapshotManager, Table, TagManager};
use crate::Error;
@@ -35,13 +36,15 @@ pub(crate) async fn travel_to_snapshot(
tag_manager: &TagManager,
options: &HashMap<String, String>,
) -> crate::Result<Option<Snapshot>> {
+ let mut version_tag = None;
// Java adapts scan.version before checking mutually exclusive selectors.
// It overwrites the same selector kind, but preserves conflicts with
others.
let mut adapted;
let options = if let Some(version) = options.get("scan.version") {
adapted = options.clone();
adapted.remove("scan.version");
- let (key, value) = if tag_manager.tag_exists(version).await? {
+ version_tag = resolve_version_tag(tag_manager, version).await?;
+ let (key, value) = if version_tag.is_some() {
("scan.tag-name", version.clone())
} else if let Some(watermark) = version.strip_prefix(WATERMARK_PREFIX)
{
let value = watermark.parse::<i64>().map_err(|e|
Error::DataInvalid {
@@ -49,7 +52,7 @@ pub(crate) async fn travel_to_snapshot(
source: Some(Box::new(e)),
})?;
("scan.watermark", value.to_string())
- } else if !version.is_empty() && version.bytes().all(|b|
b.is_ascii_digit()) {
+ } else if is_snapshot_id_version(version) {
("scan.snapshot-id", version.clone())
} else {
return Err(Error::DataInvalid {
@@ -97,20 +100,45 @@ pub(crate) async fn travel_to_snapshot(
value: v,
option_name: _,
}) => {
- // An explicit tag name: resolve strictly by tag, never as a
snapshot id.
- if tag_manager.tag_exists(v).await? {
- resolve_tag(tag_manager, v).await.map(Some)
- } else {
- Err(Error::DataInvalid {
- message: format!("Tag '{v}' doesn't exist."),
- source: None,
- })
+ // Tag selectors never fall back to snapshot ids. Reuse the tag
+ // fetched while adapting scan.version when it selected this tag.
+ match version_tag {
+ Some(snapshot) => Ok(Some(snapshot)),
+ None => resolve_tag(tag_manager, v).await.map(Some),
}
}
None => Ok(None),
}
}
+/// Resolve a `scan.version` tag before trying a snapshot id or watermark of
+/// the same spelling. Reuse its snapshot rather than fetching the tag twice.
+///
+/// A numeric snapshot id or watermark can use table storage when the tag
endpoint
+/// returns HTTP 501. Other catalog errors and tag-only versions propagate.
+async fn resolve_version_tag(
+ tag_manager: &TagManager,
+ version: &str,
+) -> crate::Result<Option<Snapshot>> {
+ match tag_manager.get(version).await {
+ Err(Error::RestApi {
+ source: RestError::NotImplemented { .. },
+ }) if is_snapshot_or_watermark_version(version) => Ok(None),
+ result => result,
+ }
+}
+
+fn is_snapshot_or_watermark_version(version: &str) -> bool {
+ match version.strip_prefix(WATERMARK_PREFIX) {
+ Some(watermark) => watermark.parse::<i64>().is_ok(),
+ None => is_snapshot_id_version(version),
+ }
+}
+
+fn is_snapshot_id_version(version: &str) -> bool {
+ !version.is_empty() && version.bytes().all(|b| b.is_ascii_digit())
+}
+
async fn resolve_watermark(
snapshot_manager: &SnapshotManager,
watermark: i64,
@@ -151,7 +179,7 @@ pub(crate) async fn resolve_snapshot(table: &Table) ->
crate::Result<Option<Snap
}
}
-/// Fetch a tag known to exist, mapping an unexpectedly-missing tag to an
error.
+/// Fetch a tag's snapshot, failing when the tag does not exist.
async fn resolve_tag(tag_manager: &TagManager, name: &str) ->
crate::Result<Snapshot> {
match tag_manager.get(name).await? {
Some(s) => Ok(s),
@@ -173,6 +201,27 @@ mod tests {
use std::collections::HashMap;
use std::sync::Arc;
+ #[test]
+ fn test_snapshot_or_watermark_version_shape() {
+ for (version, expected) in [
+ ("1", true),
+ ("0042", true),
+ ("watermark-1000", true),
+ ("watermark--5", true),
+ ("", false),
+ ("-1", false),
+ ("release", false),
+ ("watermark-", false),
+ ("watermark-soon", false),
+ ] {
+ assert_eq!(
+ super::is_snapshot_or_watermark_version(version),
+ expected,
+ "{version}"
+ );
+ }
+ }
+
fn schema_v0() -> TableSchema {
let schema = Schema::builder()
.column("id", DataType::Int(IntType::new()))
diff --git a/crates/paimon/tests/mock_server.rs
b/crates/paimon/tests/mock_server.rs
index aae1f99b..f13a8833 100644
--- a/crates/paimon/tests/mock_server.rs
+++ b/crates/paimon/tests/mock_server.rs
@@ -51,9 +51,17 @@ type PartitionPageResponse = (Vec<Partition>,
Option<String>);
type PartitionSpecPageResponse = (Vec<HashMap<String, String>>,
Option<String>);
fn branch_name_from_uri(uri: &Uri) -> String {
- // Branch paths use Java's form encoding. Decode the raw segment so spaces
- // (`+`) remain distinct from literal plus signs (`%2B`), unlike Axum's
Path.
- let (_, suffix) = uri.path().rsplit_once("/branches/").unwrap();
+ resource_name_from_uri(uri, "/branches/")
+}
+
+fn tag_name_from_uri(uri: &Uri) -> String {
+ resource_name_from_uri(uri, "/tags/")
+}
+
+fn resource_name_from_uri(uri: &Uri, marker: &str) -> String {
+ // Branch and tag paths use Java's form encoding. Decode the raw segment so
+ // spaces (`+`) remain distinct from literal plus signs (`%2B`), unlike
Axum's Path.
+ let (_, suffix) = uri.path().rsplit_once(marker).unwrap();
RESTUtil::decode_string(suffix.split('/').next().unwrap())
}
@@ -65,6 +73,12 @@ struct MockState {
views: HashMap<String, GetViewResponse>,
functions: HashMap<String, GetFunctionResponse>,
tags: HashMap<String, GetTagResponse>,
+ catalog_snapshots: HashMap<String, Snapshot>,
+ create_tag_calls: Vec<(String, String, CreateTagRequest)>,
+ get_tag_calls: Vec<(String, String, String)>,
+ delete_tag_calls: Vec<(String, String, String)>,
+ tag_mutation_error: Option<ErrorResponse>,
+ tag_read_error: Option<ErrorResponse>,
branches: HashMap<String, Vec<String>>,
drop_branch_calls: Vec<(String, String, String)>,
fast_forward_calls: Vec<(String, String, String)>,
@@ -792,11 +806,25 @@ impl RESTServer {
(StatusCode::OK, Json(serde_json::json!(""))).into_response()
}
- /// Load the snapshot from the same filesystem fixtures used by table
reads.
+ /// Load a registered catalog snapshot, or use the filesystem fixtures.
pub async fn load_snapshot(
Path((db, table)): Path<(String, String)>,
Extension(state): Extension<Arc<RESTServer>>,
) -> impl IntoResponse {
+ let snapshot = state
+ .inner
+ .lock()
+ .unwrap()
+ .catalog_snapshots
+ .get(&format!("{db}.{table}"))
+ .cloned();
+ if let Some(snapshot) = snapshot {
+ return (
+ StatusCode::OK,
+ Json(json!({"snapshot": {"snapshot": snapshot}})),
+ )
+ .into_response();
+ }
let identifier = Identifier::new(&db, &table);
let parsed = identifier.parsed_object_name().unwrap();
let key = format!("{db}.{}", parsed.table());
@@ -1121,24 +1149,44 @@ impl RESTServer {
Extension(state): Extension<Arc<RESTServer>>,
Json(request): Json<CreateTagRequest>,
) -> impl IntoResponse {
- let mut state = state.inner.lock().unwrap();
- if !state.tables.contains_key(&format!("{db}.{table}")) {
- return resource_error(StatusCode::NOT_FOUND, "table", &table);
- }
-
let key = format!("{db}.{table}.{}", request.tag_name);
+ let (location, catalog_snapshot) = {
+ let mut state = state.inner.lock().unwrap();
+ state
+ .create_tag_calls
+ .push((db.clone(), table.clone(), request.clone()));
+ if let Some(error) = state.tag_mutation_error.clone() {
+ return Self::error_response(error);
+ }
+ let Some(response) = state.tables.get(&format!("{db}.{table}"))
else {
+ return resource_error(StatusCode::NOT_FOUND, "table", &table);
+ };
+ let location = response.path.clone();
+ if state.tags.contains_key(&key) {
+ return resource_error(StatusCode::CONFLICT, "TAG",
&request.tag_name);
+ }
+ let catalog_snapshot = state
+ .catalog_snapshots
+ .get(&format!("{db}.{table}"))
+ .cloned();
+ (location, catalog_snapshot)
+ };
+ let Some(snapshot) =
+ Self::tag_target(location, catalog_snapshot,
request.snapshot_id).await
+ else {
+ let snapshot_id = request.snapshot_id.unwrap_or(1);
+ return resource_error(StatusCode::NOT_FOUND, "SNAPSHOT",
&snapshot_id.to_string());
+ };
+
+ let mut state = state.inner.lock().unwrap();
if state.tags.contains_key(&key) {
return resource_error(StatusCode::CONFLICT, "TAG",
&request.tag_name);
}
- let snapshot_id = request.snapshot_id.unwrap_or(1);
- if snapshot_id != 1 {
- return resource_error(StatusCode::NOT_FOUND, "SNAPSHOT",
&snapshot_id.to_string());
- }
state.tags.insert(
key,
GetTagResponse {
tag_name: request.tag_name,
- snapshot: tag_snapshot(snapshot_id),
+ snapshot,
tag_create_time: None,
tag_time_retained: request.time_retained,
},
@@ -1146,11 +1194,85 @@ impl RESTServer {
(StatusCode::OK, Json(json!(""))).into_response()
}
- pub async fn get_tag(
- Path((db, table, tag)): Path<(String, String, String)>,
+ /// The snapshot a new tag points at: the catalog's current snapshot when
no
+ /// id is requested or the id matches it, then table storage when the table
+ /// has snapshot files, otherwise a placeholder snapshot 1.
+ async fn tag_target(
+ location: Option<String>,
+ catalog_snapshot: Option<Snapshot>,
+ snapshot_id: Option<i64>,
+ ) -> Option<Snapshot> {
+ if let Some(snapshot) =
+ catalog_snapshot.filter(|snapshot| snapshot_id.is_none_or(|id| id
== snapshot.id()))
+ {
+ return Some(snapshot);
+ }
+ let file_io = location
+ .as_deref()
+ .and_then(|location|
paimon::io::FileIO::from_path(location).ok()?.build().ok());
+ if let (Some(location), Some(file_io)) = (location, file_io) {
+ let manager = paimon::table::SnapshotManager::new(file_io,
location);
+ if !manager.list_all_ids().await.unwrap_or_default().is_empty() {
+ return match snapshot_id {
+ None => manager.get_latest_snapshot().await.ok().flatten(),
+ Some(id) => manager.get_snapshot(id).await.ok(),
+ };
+ }
+ }
+ (snapshot_id.unwrap_or(1) == 1).then(|| tag_snapshot(1))
+ }
+
+ /// List tag names in pages of `maxResults` (default 2, so clients must
+ /// follow tokens). The token is the last name of the previous page.
+ pub async fn list_tags(
+ Path((db, table)): Path<(String, String)>,
+ Query(params): Query<HashMap<String, String>>,
Extension(state): Extension<Arc<RESTServer>>,
) -> impl IntoResponse {
let state = state.inner.lock().unwrap();
+ if let Some(error) = state.tag_read_error.clone() {
+ return Self::error_response(error);
+ }
+ if !state.tables.contains_key(&format!("{db}.{table}")) {
+ return resource_error(StatusCode::NOT_FOUND, "TABLE", &table);
+ }
+ let prefix = format!("{db}.{table}.");
+ let mut names: Vec<String> = state
+ .tags
+ .keys()
+ .filter_map(|key| key.strip_prefix(&prefix))
+ .map(str::to_string)
+ .collect();
+ names.sort();
+ let page_size = params
+ .get("maxResults")
+ .and_then(|value| value.parse().ok())
+ .unwrap_or(2);
+ let mut remaining = names
+ .into_iter()
+ .filter(|name| params.get("pageToken").is_none_or(|token| name >
token));
+ let page: Vec<String> = remaining.by_ref().take(page_size).collect();
+ let next_page_token = remaining.next().and_then(|_|
page.last().cloned());
+ let response = paimon::api::ListTagsResponse {
+ tags: Some(page),
+ next_page_token,
+ };
+ (StatusCode::OK, Json(response)).into_response()
+ }
+
+ pub async fn get_tag(
+ Path((db, table, _)): Path<(String, String, String)>,
+ OriginalUri(uri): OriginalUri,
+ Extension(state): Extension<Arc<RESTServer>>,
+ ) -> impl IntoResponse {
+ let tag = tag_name_from_uri(&uri);
+ let mut state = state.inner.lock().unwrap();
+ state
+ .get_tag_calls
+ .push((db.clone(), table.clone(), tag.clone()));
+ if let Some(error) = state.tag_read_error.clone() {
+ return Self::error_response(error);
+ }
if !state.tables.contains_key(&format!("{db}.{table}")) {
return resource_error(StatusCode::NOT_FOUND, "table", &table);
}
@@ -1161,10 +1283,18 @@ impl RESTServer {
}
pub async fn delete_tag(
- Path((db, table, tag)): Path<(String, String, String)>,
+ Path((db, table, _)): Path<(String, String, String)>,
+ OriginalUri(uri): OriginalUri,
Extension(state): Extension<Arc<RESTServer>>,
) -> impl IntoResponse {
+ let tag = tag_name_from_uri(&uri);
let mut state = state.inner.lock().unwrap();
+ state
+ .delete_tag_calls
+ .push((db.clone(), table.clone(), tag.clone()));
+ if let Some(error) = state.tag_mutation_error.clone() {
+ return Self::error_response(error);
+ }
if !state.tables.contains_key(&format!("{db}.{table}")) {
return resource_error(StatusCode::NOT_FOUND, "table", &table);
}
@@ -2437,6 +2567,74 @@ impl RESTServer {
);
}
+ /// Serve a current snapshot from the catalog independently of table
storage.
+ pub fn set_catalog_snapshot(&self, database: &str, table: &str, snapshot:
Snapshot) {
+ self.inner
+ .lock()
+ .unwrap()
+ .catalog_snapshots
+ .insert(format!("{database}.{table}"), snapshot);
+ }
+
+ /// Set the REST metadata of a tag registered in the mock catalog.
+ pub fn set_tag_metadata(
+ &self,
+ database: &str,
+ table: &str,
+ tag: &str,
+ create_time: Option<i64>,
+ time_retained: Option<&str>,
+ ) {
+ let mut state = self.inner.lock().unwrap();
+ let response = state
+ .tags
+ .get_mut(&format!("{database}.{table}.{tag}"))
+ .unwrap();
+ response.tag_create_time = create_time;
+ response.tag_time_retained = time_retained.map(str::to_string);
+ }
+
+ /// Make tag reads and listings answer with `error` (status from its
`code`).
+ pub fn set_tag_read_error(&self, error: Option<ErrorResponse>) {
+ self.inner.lock().unwrap().tag_read_error = error;
+ }
+
+ /// Tags of `database.table` known to the catalog, sorted by name.
+ pub fn tags(&self, database: &str, table: &str) -> Vec<GetTagResponse> {
+ let prefix = format!("{database}.{table}.");
+ let mut tags: Vec<_> = self
+ .inner
+ .lock()
+ .unwrap()
+ .tags
+ .iter()
+ .filter(|(key, _)| key.starts_with(&prefix))
+ .map(|(_, tag)| tag.clone())
+ .collect();
+ tags.sort_by(|a, b| a.tag_name.cmp(&b.tag_name));
+ tags
+ }
+
+ /// Tag-create attempts received by the server, including failed requests.
+ pub fn create_tag_calls(&self) -> Vec<(String, String, CreateTagRequest)> {
+ self.inner.lock().unwrap().create_tag_calls.clone()
+ }
+
+ /// Tag-get attempts received by the server, including failed requests.
+ pub fn get_tag_calls(&self) -> Vec<(String, String, String)> {
+ self.inner.lock().unwrap().get_tag_calls.clone()
+ }
+
+ /// Tag-delete attempts received by the server, including failed requests.
+ pub fn delete_tag_calls(&self) -> Vec<(String, String, String)> {
+ self.inner.lock().unwrap().delete_tag_calls.clone()
+ }
+
+ /// Make every tag create or delete answer with `error` (status from its
`code`).
+ pub fn set_tag_mutation_error(&self, error: Option<ErrorResponse>) {
+ self.inner.lock().unwrap().tag_mutation_error = error;
+ }
+
/// Register a branch of `database.table` in the catalog.
pub fn add_branch(&self, database: &str, table: &str, branch: &str) {
self.inner
@@ -2616,7 +2814,7 @@ pub async fn start_mock_server(
)
.route(
&format!("{prefix}/databases/:db/tables/:table/tags"),
- post(RESTServer::create_tag),
+ get(RESTServer::list_tags).post(RESTServer::create_tag),
)
.route(
&format!("{prefix}/databases/:db/tables/:table/tags/:tag"),
diff --git a/crates/paimon/tests/rest_branch_test.rs
b/crates/paimon/tests/rest_branch_test.rs
index 7dbfde17..215cde89 100644
--- a/crates/paimon/tests/rest_branch_test.rs
+++ b/crates/paimon/tests/rest_branch_test.rs
@@ -25,7 +25,7 @@ use axum::extract::State;
use axum::http::{header, HeaderMap, Method, StatusCode, Uri};
use axum::response::{IntoResponse, Response};
use axum::Router;
-use paimon::api::RestError;
+use paimon::api::{rest_api::RESTApi, RestError};
use paimon::catalog::{Catalog, Identifier, RESTCatalog};
use paimon::common::Options;
use paimon::Error;
@@ -222,6 +222,90 @@ async fn tag_page_nulls_and_empty_parameters_match_java() {
}
}
+#[tokio::test]
+async fn all_tag_pages_stop_on_empty_tokens_or_pages() {
+ for (response, expected) in [
+ (json!({"tags":["release"]}), vec!["release"]),
+ (
+ json!({"tags":["release"],"nextPageToken":""}),
+ vec!["release"],
+ ),
+ (json!({"tags":[],"nextPageToken":"unused"}), vec![]),
+ (json!({"tags":null,"nextPageToken":"unused"}), vec![]),
+ (json!({"nextPageToken":"unused"}), vec![]),
+ ] {
+ let ctx = TestCatalog::new(vec![(StatusCode::OK, response)]).await;
+ let names = tokio::time::timeout(
+ std::time::Duration::from_secs(5),
+ ctx.api.list_tags(&Identifier::new("db", "t")),
+ )
+ .await
+ .expect("tag pagination did not terminate")
+ .unwrap();
+ assert_eq!(names, expected);
+ assert_eq!(ctx.requests().len(), 1);
+ }
+}
+
+#[tokio::test]
+async fn all_tag_pages_preserve_names_order_and_opaque_tokens() {
+ let token = "next +/%一";
+ let ctx = TestCatalog::new(vec![
+ (
+ StatusCode::OK,
+ json!({"tags":["z","a"],"nextPageToken":token}),
+ ),
+ (StatusCode::OK, json!({"tags":["a","一"]})),
+ ])
+ .await;
+ assert_eq!(
+ ctx.api
+ .list_tags(&Identifier::new("db", "t$branch_dev"))
+ .await
+ .unwrap(),
+ ["z", "a", "a", "一"]
+ );
+ let requests = ctx.requests();
+ assert_eq!(requests.len(), 2);
+ assert!(requests[0].uri.ends_with("t%24branch_dev/tags"));
+ let url = reqwest::Url::parse(&format!("http://server{}",
requests[1].uri)).unwrap();
+ assert_eq!(
+ url.query_pairs().collect::<Vec<_>>(),
+ [("pageToken".into(), token.into())]
+ );
+}
+
+#[tokio::test]
+async fn all_tag_pages_reject_repeated_or_cyclic_tokens() {
+ for tokens in [vec!["same", "same"], vec!["a", "b", "a"]] {
+ let ctx = TestCatalog::new(
+ tokens
+ .iter()
+ .map(|token| {
+ (
+ StatusCode::OK,
+ json!({"tags":["release"],"nextPageToken":token}),
+ )
+ })
+ .collect(),
+ )
+ .await;
+ let error = tokio::time::timeout(
+ std::time::Duration::from_secs(5),
+ ctx.api.list_tags(&Identifier::new("db", "t")),
+ )
+ .await
+ .expect("tag pagination did not terminate")
+ .unwrap_err();
+ assert!(
+ matches!(error, Error::UnexpectedError { ref message, .. }
+ if message.contains("tag page token") && message.contains("more
than once")),
+ "{error}"
+ );
+ assert_eq!(ctx.requests().len(), tokens.len());
+ }
+}
+
#[tokio::test]
async fn tag_page_errors_are_table_errors_and_keep_permissions() {
for status in [StatusCode::NOT_FOUND, StatusCode::FORBIDDEN] {
@@ -348,6 +432,25 @@ async fn
tag_retention_and_metadata_are_opaque_and_mutations_ignore_success_bodi
assert_eq!(requests[2].method, Method::DELETE);
}
+#[tokio::test]
+async fn tag_response_for_another_name_is_rejected() {
+ let ctx = TestCatalog::new_raw(vec![(
+ StatusCode::OK,
+ json!({"tagName":"other","snapshot":version_snapshot(7)}).to_string(),
+ )])
+ .await;
+ let error = ctx
+ .catalog
+ .get_tag(&Identifier::new("db", "t"), "release")
+ .await
+ .unwrap_err();
+ assert!(
+ matches!(error, Error::DataInvalid { ref message, .. }
+ if message.contains("returned tag 'other' for requested tag
'release'")),
+ "{error}"
+ );
+}
+
#[tokio::test]
async fn version_paths_reject_parent_resources_before_requests() {
use paimon::table::Instant;
@@ -371,6 +474,11 @@ async fn
version_paths_reject_parent_resources_before_requests() {
.is_err());
}
for name in ["", " ", ".", ".."] {
+ assert!(ctx
+ .catalog
+ .create_tag(&Identifier::new("db", "t"), name, None, false)
+ .await
+ .is_err());
assert!(ctx
.catalog
.get_tag(&Identifier::new("db", "t"), name)
@@ -400,6 +508,7 @@ struct ServerState {
struct TestCatalog {
catalog: RESTCatalog,
+ api: RESTApi,
state: Arc<Mutex<ServerState>>,
server: tokio::task::JoinHandle<()>,
}
@@ -459,9 +568,11 @@ impl TestCatalog {
options.set("prefix", "tenant /一");
options.set("token.provider", "bear");
options.set("token", "test-token");
+ let api = RESTApi::new(options.clone(), false).await.unwrap();
let catalog = RESTCatalog::new(options, false).await.unwrap();
Self {
catalog,
+ api,
state,
server,
}
diff --git a/crates/paimon/tests/rest_catalog/read_path_completion.rs
b/crates/paimon/tests/rest_catalog/read_path_completion.rs
index 97fa39c0..0b2c5133 100644
--- a/crates/paimon/tests/rest_catalog/read_path_completion.rs
+++ b/crates/paimon/tests/rest_catalog/read_path_completion.rs
@@ -502,9 +502,9 @@ async fn
authorized_pinned_snapshot_can_verify_a_retained_tag_after_expiry_or_id
)
.await;
let snapshot =
g.table.snapshot_manager().get_snapshot(1).await.unwrap();
- g.table
- .tag_manager()
- .create("before", &snapshot)
+ g.ctx
+ .catalog
+ .create_tag(&g.identifier, "before", Some(snapshot.id()), false)
.await
.unwrap();
let path = g.table.snapshot_manager().snapshot_path(1);
@@ -522,6 +522,16 @@ async fn
authorized_pinned_snapshot_can_verify_a_retained_tag_after_expiry_or_id
} else {
g.table.file_io().delete_file(&path).await.unwrap();
}
+ let retained = g
+ .ctx
+ .catalog
+ .get_tag(&g.identifier, "before")
+ .await
+ .unwrap();
+ assert_eq!(
+ serde_json::to_value(&retained.snapshot).unwrap(),
+ serde_json::to_value(&snapshot).unwrap()
+ );
let view = g.table.copy_with_pinned_snapshot(Some(&snapshot));
let rows = read_all(&view.new_read_builder()).await.unwrap();
assert_eq!(ids(&rows), [1]);
@@ -546,10 +556,18 @@ async fn
authorized_pinned_latest_can_use_rest_when_tag_metadata_is_unavailable(
std::fs::copy(file.path(),
destination.join(file.file_name())).unwrap();
}
}
- // The mount exposes data/manifests but no snapshot directory. An unrelated
- // malformed tag must not block validation through the REST snapshot
source.
+ // The mount exposes data/manifests but no snapshot directory. Unavailable
+ // catalog tags must not block validation through the REST snapshot source.
std::fs::create_dir_all(mounted.join("tag")).unwrap();
std::fs::write(mounted.join("tag/tag-broken"), "not snapshot
JSON").unwrap();
+ g.ctx
+ .server
+ .set_tag_read_error(Some(paimon::api::ErrorResponse::new(
+ None,
+ None,
+ Some("tag metadata unavailable".into()),
+ Some(501),
+ )));
let mut options = g.ctx.catalog.options().clone();
options.set("fuse.enabled", "true");
options.set("fuse.root", root.path().to_str().unwrap());
@@ -560,7 +578,11 @@ async fn
authorized_pinned_latest_can_use_rest_when_tag_metadata_is_unavailable(
.get_table(&g.identifier)
.await
.unwrap();
- assert!(table.tag_manager().list_all().await.is_err());
+ let error = table.tag_manager().list_all().await.unwrap_err();
+ assert!(
+ error.to_string().contains("tag metadata unavailable"),
+ "{error}"
+ );
let view = table.copy_with_pinned_snapshot(Some(&snapshot));
let rows = read_all(&view.new_read_builder()).await.unwrap();
assert_eq!(ids(&rows), [1]);
diff --git a/docs/src/sql.md b/docs/src/sql.md
index 71a66f58..713dd370 100644
--- a/docs/src/sql.md
+++ b/docs/src/sql.md
@@ -1459,10 +1459,16 @@ CALL sys.create_tag(
);
```
-When `time_retained` is specified, retention and tag creation time are
persisted in
-the tag file. For example, `'1d'` appears as `PT24H` in the `time_retained`
column
-of `$tags`. Omitting `time_retained` creates a tag without these metadata
fields.
-This procedure does not automatically delete expired tags.
+For filesystem-managed tables, specifying `time_retained` persists retention
and
+tag creation time in the tag file. For example, `'1d'` appears as `PT24H` in
the
+`time_retained` column of `$tags`. Omitting `time_retained` creates a tag
without
+these metadata fields. This procedure does not automatically delete expired
tags.
+
+For tables managed by a REST catalog, the tag is created through the catalog:
+`snapshot_id` and `time_retained` are forwarded unchanged, and the server
resolves
+the snapshot (the latest one when `snapshot_id` is omitted), validates
retention,
+and stores the tag. The table's `tag/` directory is not read or written. An
+existing tag name fails with `Tag '...' already exists`, as for other tables.
### replace_tag
@@ -1513,6 +1519,10 @@ Create a named tag from an epoch timestamp in
milliseconds (finds the earliest r
CALL sys.create_tag_from_timestamp(table => 'paimon.my_db.my_table', tag =>
'my_tag', timestamp => 1234567890000);
```
+This procedure is not supported for tables managed by a REST catalog. Their
+snapshots may exist only in the catalog, while timestamp selection currently
+relies on stored snapshot files.
+
### create_tag_from_watermark
This procedure is not supported for tables managed by a REST catalog. Their
@@ -1554,6 +1564,23 @@ Delete a named tag:
CALL sys.delete_tag(table => 'paimon.my_db.my_table', tag => 'my_tag');
```
+`tag` accepts a comma-separated list. Each name is trimmed, empty names are
+skipped, and missing tags are ignored. For tables managed by a REST catalog,
+each tag is deleted through the catalog, and the table's `tag/` directory is
not
+read or written. Any other error stops the batch; earlier deletions are not
+rolled back.
+
+### rename_tag
+
+Rename a tag:
+
+```sql
+CALL sys.rename_tag(table => 'paimon.my_db.my_table', tag => 'old_tag',
target_tag => 'new_tag');
+```
+
+The source tag must exist and the target tag must not. This procedure is not
+supported for tables managed by a REST catalog, which has no tag-rename
endpoint.
+
### rollback_to
Rollback a table to a specific snapshot or tag:
@@ -1574,6 +1601,10 @@ Rollback a table to an epoch timestamp in milliseconds
(selects the latest retai
CALL sys.rollback_to_timestamp(table => 'paimon.my_db.my_table', timestamp =>
1234567890000);
```
+This procedure is not supported for tables managed by a REST catalog, for the
+same reason as `create_tag_from_timestamp`. Use `rollback_to` with an explicit
+`snapshot_id` or `tag` instead.
+
Both timestamp procedures take epoch milliseconds. The `$snapshots.commit_time`
column is a local `TIMESTAMP`; its raw Arrow value includes the local timezone
offset and must not be passed directly as an epoch timestamp.
@@ -2898,7 +2929,16 @@ Use a quoted tag name with `VERSION AS OF`:
SELECT * FROM paimon.default.my_table VERSION AS OF 'my_tag';
```
-Resolution order: first checks if a tag with that name exists, then tries to
parse it as a snapshot ID.
+Resolution order: first resolves a tag with that name, then tries
+`watermark-<value>` or a numeric snapshot ID.
+
+For tables managed by a REST catalog, tags named by `VERSION AS OF` or
+`scan.tag-name` are resolved through the catalog; tag files in table storage
are
+ignored. Legacy tags named `.` or `..` cannot be resolved through the REST API.
+If the tag endpoint returns HTTP 501, `scan.version` (including `VERSION AS
OF`)
+can still resolve a numeric snapshot ID or `watermark-<value>` from stored
+snapshots. `scan.tag-name` always requires the tag endpoint, including for
+numeric tag names. Other catalog errors fail the query.
### By Timestamp
@@ -3170,6 +3210,17 @@ Columns:
| `create_time` | TIMESTAMP | Tag creation time; `NULL` for tags written
without one |
| `time_retained` | STRING | Tag retention as an ISO-8601 duration (for
example `PT72H`); `NULL` for tags written without one |
+For tables managed by a REST catalog, the tags are listed from the catalog
+rather than from tag files in table storage. Legacy tags named `.` or `..`,
which
+cannot be addressed safely by the REST API, are omitted with a warning so they
+cannot prevent other tags from being queried. Their storage files are ignored,
+and direct time travel by these legacy names is rejected.
+
+`create_time` is a local `TIMESTAMP` without a timezone. REST catalog creation
+times are converted from epoch milliseconds to the client's local time,
matching
+the local date-time fields in filesystem tag metadata. Its raw Arrow integer is
+not an epoch timestamp.
+
### $branches
View all branches of a table:
@@ -3342,10 +3393,19 @@ Columns:
| `index_file_size` | BIGINT | Total size of index files (bytes) |
The output contains one row per scope:
-- `total` — sum across all branches and tags
+- `total` — unique referenced files across all branches and tags
- `branch:main` — main branch snapshots + tag snapshots
- `branch:<name>` — one row per other branch
+For tables managed by a REST catalog, branches and tags come from the catalog,
+including branches with no corresponding storage directory. Current snapshots
+and tag snapshots returned by the catalog are counted even when their snapshot
+files are absent, together with the snapshot history visible in table storage.
+REST metadata API failures, including HTTP 501, fail the query rather than
return
+an incomplete count. Invalid or unaddressable branch names also fail the query.
+Legacy `.` or `..` tags fail this query because their catalog snapshots cannot
+be read safely; they are not replaced by storage files.
+
To estimate possible orphan file size for recognized data files:
```sql