Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion kernel/src/actions/domain_metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ pub(crate) fn domain_metadata_configuration(
/// Scan the entire log for all domain metadata actions but terminate early if a specific domain
/// is provided. Note that this returns the latest domain metadata for each domain, accounting for
/// tombstones (removed=true) - that is, removed domain metadatas will _never_ be returned.
fn scan_domain_metadatas(
pub(crate) fn scan_domain_metadatas(
log_segment: &LogSegment,
domain: Option<&str>,
engine: &dyn Engine,
Expand Down
17 changes: 17 additions & 0 deletions kernel/src/actions/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -939,6 +939,15 @@ impl DomainMetadata {
}
}

// Create a new DomainMetadata action to remove a domain.
pub(crate) fn remove(domain: String, configuration: String) -> Self {
Self {
domain,
configuration,
removed: true,
}
}

// returns true if the domain metadata is an system-controlled domain (all domains that start
// with "delta.")
#[allow(unused)]
Expand All @@ -949,6 +958,14 @@ impl DomainMetadata {
pub(crate) fn domain(&self) -> &str {
&self.domain
}

pub(crate) fn configuration(&self) -> &str {
&self.configuration
}

pub(crate) fn is_removed(&self) -> bool {
self.removed
}
}

#[cfg(test)]
Expand Down
72 changes: 59 additions & 13 deletions kernel/src/transaction/mod.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use std::iter;
use std::ops::Deref;
use std::sync::{Arc, LazyLock};

use url::Url;

use crate::actions::{
as_log_add_schema, get_log_commit_info_schema, get_log_domain_metadata_schema,
get_log_txn_schema, CommitInfo, DomainMetadata, SetTransaction,
as_log_add_schema, domain_metadata::scan_domain_metadatas, get_log_commit_info_schema,
get_log_domain_metadata_schema, get_log_txn_schema, CommitInfo, DomainMetadata, SetTransaction,
};
use crate::error::Error;
use crate::expressions::{ArrayData, Transform, UnaryExpressionOp::ToJson};
Expand Down Expand Up @@ -277,7 +277,27 @@ impl Transaction {
self
}

/// Remove domain metadata from the Delta log.
/// If the domain exists in the Delta log, this creates a tombstone to logically delete
/// the domain. The tombstone preserves the previous configuration value.
/// If the domain does not exist in the Delta log, this is a no-op.
/// Note that each domain can only appear once per transaction. That is, multiple operations
/// on the same domain are disallowed in a single transaction, as well as setting and removing
/// the same domain in a single transaction. If a duplicate domain is included, the `commit` will
/// fail (that is, we don't eagerly check domain validity here).
/// Removing metadata for multiple distinct domains is allowed.
pub fn with_domain_metadata_removed(mut self, domain: String) -> Self {
// actual configuration value determined during commit
self.domain_metadatas
.push(DomainMetadata::remove(domain, String::new()));
Comment on lines +290 to +292
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of having the dummy data and checking below whether we have a removal, why not maintain a separate removed_domains: HashSet<String> that we fill in after the log replay?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: only do this if we actually do need to preserve the removed domain metadata's configuration. See my comment here: https://github.com/delta-io/delta-kernel-rs/pull/1275/files#r2400384116

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

self
}

/// Generate domain metadata actions with validation. Handle both user and system domains.
///
/// This function may perform an expensive log replay operation if there are any domain removals.
/// The log replay is required to fetch the previous configuration value for the domain to preserve
/// in removal tombstones as mandated by the Delta spec.
fn generate_domain_metadata_actions<'a>(
&'a self,
engine: &'a dyn Engine,
Expand All @@ -295,32 +315,58 @@ impl Transaction {
));
}

