Skip to content
Closed
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
81 changes: 69 additions & 12 deletions crates/core/src/kernel/transaction/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,9 @@ use chrono::Utc;
use conflict_checker::ConflictChecker;
use delta_kernel::table_properties::TableProperties;
use futures::future::BoxFuture;
use object_store::path::Path;
use object_store::Error as ObjectStoreError;
use object_store::ObjectStoreExt as _;
use object_store::path::Path;
use serde_json::Value;
use tracing::*;
use uuid::Uuid;
Expand All @@ -98,20 +98,25 @@ use crate::kernel::{
Action, CommitInfo, EagerSnapshot, IsolationLevel, Metadata, Protocol, Transaction, Version,
};
use crate::logstore::ObjectStoreRef;
use crate::logstore::{CommitOrBytes, LogStoreRef};
use crate::logstore::{CommitOrBytes, LogStore, LogStoreRef};
use crate::operations::CustomExecuteHandler;
use crate::protocol::{DeltaOperation, operation_parameter_value};
use crate::protocol::{cleanup_expired_logs_for, create_checkpoint_for};
use crate::protocol::{operation_parameter_value, DeltaOperation};
use crate::table::config::TablePropertiesExt as _;
use crate::table::state::DeltaTableState;
use crate::{DeltaResult, crate_version};
use crate::{crate_version, DeltaResult};

pub use self::conflict_checker::CommitConflictError;
pub use self::observer::{
set_commit_conflict_observer, CommitConflictEvent, CommitConflictObserver,
CommitConflictOutcome,
};
pub use self::protocol::INSTANCE as PROTOCOL;

#[cfg(test)]
pub(crate) mod application;
mod conflict_checker;
mod observer;
mod protocol;
#[cfg(feature = "datafusion")]
mod state;
Expand Down Expand Up @@ -435,11 +440,9 @@ fn assign_commit_info_metadata(
for (key, value) in existing_info {
app_metadata.entry(key).or_insert(value);
}
debug_assert!(
RESERVED_COMMIT_INFO_KEYS
.iter()
.all(|key| !app_metadata.contains_key(*key))
);
debug_assert!(RESERVED_COMMIT_INFO_KEYS
.iter()
.all(|key| !app_metadata.contains_key(*key)));

commit_info.info = app_metadata.clone();
}
Expand Down Expand Up @@ -764,6 +767,22 @@ impl PreparedCommit<'_> {
}
}

