Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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 +366 to +367
Copy link
Member

Choose a reason for hiding this comment

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

I think we seem to be conflating the API communicating domain metadata additions/removals with the underlying DomainMetadata itself.

Can we simplify and make our lives easier below if we just take a set of domains to remove? Then we (1) don't have the 'fill-in-later' behavior here, and (2) immediately know if we have removals

I suppose we might need to still have something that knows our global set of domains since it's a logic error to add/remove in the same transaciton..

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

hmm this is interesting. if we have a separate state variable for removals, we can make it something like HashSet<String> instead. then we immediately know whether there are removals or not (point 2).

regarding point 1, the "fill-in" behavior, we can do log replay and store that value in a OnceCell or similar on the first removal. Subsequent removals can then immediately look up the configuration value to preserve. But, I think now we are adding class level state for something that could have been totally local in commit.

wdyt about adding a separate state variable as HashSet<String> for removals @zachschuermann?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

resolved offline; will merge pr as-is. (can cut a follow-ups as this is internal state only - no external API)

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 +397 to 409
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?

Copy link
Collaborator

Choose a reason for hiding this comment

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

which is an awkward interface for both Rust (chaining requires try operator)

I was willing to deal with an awkward interface

but particularly for engines across the FFI boundary.

But this is a really good point! GJ


if dm.is_removed() {
has_removals = true;
}
}

// 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()
};

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 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