// validate domain metadata
let mut domains = HashSet::new();
for domain_metadata in &self.domain_metadatas {
if domain_metadata.is_internal() {
// validate user domain metadata and check if we have removals
let mut seen_domains = HashSet::new();
let mut has_removals = false;
for dm in &self.domain_metadatas {
if dm.is_internal() {
return Err(Error::Generic(
"Cannot modify domains that start with 'delta.' as those are system controlled"
.to_string(),
));
}
if !domains.insert(domain_metadata.domain()) {

if !seen_domains.insert(dm.domain()) {
return Err(Error::Generic(format!(
"Metadata for domain {} already specified in this transaction",
domain_metadata.domain()
dm.domain()
)));
}
Comment on lines +322 to 334
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These feel like checks that should be done in with_domain_metadata:

  • if dm.is_internal()
  • if !seen_domains.insert(dm.domain())

Generally I prefer to fail early. Feel free to make this a followup issue.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I generally agree with the fail fast principle, but this case warrants an exception imo.

We're treating these methods as builder methods (return Self, even though there is no explicit build call) so we should present a fluent builder API. If we do the checking of the error conditions at this point, then we need to return DeltaResult<Self>, which is an awkward interface for both Rust (chaining requires try operator), but particularly for engines across the FFI boundary.

wdyt?


if dm.is_removed() {
has_removals = true;
}
Comment on lines +336 to +338
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Linearly checking domain metadatas can be avoided by maintaining a separate hashmap. See here

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's bottom out on deferred error checking or not above. Because if we choose to defer error checking, then we cannot make it a HashMap. If we decide to not defer, then will refactor accordingly.

}

// fetch previous configuration values (requires log replay)
let existing_domains = if has_removals {
scan_domain_metadatas(self.read_snapshot.log_segment(), None, engine)?
} else {
HashMap::new()
};
Comment on lines +341 to +346
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not convinced we need to verify that the domain metadata exists. After all, Delta never checks that a removed file is actually present. Is this something that we need to do? If so, can you put a comment explaining why we need to read the entire log and set the removed configuration?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added a comment (that the Delta spec requires it). let's bottom out on this in one of the above threads.


let user_domains = self
.domain_metadatas
.iter()
.filter_map(move |dm: &DomainMetadata| {
if dm.is_removed() {
existing_domains.get(dm.domain()).map(|existing| {
DomainMetadata::remove(
dm.domain().to_string(),
existing.configuration().to_string(),
)
})
} else {
Some(dm.clone())
}
});
Comment on lines +348 to +362
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can consume the domain_metadatas and avoid the clone since it seems like we don't use it anymore

Suggested change
let user_domains = self
.domain_metadatas
.iter()
.filter_map(move |dm: &DomainMetadata| {
if dm.is_removed() {
existing_domains.get(dm.domain()).map(|existing| {
DomainMetadata::remove(
dm.domain().to_string(),
existing.configuration().to_string(),
)
})
} else {
Some(dm.clone())
}
});
let user_domains = self
.domain_metadatas
.into_iter()
.filter_map(move |dm: DomainMetadata| {
if !dm.is_removed() {
return Some(dm);
}
existing_domains.get(dm.domain()).map(|existing| {
DomainMetadata::remove(
dm.domain().to_string(),
existing.configuration().to_string(),
)
})
});

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we decide to use removed_domains this becomes:
We can consume the domain_metadatas and avoid the clone since it seems like we don't use it anymore

Suggested change
let user_domains = self
.domain_metadatas
.iter()
.filter_map(move |dm: &DomainMetadata| {
if dm.is_removed() {
existing_domains.get(dm.domain()).map(|existing| {
DomainMetadata::remove(
dm.domain().to_string(),
existing.configuration().to_string(),
)
})
} else {
Some(dm.clone())
}
});
let user_domains = self
.removed_domains
.iter()
.map(move |domain_name: &str| {
existing_domains.get(domain_name).map(|existing| {
DomainMetadata::remove(
dm.domain().to_string(),
existing.configuration().to_string(),
)
})
})
.chain(domain_metadatas);

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will probably apply suggestion 1 or 2 depending on our takeaways from the other threads :)


let system_domains = row_tracking_high_watermark
.map(DomainMetadata::try_from)
.transpose()?
.into_iter();

Ok(self
.domain_metadatas
.iter()
.cloned()
Ok(user_domains
.chain(system_domains)
.map(|dm| dm.into_engine_data(get_log_domain_metadata_schema().clone(), engine)))
}
Expand Down
197 changes: 197 additions & 0 deletions kernel/tests/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1382,3 +1382,200 @@ async fn test_set_domain_metadata_unsupported_writer_feature(

Ok(())
}

#[tokio::test]
async fn test_remove_domain_metadata_non_existent_domain() -> Result<(), Box<dyn std::error::Error>>
{
let _ = tracing_subscriber::fmt::try_init();

let schema = Arc::new(StructType::try_new(vec![StructField::nullable(
"number",
DataType::INTEGER,
)])?);

let table_name = "test_domain_metadata_unsupported";

let (store, engine, table_location) = engine_store_setup(table_name, None);
let table_url = create_table(
store.clone(),
table_location,
schema.clone(),
&[],
true,
vec![],
vec!["domainMetadata"],
)
.await?;

let snapshot = Snapshot::builder_for(table_url.clone()).build(&engine)?;
let txn = snapshot.transaction()?;

let domain = "app.deprecated";

// removing domain metadata that doesn't exist should NOT write a tombstone
txn.with_domain_metadata_removed(domain.to_string())
.commit(&engine)?;

let commit_data = store
.get(&Path::from(format!(
"/{table_name}/_delta_log/00000000000000000001.json"
)))
.await?
.bytes()
.await?;
let actions: Vec<serde_json::Value> = Deserializer::from_slice(&commit_data)
.into_iter()
.try_collect()?;

let domain_action = actions.iter().find(|v| v.get("domainMetadata").is_some());
assert!(
domain_action.is_none(),
"No tombstone should be written for non-existent domain"
);

let final_snapshot = Snapshot::builder_for(table_url.clone()).build(&engine)?;
let config = final_snapshot.get_domain_metadata(domain, &engine)?;
assert_eq!(config, None);

Ok(())
}

#[tokio::test]
async fn test_domain_metadata_set_remove_conflicts() -> Result<(), Box<dyn std::error::Error>> {
let _ = tracing_subscriber::fmt::try_init();

let schema = Arc::new(StructType::try_new(vec![StructField::nullable(
"number",
DataType::INTEGER,
)])?);

let table_name = "test_domain_metadata_unsupported";

let (store, engine, table_location) = engine_store_setup(table_name, None);
let table_url = create_table(
store.clone(),
table_location,
schema.clone(),
&[],
true,
vec![],
vec!["domainMetadata"],
)
.await?;

let snapshot = Snapshot::builder_for(table_url.clone()).build(&engine)?;

// set then remove same domain
let txn = snapshot.clone().transaction()?;
let err = txn
.with_domain_metadata("app.config".to_string(), "v1".to_string())
.with_domain_metadata_removed("app.config".to_string())
.commit(&engine)
.unwrap_err();
assert!(err
.to_string()
.contains("already specified in this transaction"));

// remove then set same domain
let txn2 = snapshot.clone().transaction()?;
let err = txn2
.with_domain_metadata_removed("test.domain".to_string())
.with_domain_metadata("test.domain".to_string(), "v1".to_string())
.commit(&engine)
.unwrap_err();
assert!(err
.to_string()
.contains("already specified in this transaction"));

// remove same domain twice
let txn3 = snapshot.clone().transaction()?;
let err = txn3
.with_domain_metadata_removed("another.domain".to_string())
.with_domain_metadata_removed("another.domain".to_string())
.commit(&engine)
.unwrap_err();
assert!(err
.to_string()
.contains("already specified in this transaction"));

// remove system domain
let txn4 = snapshot.clone().transaction()?;
let err = txn4
.with_domain_metadata_removed("delta.system".to_string())
.commit(&engine)
.unwrap_err();
assert!(err
.to_string()
.contains("Cannot modify domains that start with 'delta.' as those are system controlled"));

Ok(())
}

#[tokio::test]
async fn test_domain_metadata_set_then_remove() -> Result<(), Box<dyn std::error::Error>> {
let _ = tracing_subscriber::fmt::try_init();

let schema = Arc::new(StructType::try_new(vec![StructField::nullable(
"number",
DataType::INTEGER,
)])?);

let table_name = "test_domain_metadata_unsupported";

let (store, engine, table_location) = engine_store_setup(table_name, None);
let table_url = create_table(
store.clone(),
table_location,
schema.clone(),
&[],
true,
vec![],
vec!["domainMetadata"],
)
.await?;

let domain = "app.config";
let configuration = r#"{"version": 1}"#;

// txn 1: set domain metadata
let snapshot = Snapshot::builder_for(table_url.clone()).build(&engine)?;
let txn = snapshot.transaction()?;
txn.with_domain_metadata(domain.to_string(), configuration.to_string())
.commit(&engine)?;

// txn 2: remove the same domain metadata
let snapshot = Snapshot::builder_for(table_url.clone()).build(&engine)?;
let txn = snapshot.transaction()?;
txn.with_domain_metadata_removed(domain.to_string())
.commit(&engine)?;

// verify removal commit preserves the previous configuration
let commit_data = store
.get(&Path::from(format!(
"/{table_name}/_delta_log/00000000000000000002.json"
)))
.await?
.bytes()
.await?;
let actions: Vec<serde_json::Value> = Deserializer::from_slice(&commit_data)
.into_iter()
.try_collect()?;

let domain_action = actions
.iter()
.find(|v| v.get("domainMetadata").is_some())
.unwrap();
assert_eq!(domain_action["domainMetadata"]["domain"], domain);
assert_eq!(
domain_action["domainMetadata"]["configuration"],
configuration
);
assert_eq!(domain_action["domainMetadata"]["removed"], true);

// verify reads see the metadata removal
let final_snapshot = Snapshot::builder_for(table_url.clone()).build(&engine)?;
let domain_config = final_snapshot.get_domain_metadata(domain, &engine)?;
assert_eq!(domain_config, None);

Ok(())
}
Loading