mbutrovich commented on code in PR #3812:
URL: https://github.com/apache/iceberg-rust/pull/3812#discussion_r4801951547
##########
crates/catalog/hms/src/catalog.rs:
##########
@@ -458,10 +415,9 @@ impl Catalog for HmsCatalog {
}
self.client
- .0
- .drop_database(name.into(), false, false)
+ .drop_database(&name, DropDatabaseOptions::new())
.await
- .map_err(from_thrift_error)?;
+ .map_err(from_hms_error)?;
Review Comment:
Dropping a namespace that still has tables now fails with HMS's
`InvalidOperationException`, where `main` returned `Ok` and left the database
in place. The description says you checked this on Hive 3.1.3 and 4.0.0, but no
test covers it. Could we add one? `namespace_suite.rs` has no non-empty drop
case yet, and a case there with HMS enabled follows how this repo tests catalog
behavior.
##########
crates/catalog/hms/src/catalog.rs:
##########
@@ -548,10 +502,9 @@ impl Catalog for HmsCatalog {
)?;
self.client
- .0
- .create_table(hive_table)
+ .create_table(&hive_table)
.await
- .map_err(from_thrift_error)?;
+ .map_err(from_hms_error)?;
Review Comment:
`create_table` doesn't check whether the table exists, so creating a table
that's already registered reaches this call. On `main` that returned `Ok`
([`catalog.rs`](https://github.com/apache/iceberg-rust/blob/6cca8cdec6881d057581bdf9cc21c3ad426c0283/crates/catalog/hms/src/catalog.rs#L550-L554)).
It now fails, but as `Unexpected`. Should we map `AlreadyExistsException` to
`TableAlreadyExists`, as Java does
([`HiveTableOperations`](https://github.com/apache/iceberg/blob/9203eaff9eb97fef9d1f5a3ef4460e8453adaed9/hive-metastore/src/main/java/org/apache/iceberg/hive/HiveTableOperations.java#L345-L346))?
`create_namespace` has the same gap when another client creates the namespace
between the `namespace_exists` check and `create_database` (Java maps it in
[`HiveCatalog`](https://github.com/apache/iceberg/blob/9203eaff9eb97fef9d1f5a3ef4460e8453adaed9/hive-metastore/src/main/java/org/apache/iceberg/hive/HiveCatalog.java#L550-L551)).
A test that creates the same table twice and checks the k
ind would cover it.
```suggestion
self.client
.create_table(&hive_table)
.await
.map_err(|error| {
if error.is_already_exists() {
Error::new(
ErrorKind::TableAlreadyExists,
format!("Table {db_name}.{table_name} already
exists"),
)
.with_source(error)
} else {
from_hms_error(error)
}
})?;
```
While reading this I also noticed that the metadata file written a few lines
above stays behind when this call fails. That predates this PR. Could we delete
it on the error path here? The uncertain case has to keep the file, because HMS
may have registered the table.
##########
crates/catalog/hms/src/catalog.rs:
##########
@@ -582,16 +535,9 @@ impl Catalog for HmsCatalog {
let hive_table = self
.client
- .0
- .get_table_req(GetTableRequest {
- db_name: db_name.clone().into(),
- tbl_name: table.name.clone().into(),
- ..Default::default()
- })
+ .get_table(&db_name, &table.name)
.await
- .map(from_thrift_exception)
- .map_err(from_thrift_error)??
- .table;
+ .map_err(from_hms_error)?;
Review Comment:
`load_table` on a missing table still returns `Unexpected`, as it did on
`main`. This PR already maps not-found errors for `get_namespace` and
`table_exists`, so could we do the same here and return `TableNotFound`?
`purge_table` goes through `load_table` and would get the fix too.
`rename_table` has the same pattern for a missing source table at line 636.
```suggestion
let hive_table = match self.client.get_table(&db_name,
&table.name).await {
Ok(hive_table) => hive_table,
Err(error) if error.is_not_found() => {
return Err(Error::new(
ErrorKind::TableNotFound,
format!("Table {table:?} does not exist"),
));
}
Err(error) => return Err(from_hms_error(error)),
};
```
##########
crates/catalog/hms/src/error.rs:
##########
@@ -15,41 +15,32 @@
// specific language governing permissions and limitations
// under the License.
-use std::fmt::Debug;
-use std::io;
-
-use anyhow::anyhow;
+use hive_metastore::Error as HmsError;
+use hive_metastore::error::ServerError;
use iceberg::{Error, ErrorKind};
-use volo_thrift::MaybeException;
-/// Format a thrift error into iceberg error.
+/// Format an HMS client error into an iceberg error.
+///
+/// Please only throw this error when you are sure that the error came from
HMS.
///
-/// Please only throw this error when you are sure that the error is caused by
thrift.
-pub fn from_thrift_error(error: impl std::error::Error) -> Error {
+/// The original [`HmsError`] is attached as the source so callers can inspect
+/// the typed failure, such as whether a write may have been applied.
+pub fn from_hms_error(error: HmsError) -> Error {
Error::new(
ErrorKind::Unexpected,
"Operation failed for hitting thrift error".to_string(),
)
- .with_source(anyhow!("thrift error: {error:?}"))
+ .with_source(error)
}
-/// Format a thrift exception into iceberg error.
-pub fn from_thrift_exception<T, E: Debug>(value: MaybeException<T, E>) ->
Result<T, Error> {
- match value {
- MaybeException::Ok(v) => Ok(v),
- MaybeException::Exception(err) => Err(Error::new(
- ErrorKind::Unexpected,
- "Operation failed for hitting thrift error".to_string(),
+/// Returns `true` when HMS reported that the requested object does not exist.
+pub(crate) fn is_not_found(error: &HmsError) -> bool {
+ matches!(
+ error.server_error(),
+ Some(
+ ServerError::NoSuchObjectException { .. }
+ | ServerError::UnknownDbException { .. }
+ | ServerError::UnknownTableException { .. }
)
- .with_source(anyhow!("thrift error: {err:?}"))),
- }
-}
-
-/// Format an io error into iceberg error.
-pub fn from_io_error(error: io::Error) -> Error {
- Error::new(
- ErrorKind::Unexpected,
- "Operation failed for hitting io error".to_string(),
)
- .with_source(error)
}
Review Comment:
`hive_metastore::Error` already has
[`is_not_found`](https://github.com/Xuanwo/hive_metastore_rs/blob/b904cc7da48d49de060c53a1220ec12def9fcd31/src/error.rs#L159-L180),
which matches these three exceptions plus `UnknownPartitionException` and
`NoSuchLockException`. Could we call `error.is_not_found()` at the four call
sites and drop this helper?
##########
crates/catalog/hms/src/catalog.rs:
##########
@@ -212,29 +205,22 @@ impl HmsCatalog {
runtime: Runtime,
kms_client: Option<Arc<dyn KeyManagementClient>>,
) -> Result<Self> {
- let address = config
- .address
- .as_str()
- .to_socket_addrs()
- .map_err(from_io_error)?
- .next()
- .ok_or_else(|| {
- Error::new(
- ErrorKind::Unexpected,
- format!("invalid address: {}", config.address),
- )
- })?;
-
- let builder =
ThriftHiveMetastoreClientBuilder::new("hms").address(address);
-
- let client = match &config.thrift_transport {
- HmsThriftTransport::Framed => builder
-
.make_codec(volo_thrift::codec::default::DefaultMakeCodec::framed())
- .build(),
- HmsThriftTransport::Buffered => builder
-
.make_codec(volo_thrift::codec::default::DefaultMakeCodec::buffered())
- .build(),
+ // `uri` accepts both the historical `host:port` form and an explicit
+ // `thrift://host:port` URI.
+ let uri = if config.address.contains("://") {
+ config.address.clone()
+ } else {
+ format!("thrift://{}", config.address)
};
+ let framing = match config.thrift_transport {
+ HmsThriftTransport::Framed => Framing::Framed,
+ HmsThriftTransport::Buffered => Framing::Buffered,
+ };
+ let client = Client::builder()
+ .uri(uri)
+ .framing(framing)
+ .build()
+ .map_err(from_hms_error)?;
Review Comment:
This client uses the crate's default deadlines: 10 s to connect, 30 s per
attempt, and 60 s per call
([defaults](https://github.com/Xuanwo/hive_metastore_rs/blob/b904cc7da48d49de060c53a1220ec12def9fcd31/src/client/mod.rs#L99-L101)).
Hive's Java client waits 600 s by default
([`hive.metastore.client.socket.timeout`](https://github.com/apache/hive/blob/04c1b307d1bbd1ae268ad47dc36ca4f50c6d9cd8/standalone-metastore/src/main/java/org/apache/hadoop/hive/metastore/conf/MetastoreConf.java#L334-L335)).
An HMS call that takes longer than 30 s, for example on a loaded metastore,
now fails, and a write that times out comes back as an uncertain outcome. Users
have no catalog property to raise the limits. Should we expose the three
timeouts as catalog properties next to `uri` and `thrift_transport`, or set
them to Hive's default here?
##########
crates/catalog/hms/src/utils.rs:
##########
@@ -110,100 +107,137 @@ pub(crate) fn convert_to_database(
let name = validate_namespace(namespace)?;
validate_owner_settings(properties)?;
- let mut db = Database::default();
- let mut parameters = AHashMap::new();
-
- db.name = Some(name.into());
+ let mut db = Database::builder(name).build();
- for (k, v) in properties {
- match k.as_str() {
- COMMENT => db.description = Some(v.clone().into()),
- LOCATION => db.location_uri =
Some(format_location_uri(v.clone()).into()),
- HMS_DB_OWNER => db.owner_name = Some(v.clone().into()),
+ for (key, value) in properties {
+ match key.as_str() {
+ COMMENT => db.description = Some(value.clone()),
+ LOCATION => db.location_uri =
Some(format_location_uri(value.clone())),
+ HMS_DB_OWNER => db.owner_name = Some(value.clone()),
HMS_DB_OWNER_TYPE => {
- let owner_type = match v.to_lowercase().as_str() {
+ let owner_type = match value.to_lowercase().as_str() {
"user" => PrincipalType::USER,
"group" => PrincipalType::GROUP,
"role" => PrincipalType::ROLE,
_ => {
return Err(Error::new(
ErrorKind::DataInvalid,
- format!("Invalid value for setting 'owner_type':
{v}"),
+ format!("Invalid value for setting 'owner_type':
{value}"),
));
}
};
db.owner_type = Some(owner_type);
}
_ => {
- parameters.insert(
- FastStr::from_string(k.clone()),
- FastStr::from_string(v.clone()),
- );
+ db.parameters.insert(key.clone(), value.clone());
}
}
}
- db.parameters = Some(parameters);
-
// Set default owner, if none provided
//
https://github.com/apache/iceberg/blob/main/hive-metastore/src/main/java/org/apache/iceberg/hive/HiveHadoopUtil.java#L44
if db.owner_name.is_none() {
- db.owner_name = Some(HMS_DEFAULT_DB_OWNER.into());
+ db.owner_name = Some(HMS_DEFAULT_DB_OWNER.to_string());
db.owner_type = Some(PrincipalType::USER);
}
Ok(db)
Review Comment:
`apply_database_properties` repeats this loop and the default-owner rule. On
a fresh `Database`, `owner_name` is `None` exactly when `properties` has no
owner key, so the two functions give the same result. Could
`convert_to_database` delegate to it, so the owner-type parsing lives in one
place? The `HiveHadoopUtil` link would move to the default-owner comment in
`apply_database_properties`.
```suggestion
let name = validate_namespace(namespace)?;
let mut db = Database::builder(name).build();
apply_database_properties(&mut db, properties)?;
Ok(db)
```
##########
crates/catalog/hms/tests/hms_catalog_test.rs:
##########
@@ -115,3 +121,306 @@ async fn test_get_default_namespace() -> Result<()> {
Ok(())
}
+
+async fn raw_hms_client() -> HmsClient {
+ let endpoint = get_hms_endpoint();
+ let uri = if endpoint.contains("://") {
+ endpoint
+ } else {
+ format!("thrift://{endpoint}")
+ };
+ HmsClient::builder().uri(uri).build().unwrap()
+}
+
+#[tokio::test]
+async fn test_update_namespace_uses_full_property_set() -> Result<()> {
+ let catalog = get_catalog().await;
+ let namespace =
NamespaceIdent::new("catalog_update_namespace_full_set_hms".into());
+ let name = namespace.as_ref()[0].as_str();
+
+ let _ = catalog.drop_namespace(&namespace).await;
+
+ let properties = HashMap::from([
+ (
+ "comment".to_string(),
+ "created for full property update".to_string(),
+ ),
+ (
+ "hive.metastore.database.owner".to_string(),
+ "public".to_string(),
+ ),
+ (
+ "hive.metastore.database.owner-type".to_string(),
+ "Role".to_string(),
+ ),
+ ("custom.keep".to_string(), "keep-me".to_string()),
+ ("custom.remove".to_string(), "remove-me".to_string()),
+ ("custom.change".to_string(), "old-value".to_string()),
+ ]);
+ catalog.create_namespace(&namespace, properties).await?;
+
+ let hms = raw_hms_client().await;
+ let before = hms.get_database(name).await.unwrap();
+ let before_location = before
+ .location_uri
+ .as_deref()
+ .expect("HMS returns a location");
+ assert!(before_location.starts_with("s3a://"));
+ assert_eq!(before.owner_name.as_deref(), Some("public"));
+ assert_eq!(before.owner_type, Some(PrincipalType::ROLE));
+
+ // Start from the full property set the catalog reports, then edit only
+ // custom keys. Removing a key must remove it from HMS as well.
+ let mut updated = catalog
+ .get_namespace(&namespace)
+ .await?
+ .properties()
+ .clone();
+ updated.remove("custom.remove");
+ updated.insert("custom.change".to_string(), "new-value".to_string());
+ updated.insert("custom.add".to_string(), "added-value".to_string());
+
+ catalog.update_namespace(&namespace, updated).await?;
+
+ let after = hms.get_database(name).await.unwrap();
+ let mut expected = before.clone();
+ expected.parameters = std::collections::BTreeMap::from([
+ ("custom.keep".to_string(), "keep-me".to_string()),
+ ("custom.change".to_string(), "new-value".to_string()),
+ ("custom.add".to_string(), "added-value".to_string()),
+ ]);
+ assert_eq!(
+ after, expected,
+ "the full property update must replace custom parameters and keep
every other HMS field"
+ );
+ assert_eq!(
+ after.location_uri, before.location_uri,
+ "a qualified namespace location must survive the update byte-for-byte"
+ );
+
+ let fetched = catalog.get_namespace(&namespace).await?;
+ assert!(
+ !fetched.properties().contains_key("custom.remove"),
+ "a custom parameter removed from the full set must not survive"
+ );
+ assert_eq!(
+ fetched.properties().get("custom.keep"),
+ Some(&"keep-me".to_string())
+ );
+ assert_eq!(
+ fetched.properties().get("custom.change"),
+ Some(&"new-value".to_string())
+ );
+ assert_eq!(
+ fetched.properties().get("custom.add"),
+ Some(&"added-value".to_string())
+ );
+ assert_eq!(
+ fetched.properties().get("location"),
+ Some(&before_location.to_string()),
+ "the public location must match the unchanged stored URI"
+ );
+
+ // A full set with no custom keys clears the whole parameter map.
+ let mut cleared = fetched.properties().clone();
+ for key in ["custom.keep", "custom.change", "custom.add"] {
+ cleared.remove(key);
+ }
+ catalog.update_namespace(&namespace, cleared).await?;
+
+ let after_clear = hms.get_database(name).await.unwrap();
+ assert!(
+ after_clear.parameters.is_empty(),
+ "an empty custom property set must clear all managed parameters"
+ );
+ assert_eq!(after_clear.location_uri, before.location_uri);
+ assert_eq!(after_clear.owner_name, before.owner_name);
+ assert_eq!(after_clear.owner_type, before.owner_type);
+
+ let fetched = catalog.get_namespace(&namespace).await?;
+ assert!(!fetched.properties().contains_key("custom.keep"));
+ assert_eq!(
+ fetched.properties().get("location"),
+ Some(&before_location.to_string())
+ );
+
+ catalog.drop_namespace(&namespace).await?;
+
+ Ok(())
+}
+
+#[tokio::test]
+async fn test_ambiguous_write_keeps_typed_hms_error_source() {
+ use std::error::Error as _;
+
+ use tokio::io::AsyncReadExt;
+
+ // A peer that reads part of a request and disconnects leaves the outcome
+ // of a write unknown. The catalog must keep that ambiguity inspectable
+ // instead of flattening it into a string.
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ while let Ok((mut socket, _)) = listener.accept().await {
+ let mut request = [0_u8; 512];
+ let _ = socket.read(&mut request).await;
+ drop(socket);
+ }
+ });
+
+ let props = HashMap::from([
+ (
+ HMS_CATALOG_PROP_URI.to_string(),
+ format!("thrift://{address}"),
+ ),
+ (
+ HMS_CATALOG_PROP_THRIFT_TRANSPORT.to_string(),
+ THRIFT_TRANSPORT_BUFFERED.to_string(),
+ ),
+ (
+ HMS_CATALOG_PROP_WAREHOUSE.to_string(),
+ "memory://hive".to_string(),
+ ),
+ ]);
+ let catalog = HmsCatalogBuilder::default()
+ .with_storage_factory(Arc::new(iceberg::io::MemoryStorageFactory))
+ .load("hms", props)
+ .await
+ .unwrap();
+
+ // `create_table` with an explicit location writes the metadata file and
+ // then sends `create_table`, the first HMS RPC it makes. The in-memory
+ // storage keeps this test on the catalog and error boundary.
+ let schema = iceberg::spec::Schema::builder()
+ .with_fields(vec![
+ iceberg::spec::NestedField::required(
+ 1,
+ "id",
+
iceberg::spec::Type::Primitive(iceberg::spec::PrimitiveType::Long),
+ )
+ .into(),
+ ])
+ .build()
+ .unwrap();
+ let creation = iceberg::TableCreation::builder()
+ .name("ambiguous_write_table".to_string())
+ .schema(schema)
+ .location("memory://ambiguous_write_table".to_string())
+ .build();
+
+ let error = catalog
+ .create_table(&NamespaceIdent::new("default".into()), creation)
+ .await
+ .expect_err("the peer never replies to the write");
+
+ assert_eq!(error.kind(), iceberg::ErrorKind::Unexpected);
+ assert!(
+ !error.retryable(),
+ "an ambiguous write must not be retried automatically"
+ );
Review Comment:
`from_hms_error` never sets `retryable`, and `Error::new` defaults it to
`false`
([`error.rs`](https://github.com/apache/iceberg-rust/blob/83a2f70686780d4007dd4610362893b31abcbd21/crates/iceberg/src/error.rs#L236)),
so this assert passes for every HMS error. The `is_uncertain` check below is
what tests the ambiguous write. Could we drop it?
```suggestion
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]