fn notify_commit_conflict(
log_store: &dyn LogStore,
operation: &DeltaOperation,
winner_operation: Option<&str>,
outcome: CommitConflictOutcome,
error: Option<&CommitConflictError>,
) {
observer::notify(&CommitConflictEvent {
table_url: log_store.root_url(),
operation: operation.name(),
winner_operation,
outcome,
error,
});
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Create-race conflict skips observer

Low Severity

A lost race on the initial version-0 put is a VersionAlreadyExists retry, but it never calls notify_commit_conflict. The handler still consumes an attempt and continues the retry loop, so table-creation conflicts are omitted from observer counts that the other version-already-exists path records.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 754c915. Configure here.

impl<'a> std::future::IntoFuture for PreparedCommit<'a> {
type Output = DeltaResult<PostCommit>;
type IntoFuture = BoxFuture<'a, Self::Output>;
Expand Down Expand Up @@ -844,6 +863,13 @@ impl<'a> std::future::IntoFuture for PreparedCommit<'a> {
latest_version = latest_version,
"table updated but max_retries is 0, failing immediately"
);
notify_commit_conflict(
this.log_store.as_ref(),
&this.data.operation,
None,
CommitConflictOutcome::Exhausted,
None,
);
return Err(TransactionError::MaxCommitAttempts(
this.max_retries as i32,
)
Expand All @@ -868,6 +894,10 @@ impl<'a> std::future::IntoFuture for PreparedCommit<'a> {
(latest_version - steps) + 1,
)
.await?;
let winner_operation = summary
.commit_info
.as_ref()
.and_then(|info| info.operation.clone());
let transaction_info = TransactionInfo::try_new(
read_snapshot.log_data(),
this.data.operation.read_predicate(),
Expand All @@ -881,8 +911,21 @@ impl<'a> std::future::IntoFuture for PreparedCommit<'a> {
);

match conflict_checker.check_conflicts() {
Ok(_) => {}
Ok(()) => notify_commit_conflict(
this.log_store.as_ref(),
&this.data.operation,
winner_operation.as_deref(),
CommitConflictOutcome::Rebase,
None,
),
Err(err) => {
notify_commit_conflict(
this.log_store.as_ref(),
&this.data.operation,
winner_operation.as_deref(),
CommitConflictOutcome::Abort,
Some(&err),
);
error!(
conflicts_checked = conflicts_checked,
error = %err,
Expand Down Expand Up @@ -937,6 +980,13 @@ impl<'a> std::future::IntoFuture for PreparedCommit<'a> {
});
}
Err(TransactionError::VersionAlreadyExists(version)) => {
notify_commit_conflict(
this.log_store.as_ref(),
&this.data.operation,
None,
CommitConflictOutcome::Retry,
None,
);
warn!(
version = version,
attempt = attempt_number,
Expand All @@ -960,6 +1010,13 @@ impl<'a> std::future::IntoFuture for PreparedCommit<'a> {
}
}

notify_commit_conflict(
this.log_store.as_ref(),
&this.data.operation,
None,
CommitConflictOutcome::Exhausted,
None,
);
error!(
max_retries = this.max_retries,
"exceeded maximum commit attempts"
Expand Down Expand Up @@ -1165,9 +1222,9 @@ mod tests {

use super::*;
use crate::kernel::IsolationLevel;
use crate::logstore::{LogStore, StorageConfig, default_logstore::DefaultLogStore};
use crate::logstore::{default_logstore::DefaultLogStore, LogStore, StorageConfig};
use crate::protocol::SaveMode;
use object_store::{PutPayload, memory::InMemory};
use object_store::{memory::InMemory, PutPayload};
use serde_json::json;
use url::Url;

Expand Down
83 changes: 83 additions & 0 deletions crates/core/src/kernel/transaction/observer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
use std::sync::{Arc, OnceLock};

use url::Url;

use super::CommitConflictError;

/// What the commit loop did after another writer committed first.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CommitConflictOutcome {
/// The target log version already existed. The loop tries the next version.
Retry,
/// A newer commit passed the conflict check. The loop moves its snapshot forward.
Rebase,
/// A newer commit failed the conflict check. The loop returns the error.
Abort,
/// The loop used every attempt, or retries were disabled.
Exhausted,
}

/// One commit-conflict event from the commit retry loop.
#[derive(Debug)]
pub struct CommitConflictEvent<'a> {
/// Root URL of the Delta table, including the table name as the last path segment.
pub table_url: &'a Url,
/// [`crate::protocol::DeltaOperation::name`] of the commit that lost the race.
pub operation: &'a str,
/// `commitInfo.operation` of the commit that won. Absent for a lost put, because
/// that attempt has not read the winning commit yet.
pub winner_operation: Option<&'a str>,
pub outcome: CommitConflictOutcome,
/// Set only when `outcome` is [`CommitConflictOutcome::Abort`].
pub error: Option<&'a CommitConflictError>,
}

/// Receives commit-conflict events. The Delta library does not record metrics itself.
pub trait CommitConflictObserver: Send + Sync {
fn on_commit_conflict(&self, event: &CommitConflictEvent<'_>);
}

static OBSERVER: OnceLock<Arc<dyn CommitConflictObserver>> = OnceLock::new();

/// Installs the process-wide observer. Returns `false` when one is already installed.
pub fn set_commit_conflict_observer(observer: Arc<dyn CommitConflictObserver>) -> bool {
OBSERVER.set(observer).is_ok()
}

pub(crate) fn notify(event: &CommitConflictEvent<'_>) {
if let Some(observer) = OBSERVER.get() {
observer.on_commit_conflict(event);
}
}

#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;

struct Counter(Mutex<u32>);

impl CommitConflictObserver for Counter {
fn on_commit_conflict(&self, event: &CommitConflictEvent<'_>) {
assert_eq!(event.operation, "WRITE");
assert_eq!(event.outcome, CommitConflictOutcome::Retry);
*self.0.lock().unwrap() += 1;
}
}

#[test]
fn installed_observer_counts_one_notification() {
let counter = Arc::new(Counter(Mutex::new(0)));
assert!(set_commit_conflict_observer(counter.clone()));
let table_url = Url::parse("s3://bucket/acme/traces_v2").unwrap();
notify(&CommitConflictEvent {
table_url: &table_url,
operation: "WRITE",
winner_operation: None,
outcome: CommitConflictOutcome::Retry,
error: None,
});
assert_eq!(*counter.0.lock().unwrap(), 1);
assert!(!set_commit_conflict_observer(counter));
}
}
Loading