1use std::collections::HashMap;
77use std::sync::Arc;
78
79use bytes::Bytes;
80use chrono::Utc;
81use conflict_checker::ConflictChecker;
82use delta_kernel::table_properties::TableProperties;
83use futures::future::BoxFuture;
84use object_store::Error as ObjectStoreError;
85use object_store::path::Path;
86use serde_json::Value;
87use tracing::*;
88use uuid::Uuid;
89
90use delta_kernel::table_features::TableFeature;
91use serde::{Deserialize, Serialize};
92
93use self::conflict_checker::{TransactionInfo, WinningCommitSummary};
94use crate::errors::DeltaTableError;
95use crate::kernel::{Action, CommitInfo, EagerSnapshot, Metadata, Protocol, Transaction};
96use crate::logstore::ObjectStoreRef;
97use crate::logstore::{CommitOrBytes, LogStoreRef};
98use crate::operations::CustomExecuteHandler;
99use crate::protocol::DeltaOperation;
100use crate::protocol::{cleanup_expired_logs_for, create_checkpoint_for};
101use crate::table::config::TablePropertiesExt as _;
102use crate::table::state::DeltaTableState;
103use crate::{DeltaResult, crate_version};
104
105pub use self::conflict_checker::CommitConflictError;
106pub use self::protocol::INSTANCE as PROTOCOL;
107
108#[cfg(test)]
109pub(crate) mod application;
110mod conflict_checker;
111mod protocol;
112#[cfg(feature = "datafusion")]
113mod state;
114
115const DELTA_LOG_FOLDER: &str = "_delta_log";
116pub(crate) const DEFAULT_RETRIES: usize = 15;
117
118#[derive(Default, Debug, PartialEq, Clone, Serialize, Deserialize)]
119#[serde(rename_all = "camelCase")]
120pub struct CommitMetrics {
121 pub num_retries: u64,
123}
124
125#[derive(Default, Debug, PartialEq, Clone, Serialize, Deserialize)]
126#[serde(rename_all = "camelCase")]
127pub struct PostCommitMetrics {
128 pub new_checkpoint_created: bool,
130
131 pub num_log_files_cleaned_up: u64,
133}
134
135#[derive(Default, Debug, PartialEq, Clone, Serialize, Deserialize)]
136#[serde(rename_all = "camelCase")]
137pub struct Metrics {
138 pub num_retries: u64,
140
141 pub new_checkpoint_created: bool,
143
144 pub num_log_files_cleaned_up: u64,
146}
147
148#[derive(thiserror::Error, Debug)]
150pub enum TransactionError {
151 #[error("Tried committing existing table version: {0}")]
153 VersionAlreadyExists(i64),
154
155 #[error("Error serializing commit log to json: {json_err}")]
157 SerializeLogJson {
158 json_err: serde_json::error::Error,
160 },
161
162 #[error("Log storage error: {}", .source)]
164 ObjectStore {
165 #[from]
167 source: ObjectStoreError,
168 },
169
170 #[error("Failed to commit transaction: {0}")]
172 CommitConflict(#[from] CommitConflictError),
173
174 #[error("Failed to commit transaction: {0}")]
176 MaxCommitAttempts(i32),
177
178 #[error(
180 "The transaction includes Remove action with data change but Delta table is append-only"
181 )]
182 DeltaTableAppendOnly,
183
184 #[error("Unsupported table features required: {0:?}")]
186 UnsupportedTableFeatures(Vec<TableFeature>),
187
188 #[error("Table features must be specified, please specify: {0:?}")]
190 TableFeaturesRequired(TableFeature),
191
192 #[error("Transaction failed: {msg}")]
195 LogStoreError {
196 msg: String,
198 source: Box<dyn std::error::Error + Send + Sync + 'static>,
200 },
201}
202
203impl From<TransactionError> for DeltaTableError {
204 fn from(err: TransactionError) -> Self {
205 match err {
206 TransactionError::VersionAlreadyExists(version) => {
207 DeltaTableError::VersionAlreadyExists(version)
208 }
209 TransactionError::SerializeLogJson { json_err } => {
210 DeltaTableError::SerializeLogJson { json_err }
211 }
212 TransactionError::ObjectStore { source } => DeltaTableError::ObjectStore { source },
213 other => DeltaTableError::Transaction { source: other },
214 }
215 }
216}
217
218#[derive(thiserror::Error, Debug)]
220pub enum CommitBuilderError {}
221
222impl From<CommitBuilderError> for DeltaTableError {
223 fn from(err: CommitBuilderError) -> Self {
224 DeltaTableError::CommitValidation { source: err }
225 }
226}
227
228pub trait TableReference: Send + Sync {
230 fn config(&self) -> &TableProperties;
232
233 fn protocol(&self) -> &Protocol;
235
236 fn metadata(&self) -> &Metadata;
238
239 fn eager_snapshot(&self) -> &EagerSnapshot;
241}
242
243impl TableReference for EagerSnapshot {
244 fn protocol(&self) -> &Protocol {
245 EagerSnapshot::protocol(self)
246 }
247
248 fn metadata(&self) -> &Metadata {
249 EagerSnapshot::metadata(self)
250 }
251
252 fn config(&self) -> &TableProperties {
253 self.table_properties()
254 }
255
256 fn eager_snapshot(&self) -> &EagerSnapshot {
257 self
258 }
259}
260
261impl TableReference for DeltaTableState {
262 fn config(&self) -> &TableProperties {
263 self.snapshot.config()
264 }
265
266 fn protocol(&self) -> &Protocol {
267 self.snapshot.protocol()
268 }
269
270 fn metadata(&self) -> &Metadata {
271 self.snapshot.metadata()
272 }
273
274 fn eager_snapshot(&self) -> &EagerSnapshot {
275 &self.snapshot
276 }
277}
278
279#[derive(Debug)]
281pub struct CommitData {
282 pub actions: Vec<Action>,
284 pub operation: DeltaOperation,
286 pub app_metadata: HashMap<String, Value>,
288 pub app_transactions: Vec<Transaction>,
290}
291
292impl CommitData {
293 pub fn new(
295 mut actions: Vec<Action>,
296 operation: DeltaOperation,
297 mut app_metadata: HashMap<String, Value>,
298 app_transactions: Vec<Transaction>,
299 ) -> Self {
300 if !actions.iter().any(|a| matches!(a, Action::CommitInfo(..))) {
301 let mut commit_info = operation.get_commit_info();
302 commit_info.timestamp = Some(Utc::now().timestamp_millis());
303 app_metadata.insert(
304 "clientVersion".to_string(),
305 Value::String(format!("delta-rs.{}", crate_version())),
306 );
307 app_metadata.extend(commit_info.info);
308 commit_info.info = app_metadata.clone();
309 actions.insert(0, Action::CommitInfo(commit_info));
311 }
312
313 for txn in &app_transactions {
314 actions.push(Action::Txn(txn.clone()))
315 }
316
317 CommitData {
318 actions,
319 operation,
320 app_metadata,
321 app_transactions,
322 }
323 }
324
325 pub fn get_bytes(&self) -> Result<bytes::Bytes, TransactionError> {
327 let mut jsons = Vec::<String>::new();
328 for action in &self.actions {
329 let json = serde_json::to_string(action)
330 .map_err(|e| TransactionError::SerializeLogJson { json_err: e })?;
331 jsons.push(json);
332 }
333 Ok(bytes::Bytes::from(jsons.join("\n")))
334 }
335}
336
337#[derive(Clone, Debug, Copy)]
338pub struct PostCommitHookProperties {
340 create_checkpoint: bool,
341 cleanup_expired_logs: Option<bool>,
343}
344
345#[derive(Clone, Debug)]
346pub struct CommitProperties {
349 pub(crate) app_metadata: HashMap<String, Value>,
350 pub(crate) app_transaction: Vec<Transaction>,
351 max_retries: usize,
352 create_checkpoint: bool,
353 cleanup_expired_logs: Option<bool>,
354}
355
356impl Default for CommitProperties {
357 fn default() -> Self {
358 Self {
359 app_metadata: Default::default(),
360 app_transaction: Vec::new(),
361 max_retries: DEFAULT_RETRIES,
362 create_checkpoint: true,
363 cleanup_expired_logs: None,
364 }
365 }
366}
367
368impl CommitProperties {
369 pub fn with_metadata(
371 mut self,
372 metadata: impl IntoIterator<Item = (String, serde_json::Value)>,
373 ) -> Self {
374 self.app_metadata = HashMap::from_iter(metadata);
375 self
376 }
377
378 pub fn with_max_retries(mut self, max_retries: usize) -> Self {
380 self.max_retries = max_retries;
381 self
382 }
383
384 pub fn with_create_checkpoint(mut self, create_checkpoint: bool) -> Self {
386 self.create_checkpoint = create_checkpoint;
387 self
388 }
389
390 pub fn with_application_transaction(mut self, txn: Transaction) -> Self {
392 self.app_transaction.push(txn);
393 self
394 }
395
396 pub fn with_application_transactions(mut self, txn: Vec<Transaction>) -> Self {
398 self.app_transaction = txn;
399 self
400 }
401
402 pub fn with_cleanup_expired_logs(mut self, cleanup_expired_logs: Option<bool>) -> Self {
404 self.cleanup_expired_logs = cleanup_expired_logs;
405 self
406 }
407}
408
409impl From<CommitProperties> for CommitBuilder {
410 fn from(value: CommitProperties) -> Self {
411 CommitBuilder {
412 max_retries: value.max_retries,
413 app_metadata: value.app_metadata,
414 post_commit_hook: Some(PostCommitHookProperties {
415 create_checkpoint: value.create_checkpoint,
416 cleanup_expired_logs: value.cleanup_expired_logs,
417 }),
418 app_transaction: value.app_transaction,
419 ..Default::default()
420 }
421 }
422}
423
424pub struct CommitBuilder {
426 actions: Vec<Action>,
427 app_metadata: HashMap<String, Value>,
428 app_transaction: Vec<Transaction>,
429 max_retries: usize,
430 post_commit_hook: Option<PostCommitHookProperties>,
431 post_commit_hook_handler: Option<Arc<dyn CustomExecuteHandler>>,
432 operation_id: Uuid,
433}
434
435impl Default for CommitBuilder {
436 fn default() -> Self {
437 CommitBuilder {
438 actions: Vec::new(),
439 app_metadata: HashMap::new(),
440 app_transaction: Vec::new(),
441 max_retries: DEFAULT_RETRIES,
442 post_commit_hook: None,
443 post_commit_hook_handler: None,
444 operation_id: Uuid::new_v4(),
445 }
446 }
447}
448
449impl<'a> CommitBuilder {
450 pub fn with_actions(mut self, actions: Vec<Action>) -> Self {
452 self.actions = actions;
453 self
454 }
455
456 pub fn with_app_metadata(mut self, app_metadata: HashMap<String, Value>) -> Self {
458 self.app_metadata = app_metadata;
459 self
460 }
461
462 pub fn with_max_retries(mut self, max_retries: usize) -> Self {
464 self.max_retries = max_retries;
465 self
466 }
467
468 pub fn with_post_commit_hook(mut self, post_commit_hook: PostCommitHookProperties) -> Self {
470 self.post_commit_hook = Some(post_commit_hook);
471 self
472 }
473
474 pub fn with_operation_id(mut self, operation_id: Uuid) -> Self {
476 self.operation_id = operation_id;
477 self
478 }
479
480 pub fn with_post_commit_hook_handler(
482 mut self,
483 handler: Option<Arc<dyn CustomExecuteHandler>>,
484 ) -> Self {
485 self.post_commit_hook_handler = handler;
486 self
487 }
488
489 pub fn build(
491 self,
492 table_data: Option<&'a dyn TableReference>,
493 log_store: LogStoreRef,
494 operation: DeltaOperation,
495 ) -> PreCommit<'a> {
496 let data = CommitData::new(
497 self.actions,
498 operation,
499 self.app_metadata,
500 self.app_transaction,
501 );
502 PreCommit {
503 log_store,
504 table_data,
505 max_retries: self.max_retries,
506 data,
507 post_commit_hook: self.post_commit_hook,
508 post_commit_hook_handler: self.post_commit_hook_handler,
509 operation_id: self.operation_id,
510 }
511 }
512}
513
514pub struct PreCommit<'a> {
516 log_store: LogStoreRef,
517 table_data: Option<&'a dyn TableReference>,
518 data: CommitData,
519 max_retries: usize,
520 post_commit_hook: Option<PostCommitHookProperties>,
521 post_commit_hook_handler: Option<Arc<dyn CustomExecuteHandler>>,
522 operation_id: Uuid,
523}
524
525impl<'a> std::future::IntoFuture for PreCommit<'a> {
526 type Output = DeltaResult<FinalizedCommit>;
527 type IntoFuture = BoxFuture<'a, Self::Output>;
528
529 fn into_future(self) -> Self::IntoFuture {
530 Box::pin(async move { self.into_prepared_commit_future().await?.await?.await })
531 }
532}
533
534impl<'a> PreCommit<'a> {
535 pub fn into_prepared_commit_future(self) -> BoxFuture<'a, DeltaResult<PreparedCommit<'a>>> {
537 let this = self;
538
539 async fn write_tmp_commit(
542 log_entry: Bytes,
543 store: ObjectStoreRef,
544 ) -> DeltaResult<CommitOrBytes> {
545 let token = uuid::Uuid::new_v4().to_string();
546 let path = Path::from_iter([DELTA_LOG_FOLDER, &format!("_commit_{token}.json.tmp")]);
547 store.put(&path, log_entry.into()).await?;
548 Ok(CommitOrBytes::TmpCommit(path))
549 }
550
551 Box::pin(async move {
552 if let Some(table_reference) = this.table_data {
553 PROTOCOL.can_commit(table_reference, &this.data.actions, &this.data.operation)?;
554 }
555 let log_entry = this.data.get_bytes()?;
556
557 let commit_or_bytes = if ["LakeFSLogStore", "DefaultLogStore"]
560 .contains(&this.log_store.name().as_str())
561 {
562 CommitOrBytes::LogBytes(log_entry)
563 } else {
564 write_tmp_commit(
565 log_entry,
566 this.log_store.object_store(Some(this.operation_id)),
567 )
568 .await?
569 };
570
571 Ok(PreparedCommit {
572 commit_or_bytes,
573 log_store: this.log_store,
574 table_data: this.table_data,
575 max_retries: this.max_retries,
576 data: this.data,
577 post_commit: this.post_commit_hook,
578 post_commit_hook_handler: this.post_commit_hook_handler,
579 operation_id: this.operation_id,
580 })
581 })
582 }
583}
584
585pub struct PreparedCommit<'a> {
587 commit_or_bytes: CommitOrBytes,
588 log_store: LogStoreRef,
589 data: CommitData,
590 table_data: Option<&'a dyn TableReference>,
591 max_retries: usize,
592 post_commit: Option<PostCommitHookProperties>,
593 post_commit_hook_handler: Option<Arc<dyn CustomExecuteHandler>>,
594 operation_id: Uuid,
595}
596
597impl PreparedCommit<'_> {
598 pub fn commit_or_bytes(&self) -> &CommitOrBytes {
600 &self.commit_or_bytes
601 }
602}
603
604impl<'a> std::future::IntoFuture for PreparedCommit<'a> {
605 type Output = DeltaResult<PostCommit>;
606 type IntoFuture = BoxFuture<'a, Self::Output>;
607
608 fn into_future(self) -> Self::IntoFuture {
609 let this = self;
610
611 Box::pin(async move {
612 let commit_or_bytes = this.commit_or_bytes;
613
614 let mut attempt_number: usize = 1;
615
616 let read_snapshot: EagerSnapshot = if this.table_data.is_none() {
618 debug!("committing initial table version 0");
619 match this
620 .log_store
621 .write_commit_entry(0, commit_or_bytes.clone(), this.operation_id)
622 .await
623 {
624 Ok(_) => {
625 return Ok(PostCommit {
626 version: 0,
627 data: this.data,
628 create_checkpoint: false,
629 cleanup_expired_logs: None,
630 log_store: this.log_store,
631 table_data: None,
632 custom_execute_handler: this.post_commit_hook_handler,
633 metrics: CommitMetrics { num_retries: 0 },
634 });
635 }
636 Err(TransactionError::VersionAlreadyExists(0)) => {
637 debug!("version 0 already exists, loading table state for retry");
640 attempt_number = 2;
641 let latest_version = this.log_store.get_latest_version(0).await?;
642 EagerSnapshot::try_new(
643 this.log_store.as_ref(),
644 Default::default(),
645 Some(latest_version),
646 )
647 .await?
648 }
649 Err(e) => return Err(e.into()),
650 }
651 } else {
652 this.table_data.unwrap().eager_snapshot().clone()
653 };
654
655 let mut read_snapshot = read_snapshot;
656
657 let commit_span = info_span!(
658 "commit_with_retries",
659 base_version = read_snapshot.version(),
660 max_retries = this.max_retries,
661 attempt = field::Empty,
662 target_version = field::Empty,
663 conflicts_checked = 0
664 );
665
666 async move {
667 let total_retries = this.max_retries + 1;
668 while attempt_number <= total_retries {
669 Span::current().record("attempt", attempt_number);
670 let latest_version = this
671 .log_store
672 .get_latest_version(read_snapshot.version())
673 .await?;
674
675 if latest_version > read_snapshot.version() {
676 if this.max_retries == 0 {
679 warn!(
680 base_version = read_snapshot.version(),
681 latest_version = latest_version,
682 "table updated but max_retries is 0, failing immediately"
683 );
684 return Err(TransactionError::MaxCommitAttempts(
685 this.max_retries as i32,
686 )
687 .into());
688 }
689 warn!(
690 base_version = read_snapshot.version(),
691 latest_version = latest_version,
692 versions_behind = latest_version - read_snapshot.version(),
693 "table updated during transaction, checking for conflicts"
694 );
695 let mut steps = latest_version - read_snapshot.version();
696 let mut conflicts_checked = 0;
697
698 while steps != 0 {
701 conflicts_checked += 1;
702 let summary = WinningCommitSummary::try_new(
703 this.log_store.as_ref(),
704 latest_version - steps,
705 (latest_version - steps) + 1,
706 )
707 .await?;
708 let transaction_info = TransactionInfo::try_new(
709 read_snapshot.log_data(),
710 this.data.operation.read_predicate(),
711 &this.data.actions,
712 this.data.operation.read_whole_table(),
713 )?;
714 let conflict_checker = ConflictChecker::new(
715 transaction_info,
716 summary,
717 Some(&this.data.operation),
718 );
719
720 match conflict_checker.check_conflicts() {
721 Ok(_) => {}
722 Err(err) => {
723 error!(
724 conflicts_checked = conflicts_checked,
725 error = %err,
726 "conflict detected, aborting transaction"
727 );
728 return Err(TransactionError::CommitConflict(err).into());
729 }
730 }
731 steps -= 1;
732 }
733 Span::current().record("conflicts_checked", conflicts_checked);
734 debug!(
735 conflicts_checked = conflicts_checked,
736 "all conflicts resolved, updating snapshot"
737 );
738 read_snapshot
740 .update(&this.log_store, Some(latest_version as u64))
741 .await?;
742 }
743 let version: i64 = latest_version + 1;
744 Span::current().record("target_version", version);
745
746 match this
747 .log_store
748 .write_commit_entry(version, commit_or_bytes.clone(), this.operation_id)
749 .await
750 {
751 Ok(()) => {
752 info!(
753 version = version,
754 num_retries = attempt_number as u64 - 1,
755 "transaction committed successfully"
756 );
757 return Ok(PostCommit {
758 version,
759 data: this.data,
760 create_checkpoint: this
761 .post_commit
762 .map(|v| v.create_checkpoint)
763 .unwrap_or_default(),
764 cleanup_expired_logs: this
765 .post_commit
766 .map(|v| v.cleanup_expired_logs)
767 .unwrap_or_default(),
768 log_store: this.log_store,
769 table_data: Some(Box::new(read_snapshot)),
770 custom_execute_handler: this.post_commit_hook_handler,
771 metrics: CommitMetrics {
772 num_retries: attempt_number as u64 - 1,
773 },
774 });
775 }
776 Err(TransactionError::VersionAlreadyExists(version)) => {
777 warn!(
778 version = version,
779 attempt = attempt_number,
780 "version already exists, will retry"
781 );
782 attempt_number += 1;
785 }
786 Err(err) => {
787 error!(
788 version = version,
789 error = %err,
790 "commit failed, aborting"
791 );
792 this.log_store
793 .abort_commit_entry(version, commit_or_bytes, this.operation_id)
794 .await?;
795 return Err(err.into());
796 }
797 }
798 }
799
800 error!(
801 max_retries = this.max_retries,
802 "exceeded maximum commit attempts"
803 );
804 Err(TransactionError::MaxCommitAttempts(this.max_retries as i32).into())
805 }
806 .instrument(commit_span)
807 .await
808 })
809 }
810}
811
812pub struct PostCommit {
814 pub version: i64,
816 pub data: CommitData,
818 create_checkpoint: bool,
819 cleanup_expired_logs: Option<bool>,
820 log_store: LogStoreRef,
821 table_data: Option<Box<dyn TableReference>>,
822 custom_execute_handler: Option<Arc<dyn CustomExecuteHandler>>,
823 metrics: CommitMetrics,
824}
825
826impl PostCommit {
827 async fn run_post_commit_hook(&self) -> DeltaResult<(DeltaTableState, PostCommitMetrics)> {
829 if let Some(table) = &self.table_data {
830 let post_commit_operation_id = Uuid::new_v4();
831 let mut snapshot = table.eager_snapshot().clone();
832 if self.version != snapshot.version() {
833 snapshot
834 .update(&self.log_store, Some(self.version as u64))
835 .await?;
836 }
837
838 let mut state = DeltaTableState { snapshot };
839
840 let cleanup_logs = if let Some(cleanup_logs) = self.cleanup_expired_logs {
841 cleanup_logs
842 } else {
843 state.table_config().enable_expired_log_cleanup()
844 };
845
846 if let Some(custom_execute_handler) = &self.custom_execute_handler {
848 custom_execute_handler
849 .before_post_commit_hook(
850 &self.log_store,
851 cleanup_logs || self.create_checkpoint,
852 post_commit_operation_id,
853 )
854 .await?
855 }
856
857 let mut new_checkpoint_created = false;
858 if self.create_checkpoint {
859 new_checkpoint_created = self
861 .create_checkpoint(
862 &state,
863 &self.log_store,
864 self.version,
865 post_commit_operation_id,
866 )
867 .await?;
868 }
869
870 let mut num_log_files_cleaned_up: u64 = 0;
871 if cleanup_logs {
872 num_log_files_cleaned_up = cleanup_expired_logs_for(
874 self.version,
875 self.log_store.as_ref(),
876 Utc::now().timestamp_millis()
877 - state.table_config().log_retention_duration().as_millis() as i64,
878 Some(post_commit_operation_id),
879 )
880 .await? as u64;
881 if num_log_files_cleaned_up > 0 {
882 state = DeltaTableState::try_new(
883 &self.log_store,
884 state.load_config().clone(),
885 Some(self.version),
886 )
887 .await?;
888 }
889 }
890
891 if let Some(custom_execute_handler) = &self.custom_execute_handler {
893 custom_execute_handler
894 .after_post_commit_hook(
895 &self.log_store,
896 cleanup_logs || self.create_checkpoint,
897 post_commit_operation_id,
898 )
899 .await?
900 }
901 Ok((
902 state,
903 PostCommitMetrics {
904 new_checkpoint_created,
905 num_log_files_cleaned_up,
906 },
907 ))
908 } else {
909 let state =
910 DeltaTableState::try_new(&self.log_store, Default::default(), Some(self.version))
911 .await?;
912 Ok((
913 state,
914 PostCommitMetrics {
915 new_checkpoint_created: false,
916 num_log_files_cleaned_up: 0,
917 },
918 ))
919 }
920 }
921 async fn create_checkpoint(
922 &self,
923 table_state: &DeltaTableState,
924 log_store: &LogStoreRef,
925 version: i64,
926 operation_id: Uuid,
927 ) -> DeltaResult<bool> {
928 if !table_state.load_config().require_files {
929 warn!(
930 "Checkpoint creation in post_commit_hook has been skipped due to table being initialized without files."
931 );
932 return Ok(false);
933 }
934
935 let checkpoint_interval = table_state.config().checkpoint_interval().get() as i64;
936 if ((version + 1) % checkpoint_interval) == 0 {
937 create_checkpoint_for(version as u64, log_store.as_ref(), Some(operation_id)).await?;
938 Ok(true)
939 } else {
940 Ok(false)
941 }
942 }
943}
944
945pub struct FinalizedCommit {
947 pub snapshot: DeltaTableState,
949
950 pub version: i64,
952
953 pub metrics: Metrics,
955}
956
957impl std::fmt::Debug for FinalizedCommit {
958 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
959 f.debug_struct("FinalizedCommit")
960 .field("version", &self.version)
961 .field("metrics", &self.metrics)
962 .finish()
963 }
964}
965
966impl FinalizedCommit {
967 pub fn snapshot(&self) -> DeltaTableState {
969 self.snapshot.clone()
970 }
971 pub fn version(&self) -> i64 {
973 self.version
974 }
975}
976
977impl std::future::IntoFuture for PostCommit {
978 type Output = DeltaResult<FinalizedCommit>;
979 type IntoFuture = BoxFuture<'static, Self::Output>;
980
981 fn into_future(self) -> Self::IntoFuture {
982 let this = self;
983
984 Box::pin(async move {
985 match this.run_post_commit_hook().await {
986 Ok((snapshot, post_commit_metrics)) => Ok(FinalizedCommit {
987 snapshot,
988 version: this.version,
989 metrics: Metrics {
990 num_retries: this.metrics.num_retries,
991 new_checkpoint_created: post_commit_metrics.new_checkpoint_created,
992 num_log_files_cleaned_up: post_commit_metrics.num_log_files_cleaned_up,
993 },
994 }),
995 Err(err) => Err(err),
996 }
997 })
998 }
999}
1000
1001#[cfg(test)]
1002mod tests {
1003 use std::sync::Arc;
1004
1005 use super::*;
1006 use crate::logstore::{
1007 LogStore, StorageConfig, commit_uri_from_version, default_logstore::DefaultLogStore,
1008 };
1009 use object_store::{ObjectStore, PutPayload, memory::InMemory};
1010 use url::Url;
1011
1012 #[test]
1013 fn test_commit_uri_from_version() {
1014 let version = commit_uri_from_version(0);
1015 assert_eq!(version, Path::from("_delta_log/00000000000000000000.json"));
1016 let version = commit_uri_from_version(123);
1017 assert_eq!(version, Path::from("_delta_log/00000000000000000123.json"))
1018 }
1019
1020 #[tokio::test]
1021 async fn test_try_commit_transaction() {
1022 let store = Arc::new(InMemory::new());
1023 let url = Url::parse("mem://what/is/this").unwrap();
1024 let log_store = DefaultLogStore::new(
1025 store.clone(),
1026 store.clone(),
1027 crate::logstore::LogStoreConfig::new(&url, StorageConfig::default()),
1028 );
1029 let version_path = Path::from("_delta_log/00000000000000000000.json");
1030 store.put(&version_path, PutPayload::new()).await.unwrap();
1031
1032 let res = log_store
1033 .write_commit_entry(
1034 0,
1035 CommitOrBytes::LogBytes(PutPayload::new().into()),
1036 Uuid::new_v4(),
1037 )
1038 .await;
1039 assert!(res.is_err());
1041
1042 log_store
1044 .write_commit_entry(
1045 1,
1046 CommitOrBytes::LogBytes(PutPayload::new().into()),
1047 Uuid::new_v4(),
1048 )
1049 .await
1050 .unwrap();
1051 }
1052
1053 #[test]
1054 fn test_commit_with_retries_tracing_span() {
1055 let span = info_span!(
1056 "commit_with_retries",
1057 base_version = 5,
1058 max_retries = 10,
1059 attempt = field::Empty,
1060 target_version = field::Empty,
1061 conflicts_checked = 0
1062 );
1063
1064 let metadata = span.metadata().expect("span should have metadata");
1065 assert_eq!(metadata.name(), "commit_with_retries");
1066 assert_eq!(metadata.level(), &Level::INFO);
1067 assert!(metadata.is_span());
1068
1069 span.record("attempt", 1);
1070 span.record("target_version", 6);
1071 span.record("conflicts_checked", 2);
1072 }
1073
1074 #[test]
1075 fn test_commit_properties_with_retries() {
1076 let props = CommitProperties::default()
1077 .with_max_retries(5)
1078 .with_create_checkpoint(false);
1079
1080 assert_eq!(props.max_retries, 5);
1081 assert!(!props.create_checkpoint);
1082 }
1083
1084 #[test]
1085 fn test_commit_metrics() {
1086 let metrics = CommitMetrics { num_retries: 3 };
1087 assert_eq!(metrics.num_retries, 3);
1088 }
1089}