1use crate::engine_data::{FilteredEngineData, GetData, RowVisitor, TypedGetData as _};
34use crate::log_replay::deduplicator::Deduplicator as _;
35use crate::log_replay::{
36 ActionsBatch, FileActionDeduplicator, FileActionKey, HasSelectionVector, LogReplayProcessor,
37};
38use crate::scan::data_skipping::DataSkippingFilter;
39use crate::schema::{column_name, ColumnName, ColumnNamesAndTypes, DataType};
40use crate::utils::require;
41use crate::{DeltaResult, Error};
42
43use std::collections::HashSet;
44use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
45use std::sync::{Arc, LazyLock};
46
47pub(crate) struct ActionReconciliationProcessor {
50 seen_file_keys: HashSet<FileActionKey>,
53 seen_protocol: bool,
55 seen_metadata: bool,
57 seen_txns: HashSet<String>,
59 seen_domains: HashSet<String>,
62 minimum_file_retention_timestamp: i64,
64 txn_expiration_timestamp: Option<i64>,
66}
67
68pub(crate) struct ActionReconciliationBatch {
79 pub(crate) filtered_data: FilteredEngineData,
81 pub(crate) actions_count: i64,
83 pub(crate) add_actions_count: i64,
85}
86
87impl HasSelectionVector for ActionReconciliationBatch {
88 fn has_selected_rows(&self) -> bool {
89 self.filtered_data.has_selected_rows()
90 }
91}
92
93#[derive(Debug, Default)]
95pub struct ActionReconciliationIteratorState {
96 actions_count: AtomicI64,
97 add_actions_count: AtomicI64,
98 is_exhausted: AtomicBool,
99}
100
101impl ActionReconciliationIteratorState {
102 pub fn actions_count(&self) -> i64 {
104 self.actions_count.load(Ordering::Acquire)
105 }
106
107 pub fn add_actions_count(&self) -> i64 {
109 self.add_actions_count.load(Ordering::Acquire)
110 }
111
112 pub fn is_exhausted(&self) -> bool {
114 self.is_exhausted.load(Ordering::Acquire)
115 }
116}
117
118pub struct ActionReconciliationIterator {
123 inner: Box<dyn Iterator<Item = DeltaResult<ActionReconciliationBatch>> + Send>,
124 state: Arc<ActionReconciliationIteratorState>,
125}
126
127impl ActionReconciliationIterator {
128 pub(crate) fn new(
130 inner: Box<dyn Iterator<Item = DeltaResult<ActionReconciliationBatch>> + Send>,
131 ) -> Self {
132 Self {
133 inner,
134 state: Arc::new(ActionReconciliationIteratorState::default()),
135 }
136 }
137
138 pub fn state(&self) -> Arc<ActionReconciliationIteratorState> {
140 Arc::clone(&self.state)
141 }
142
143 fn transform_batch(
145 &mut self,
146 batch: Option<DeltaResult<ActionReconciliationBatch>>,
147 ) -> Option<DeltaResult<FilteredEngineData>> {
148 let Some(batch) = batch else {
149 self.state.is_exhausted.store(true, Ordering::Release);
150 return None;
151 };
152 Some(batch.map(|batch| {
153 self.state
154 .actions_count
155 .fetch_add(batch.actions_count, Ordering::Release);
156 self.state
157 .add_actions_count
158 .fetch_add(batch.add_actions_count, Ordering::Release);
159 batch.filtered_data
160 }))
161 }
162}
163
164impl std::fmt::Debug for ActionReconciliationIterator {
165 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
166 f.debug_struct("ActionReconciliationIterator")
167 .field("state", &self.state)
168 .finish()
169 }
170}
171
172impl Iterator for ActionReconciliationIterator {
173 type Item = DeltaResult<FilteredEngineData>;
174
175 fn next(&mut self) -> Option<Self::Item> {
176 let batch = self.inner.next();
177 self.transform_batch(batch)
178 }
179}
180
181impl LogReplayProcessor for ActionReconciliationProcessor {
182 type Output = ActionReconciliationBatch;
183
184 fn process_actions_batch(&mut self, actions_batch: ActionsBatch) -> DeltaResult<Self::Output> {
193 let ActionsBatch {
194 actions,
195 is_log_batch,
196 } = actions_batch;
197 let selection_vector = vec![true; actions.len()];
198
199 let mut visitor = ActionReconciliationVisitor::new(
201 &mut self.seen_file_keys,
202 is_log_batch,
203 selection_vector,
204 self.minimum_file_retention_timestamp,
205 self.seen_protocol,
206 self.seen_metadata,
207 &mut self.seen_txns,
208 &mut self.seen_domains,
209 self.txn_expiration_timestamp,
210 );
211 visitor.visit_rows_of(actions.as_ref())?;
212
213 self.seen_protocol = visitor.seen_protocol;
215 self.seen_metadata = visitor.seen_metadata;
216
217 let filtered_data = FilteredEngineData::try_new(actions, visitor.selection_vector)?;
218
219 Ok(ActionReconciliationBatch {
220 filtered_data,
221 actions_count: visitor.actions_count,
222 add_actions_count: visitor.add_actions_count,
223 })
224 }
225
226 fn data_skipping_filter(&self) -> Option<&DataSkippingFilter> {
228 None
229 }
230}
231
232impl ActionReconciliationProcessor {
233 pub(crate) fn new(
234 minimum_file_retention_timestamp: i64,
235 txn_expiration_timestamp: Option<i64>,
236 ) -> Self {
237 Self {
238 seen_file_keys: Default::default(),
239 seen_protocol: false,
240 seen_metadata: false,
241 seen_txns: Default::default(),
242 seen_domains: Default::default(),
243 minimum_file_retention_timestamp,
244 txn_expiration_timestamp,
245 }
246 }
247}
248
249pub(crate) struct ActionReconciliationVisitor<'seen> {
291 deduplicator: FileActionDeduplicator<'seen>,
295 selection_vector: Vec<bool>,
297 actions_count: i64,
301 add_actions_count: i64,
303 minimum_file_retention_timestamp: i64,
305 seen_protocol: bool,
307 seen_metadata: bool,
309 seen_txns: &'seen mut HashSet<String>,
312 seen_domains: &'seen mut HashSet<String>,
315 txn_expiration_timestamp: Option<i64>,
317}
318
319#[derive(Debug, Copy, Clone)]
327struct GetterColumn {
328 index: usize,
329 name: &'static str,
330}
331
332impl GetterColumn {
333 const fn new(index: usize, name: &'static str) -> Self {
334 GetterColumn { index, name }
335 }
336}
337
338#[allow(unused)]
339impl ActionReconciliationVisitor<'_> {
340 const ADD_PATH: GetterColumn = GetterColumn::new(0, "add.path");
343 const ADD_DV_STORAGE_TYPE: GetterColumn =
344 GetterColumn::new(1, "add.deletionVector.storageType");
345 const ADD_DV_PATH_OR_INLINE_DV: GetterColumn =
346 GetterColumn::new(2, "add.deletionVector.pathOrInlineDv");
347 const ADD_DV_OFFSET: GetterColumn = GetterColumn::new(3, "add.deletionVector.offset");
348 const REMOVE_PATH: GetterColumn = GetterColumn::new(4, "remove.path");
349 const REMOVE_DELETION_TIMESTAMP: GetterColumn =
350 GetterColumn::new(5, "remove.deletionTimestamp");
351 const REMOVE_DV_STORAGE_TYPE: GetterColumn =
352 GetterColumn::new(6, "remove.deletionVector.storageType");
353 const REMOVE_DV_PATH_OR_INLINE_DV: GetterColumn =
354 GetterColumn::new(7, "remove.deletionVector.pathOrInlineDv");
355 const REMOVE_DV_OFFSET: GetterColumn = GetterColumn::new(8, "remove.deletionVector.offset");
356 const METADATA_ID: GetterColumn = GetterColumn::new(9, "metaData.id");
357 const PROTOCOL_MIN_READER_VERSION: GetterColumn =
358 GetterColumn::new(10, "protocol.minReaderVersion");
359 const TXN_APP_ID: GetterColumn = GetterColumn::new(11, "txn.appId");
360 const TXN_LAST_UPDATED: GetterColumn = GetterColumn::new(12, "txn.lastUpdated");
361 const DOMAIN_METADATA_DOMAIN: GetterColumn = GetterColumn::new(13, "domainMetadata.domain");
362 const DOMAIN_METADATA_REMOVED: GetterColumn = GetterColumn::new(14, "domainMetadata.removed");
363
364 #[allow(clippy::too_many_arguments)]
365 pub(crate) fn new<'seen>(
366 seen_file_keys: &'seen mut HashSet<FileActionKey>,
367 is_log_batch: bool,
368 selection_vector: Vec<bool>,
369 minimum_file_retention_timestamp: i64,
370 seen_protocol: bool,
371 seen_metadata: bool,
372 seen_txns: &'seen mut HashSet<String>,
373 seen_domains: &'seen mut HashSet<String>,
374 txn_expiration_timestamp: Option<i64>,
375 ) -> ActionReconciliationVisitor<'seen> {
376 ActionReconciliationVisitor {
377 deduplicator: FileActionDeduplicator::new(
378 seen_file_keys,
379 is_log_batch,
380 Self::ADD_PATH.index,
381 Self::REMOVE_PATH.index,
382 Self::ADD_DV_STORAGE_TYPE.index,
383 Self::REMOVE_DV_STORAGE_TYPE.index,
384 ),
385 selection_vector,
386 actions_count: 0,
387 add_actions_count: 0,
388 minimum_file_retention_timestamp,
389 seen_protocol,
390 seen_metadata,
391 seen_txns,
392 seen_domains,
393 txn_expiration_timestamp,
394 }
395 }
396
397 fn is_expired_tombstone<'a>(&self, i: usize, getter: &'a dyn GetData<'a>) -> DeltaResult<bool> {
408 let deletion_timestamp = getter.get_opt(i, Self::REMOVE_DELETION_TIMESTAMP.name)?;
413 let deletion_timestamp = deletion_timestamp.unwrap_or(0i64);
414
415 Ok(deletion_timestamp <= self.minimum_file_retention_timestamp)
416 }
417
418 fn check_file_action<'a>(
428 &mut self,
429 i: usize,
430 getters: &[&'a dyn GetData<'a>],
431 ) -> DeltaResult<Option<bool>> {
432 let Some((file_key, is_add)) = self.deduplicator.extract_file_action(i, getters, false)?
434 else {
435 return Ok(None); };
437
438 let is_valid = if self.deduplicator.check_and_record_seen(file_key) {
440 false } else if is_add {
442 self.add_actions_count += 1;
443 true
444 } else {
445 !self.is_expired_tombstone(i, getters[Self::REMOVE_DELETION_TIMESTAMP.index])?
447 };
448 Ok(Some(is_valid))
449 }
450
451 fn check_protocol_action<'a>(
458 &mut self,
459 i: usize,
460 getter: &'a dyn GetData<'a>,
461 ) -> DeltaResult<Option<bool>> {
462 let result = getter
465 .get_int(i, Self::PROTOCOL_MIN_READER_VERSION.name)?
466 .is_some()
467 .then(|| !std::mem::replace(&mut self.seen_protocol, true));
468 Ok(result)
469 }
470
471 fn check_metadata_action<'a>(
478 &mut self,
479 i: usize,
480 getter: &'a dyn GetData<'a>,
481 ) -> DeltaResult<Option<bool>> {
482 let result = getter
485 .get_str(i, Self::METADATA_ID.name)?
486 .is_some()
487 .then(|| !std::mem::replace(&mut self.seen_metadata, true));
488 Ok(result)
489 }
490
491 fn check_txn_action<'a>(
498 &mut self,
499 i: usize,
500 getters: &[&'a dyn GetData<'a>],
501 ) -> DeltaResult<Option<bool>> {
502 let Some(app_id) = getters[Self::TXN_APP_ID.index].get_str(i, Self::TXN_APP_ID.name)?
503 else {
504 return Ok(None); };
506
507 if let Some(retention_ts) = self.txn_expiration_timestamp {
509 if let Some(last_updated) =
510 getters[Self::TXN_LAST_UPDATED.index].get_opt(i, Self::TXN_LAST_UPDATED.name)?
511 {
512 let last_updated: i64 = last_updated;
513 if last_updated <= retention_ts {
514 return Ok(Some(false));
516 }
517 }
518 }
520
521 Ok(Some(self.seen_txns.insert(app_id.to_string())))
524 }
525
526 fn check_domain_metadata_action<'a>(
534 &mut self,
535 i: usize,
536 getters: &[&'a dyn GetData<'a>],
537 ) -> DeltaResult<Option<bool>> {
538 let Some(domain) = getters[Self::DOMAIN_METADATA_DOMAIN.index]
539 .get_str(i, Self::DOMAIN_METADATA_DOMAIN.name)?
540 else {
541 return Ok(None); };
543
544 let removed: bool = getters[Self::DOMAIN_METADATA_REMOVED.index]
546 .get_opt(i, Self::DOMAIN_METADATA_REMOVED.name)?
547 .unwrap_or(false);
548 if removed {
549 return Ok(Some(false));
550 }
551
552 Ok(Some(self.seen_domains.insert(domain.to_string())))
555 }
556
557 pub(crate) fn is_valid_action<'a>(
574 &mut self,
575 i: usize,
576 getters: &[&'a dyn GetData<'a>],
577 ) -> DeltaResult<bool> {
578 let is_valid = if let Some(result) = self.check_file_action(i, getters)? {
579 result
580 } else if let Some(result) = self.check_txn_action(i, getters)? {
581 result
582 } else if let Some(result) = self.check_domain_metadata_action(i, getters)? {
583 result
584 } else if let Some(result) =
585 self.check_protocol_action(i, getters[Self::PROTOCOL_MIN_READER_VERSION.index])?
586 {
587 result
588 } else {
589 self.check_metadata_action(i, getters[Self::METADATA_ID.index])?
590 .unwrap_or_default()
591 };
592
593 if is_valid {
594 self.actions_count += 1;
595 }
596
597 Ok(is_valid)
598 }
599}
600
601impl RowVisitor for ActionReconciliationVisitor<'_> {
602 fn selected_column_names_and_types(&self) -> (&'static [ColumnName], &'static [DataType]) {
603 static NAMES_AND_TYPES: LazyLock<ColumnNamesAndTypes> = LazyLock::new(|| {
612 const STRING: DataType = DataType::STRING;
613 const INTEGER: DataType = DataType::INTEGER;
614 const LONG: DataType = DataType::LONG;
615 const BOOLEAN: DataType = DataType::BOOLEAN;
616 let types_and_names = vec![
617 (STRING, column_name!("add.path")),
619 (STRING, column_name!("add.deletionVector.storageType")),
620 (STRING, column_name!("add.deletionVector.pathOrInlineDv")),
621 (INTEGER, column_name!("add.deletionVector.offset")),
622 (STRING, column_name!("remove.path")),
623 (LONG, column_name!("remove.deletionTimestamp")),
624 (STRING, column_name!("remove.deletionVector.storageType")),
625 (STRING, column_name!("remove.deletionVector.pathOrInlineDv")),
626 (INTEGER, column_name!("remove.deletionVector.offset")),
627 (STRING, column_name!("metaData.id")),
629 (INTEGER, column_name!("protocol.minReaderVersion")),
630 (STRING, column_name!("txn.appId")),
631 (LONG, column_name!("txn.lastUpdated")),
632 (STRING, column_name!("domainMetadata.domain")),
633 (BOOLEAN, column_name!("domainMetadata.removed")),
634 ];
635 let (types, names) = types_and_names.into_iter().unzip();
636 (names, types).into()
637 });
638 NAMES_AND_TYPES.as_ref()
639 }
640
641 fn visit<'a>(&mut self, row_count: usize, getters: &[&'a dyn GetData<'a>]) -> DeltaResult<()> {
642 require!(
643 getters.len() == 15,
644 Error::InternalError(format!(
645 "Wrong number of visitor getters: {}",
646 getters.len()
647 ))
648 );
649
650 for i in 0..row_count {
651 self.selection_vector[i] = self.is_valid_action(i, getters)?;
652 }
653 Ok(())
654 }
655}
656
657#[cfg(test)]
658mod tests {
659 use std::collections::HashSet;
660
661 use super::*;
662 use crate::arrow::array::StringArray;
663 use crate::utils::test_utils::{action_batch, parse_json_batch};
664 use crate::Error;
665
666 use itertools::Itertools;
667
668 fn create_batch(json_strings: Vec<&str>) -> DeltaResult<ActionsBatch> {
670 let actions = parse_json_batch(StringArray::from(json_strings));
671 Ok(ActionsBatch::new(actions, true))
672 }
673
674 fn run_action_reconciliation_test(
677 input_batches: Vec<ActionsBatch>,
678 ) -> DeltaResult<(Vec<FilteredEngineData>, i64, i64)> {
679 let processed_batches: Vec<_> = ActionReconciliationProcessor::new(0, None)
680 .process_actions_iter(input_batches.into_iter().map(Ok))
681 .try_collect()?;
682 let total_count: i64 = processed_batches.iter().map(|b| b.actions_count).sum();
683 let add_count: i64 = processed_batches.iter().map(|b| b.add_actions_count).sum();
684 let filtered_data = processed_batches
685 .into_iter()
686 .map(|b| b.filtered_data)
687 .collect();
688
689 Ok((filtered_data, total_count, add_count))
690 }
691 #[test]
692 fn test_action_reconciliation_visitor() -> DeltaResult<()> {
693 let data = action_batch();
694 let mut seen_file_keys = HashSet::new();
695 let mut seen_txns = HashSet::new();
696 let mut seen_domains = HashSet::new();
697 let mut visitor = ActionReconciliationVisitor::new(
698 &mut seen_file_keys,
699 true,
700 vec![true; 9],
701 0, false,
703 false,
704 &mut seen_txns,
705 &mut seen_domains,
706 None,
707 );
708
709 visitor.visit_rows_of(data.as_ref())?;
710
711 let expected = vec![
712 true, true, false, true, true, false, false, true, false, ];
722
723 assert_eq!(visitor.actions_count, 5);
724 assert_eq!(visitor.add_actions_count, 1);
725 assert!(visitor.seen_protocol);
726 assert!(visitor.seen_metadata);
727 assert_eq!(visitor.seen_txns.len(), 1);
728
729 assert_eq!(visitor.selection_vector, expected);
730 Ok(())
731 }
732
733 #[test]
740 fn test_action_reconciliation_visitor_boundary_cases_for_tombstone_expiration(
741 ) -> DeltaResult<()> {
742 let json_strings: StringArray = vec![
743 r#"{"remove":{"path":"exactly_at_threshold","deletionTimestamp":100,"dataChange":true,"partitionValues":{}}}"#,
744 r#"{"remove":{"path":"one_below_threshold","deletionTimestamp":99,"dataChange":true,"partitionValues":{}}}"#,
745 r#"{"remove":{"path":"one_above_threshold","deletionTimestamp":101,"dataChange":true,"partitionValues":{}}}"#,
746 r#"{"remove":{"path":"missing_timestamp","dataChange":true,"partitionValues":{}}}"#,
748 ]
749 .into();
750 let batch = parse_json_batch(json_strings);
751
752 let mut seen_file_keys = HashSet::new();
753 let mut seen_txns = HashSet::new();
754 let mut seen_domains = HashSet::new();
755 let mut visitor = ActionReconciliationVisitor::new(
756 &mut seen_file_keys,
757 true,
758 vec![true; 4],
759 100, false,
761 false,
762 &mut seen_txns,
763 &mut seen_domains,
764 None,
765 );
766
767 visitor.visit_rows_of(batch.as_ref())?;
768
769 let expected = vec![false, false, true, false];
771 assert_eq!(visitor.selection_vector, expected);
772 assert_eq!(visitor.actions_count, 1);
773 assert_eq!(visitor.add_actions_count, 0);
774 Ok(())
775 }
776
777 #[test]
778 fn test_action_reconciliation_visitor_file_actions_in_batch() -> DeltaResult<()> {
779 let json_strings: StringArray = vec![
780 r#"{"add":{"path":"file1","partitionValues":{"c1":"6","c2":"a"},"size":452,"modificationTime":1670892998137,"dataChange":true}}"#,
781 ]
782 .into();
783 let batch = parse_json_batch(json_strings);
784
785 let mut seen_file_keys = HashSet::new();
786 let mut seen_txns = HashSet::new();
787 let mut seen_domains = HashSet::new();
788 let mut visitor = ActionReconciliationVisitor::new(
789 &mut seen_file_keys,
790 false, vec![true; 1],
792 0,
793 false,
794 false,
795 &mut seen_txns,
796 &mut seen_domains,
797 None,
798 );
799
800 visitor.visit_rows_of(batch.as_ref())?;
801
802 let expected = vec![true];
803 assert_eq!(visitor.selection_vector, expected);
804 assert_eq!(visitor.actions_count, 1);
805 assert_eq!(visitor.add_actions_count, 1);
806 assert!(seen_file_keys.is_empty());
810 Ok(())
811 }
812
813 #[test]
814 fn test_action_reconciliation_visitor_file_actions_with_deletion_vectors() -> DeltaResult<()> {
815 let json_strings: StringArray = vec![
816 r#"{"add":{"path":"file1","partitionValues":{},"size":635,"modificationTime":100,"dataChange":true,"deletionVector":{"storageType":"ONE","pathOrInlineDv":"dv1","offset":1,"sizeInBytes":36,"cardinality":2}}}"#,
818 r#"{"remove":{"path":"file1","deletionTimestamp":100,"dataChange":true,"deletionVector":{"storageType":"TWO","pathOrInlineDv":"dv2","offset":1,"sizeInBytes":36,"cardinality":2}}}"#,
820 r#"{"remove":{"path":"file1","deletionTimestamp":100,"dataChange":true,"deletionVector":{"storageType":"THREE","pathOrInlineDv":"dv3","offset":1,"sizeInBytes":36,"cardinality":2}}}"#,
822 ]
823 .into();
824 let batch = parse_json_batch(json_strings);
825
826 let mut seen_file_keys = HashSet::new();
827 let mut seen_txns = HashSet::new();
828 let mut seen_domains = HashSet::new();
829 let mut visitor = ActionReconciliationVisitor::new(
830 &mut seen_file_keys,
831 true,
832 vec![true; 3],
833 0,
834 false,
835 false,
836 &mut seen_txns,
837 &mut seen_domains,
838 None,
839 );
840
841 visitor.visit_rows_of(batch.as_ref())?;
842
843 let expected = vec![true, true, true];
844 assert_eq!(visitor.selection_vector, expected);
845 assert_eq!(visitor.actions_count, 3);
846 assert_eq!(visitor.add_actions_count, 1);
847
848 Ok(())
849 }
850
851 #[test]
852 fn test_action_reconciliation_visitor_already_seen_non_file_actions() -> DeltaResult<()> {
853 let json_strings: StringArray = vec![
854 r#"{"txn":{"appId":"app1","version":1,"lastUpdated":123456789}}"#,
855 r#"{"protocol":{"minReaderVersion":3,"minWriterVersion":7,"readerFeatures":["deletionVectors"],"writerFeatures":["deletionVectors"]}}"#,
856 r#"{"metaData":{"id":"testId","format":{"provider":"parquet","options":{}},"schemaString":"{\"type\":\"struct\",\"fields\":[{\"name\":\"value\",\"type\":\"integer\",\"nullable\":true,\"metadata\":{}}]}","partitionColumns":[],"configuration":{},"createdTime":1677811175819}}"#,
857 ].into();
858 let batch = parse_json_batch(json_strings);
859
860 let mut seen_file_keys = HashSet::new();
862 let mut seen_txns = HashSet::new();
863 let mut seen_domains = HashSet::new();
864 seen_txns.insert("app1".to_string());
865
866 let mut visitor = ActionReconciliationVisitor::new(
867 &mut seen_file_keys,
868 true,
869 vec![true; 3],
870 0,
871 true, true, &mut seen_txns, &mut seen_domains,
875 None,
876 );
877
878 visitor.visit_rows_of(batch.as_ref())?;
879
880 let expected = vec![false, false, false];
882 assert_eq!(visitor.selection_vector, expected);
883 assert_eq!(visitor.actions_count, 0);
884
885 Ok(())
886 }
887
888 #[test]
889 fn test_action_reconciliation_visitor_duplicate_non_file_actions() -> DeltaResult<()> {
890 let json_strings: StringArray = vec![
891 r#"{"txn":{"appId":"app1","version":1,"lastUpdated":123456789}}"#,
892 r#"{"txn":{"appId":"app1","version":1,"lastUpdated":123456789}}"#, r#"{"txn":{"appId":"app2","version":1,"lastUpdated":123456789}}"#, r#"{"protocol":{"minReaderVersion":3,"minWriterVersion":7}}"#,
895 r#"{"protocol":{"minReaderVersion":3,"minWriterVersion":7}}"#, r#"{"metaData":{"id":"testId","format":{"provider":"parquet","options":{}},"schemaString":"{\"type\":\"struct\",\"fields\":[{\"name\":\"value\",\"type\":\"integer\",\"nullable\":true,\"metadata\":{}}]}","partitionColumns":[],"configuration":{},"createdTime":1677811175819}}"#,
897 r#"{"metaData":{"id":"testId","format":{"provider":"parquet","options":{}},"schemaString":"{\"type\":\"struct\",\"fields\":[{\"name\":\"value\",\"type\":\"integer\",\"nullable\":true,\"metadata\":{}}]}","partitionColumns":[],"configuration":{},"createdTime":1677811175819}}"#,
899 ]
900 .into();
901 let batch = parse_json_batch(json_strings);
902
903 let mut seen_file_keys = HashSet::new();
904 let mut seen_txns = HashSet::new();
905 let mut seen_domains = HashSet::new();
906 let mut visitor = ActionReconciliationVisitor::new(
907 &mut seen_file_keys,
908 true, vec![true; 7],
910 0, false,
912 false,
913 &mut seen_txns,
914 &mut seen_domains,
915 None,
916 );
917
918 visitor.visit_rows_of(batch.as_ref())?;
919
920 let expected = vec![true, false, true, true, false, true, false];
922 assert_eq!(visitor.selection_vector, expected);
923 assert_eq!(visitor.seen_txns.len(), 2); assert_eq!(visitor.actions_count, 4); Ok(())
927 }
928
929 #[test]
932 fn test_action_reconciliation_actions_iter_non_file_actions() -> DeltaResult<()> {
933 let batch1 = vec![
935 r#"{"protocol":{"minReaderVersion":1,"minWriterVersion":2}}"#,
936 r#"{"metaData":{"id":"test1","format":{"provider":"parquet","options":{}},"schemaString":"{\"type\":\"struct\",\"fields\":[{\"name\":\"c1\",\"type\":\"integer\",\"nullable\":true,\"metadata\":{}},{\"name\":\"c2\",\"type\":\"string\",\"nullable\":true,\"metadata\":{}},{\"name\":\"c3\",\"type\":\"integer\",\"nullable\":true,\"metadata\":{}}]}","partitionColumns":["c1","c2"],"configuration":{},"createdTime":1670892997849}}"#,
937 r#"{"txn":{"appId":"app1","version":1,"lastUpdated":123456789}}"#,
938 ];
939
940 let batch2 = vec![
942 r#"{"protocol":{"minReaderVersion":2,"minWriterVersion":3}}"#,
944 r#"{"metaData":{"id":"test2","format":{"provider":"parquet","options":{}},"schemaString":"{\"type\":\"struct\",\"fields\":[{\"name\":\"c1\",\"type\":\"integer\",\"nullable\":true,\"metadata\":{}},{\"name\":\"c2\",\"type\":\"string\",\"nullable\":true,\"metadata\":{}},{\"name\":\"c3\",\"type\":\"integer\",\"nullable\":true,\"metadata\":{}}]}","partitionColumns":["c1","c2"],"configuration":{},"createdTime":1670892997849}}"#,
945 r#"{"txn":{"appId":"app1","version":1,"lastUpdated":123456789}}"#,
946 r#"{"txn":{"appId":"app2","version":1,"lastUpdated":123456789}}"#,
948 ];
949
950 let batch3 = vec![r#"{"protocol":{"minReaderVersion":2,"minWriterVersion":3}}"#];
952
953 let input_batches = vec![
954 create_batch(batch1)?,
955 create_batch(batch2)?,
956 create_batch(batch3)?,
957 ];
958 let (results, actions_count, add_actions) = run_action_reconciliation_test(input_batches)?;
959
960 assert_eq!(results.len(), 2, "Expected two batches in results");
962 assert_eq!(results[0].selection_vector(), &vec![true, true, true]);
963 assert_eq!(
964 results[1].selection_vector(),
965 &vec![false, false, false, true]
966 );
967 assert_eq!(actions_count, 4);
968 assert_eq!(add_actions, 0);
969
970 Ok(())
971 }
972
973 #[test]
976 fn test_action_reconciliation_actions_iter_file_actions() -> DeltaResult<()> {
977 let batch1 = vec![
979 r#"{"add":{"path":"file1","partitionValues":{"c1":"6","c2":"a"},"size":452,"modificationTime":1670892998137,"dataChange":true}}"#,
980 ];
981
982 let batch2 = vec![
984 r#"{"remove":{"path":"file1","deletionTimestamp":100,"dataChange":true,"partitionValues":{}}}"#,
986 r#"{"remove":{"path":"file2","deletionTimestamp":100,"dataChange":true,"partitionValues":{}}}"#,
988 ];
989
990 let batch3 = vec![
992 r#"{"add":{"path":"file2","partitionValues":{"c1":"6","c2":"a"},"size":452,"modificationTime":1670892998137,"dataChange":true}}"#,
993 ];
994
995 let input_batches = vec![
996 create_batch(batch1)?,
997 create_batch(batch2)?,
998 create_batch(batch3)?,
999 ];
1000 let (results, actions_count, add_actions) = run_action_reconciliation_test(input_batches)?;
1001
1002 assert_eq!(results.len(), 2); assert_eq!(results[0].selection_vector(), &vec![true]);
1005 assert_eq!(results[1].selection_vector(), &vec![false, true]);
1006 assert_eq!(actions_count, 2);
1007 assert_eq!(add_actions, 1);
1008
1009 Ok(())
1010 }
1011
1012 #[test]
1015 fn test_action_reconciliation_actions_iter_file_actions_with_deletion_vectors(
1016 ) -> DeltaResult<()> {
1017 let batch1 = vec![
1019 r#"{"add":{"path":"file1","partitionValues":{},"size":635,"modificationTime":100,"dataChange":true,"deletionVector":{"storageType":"ONE","pathOrInlineDv":"dv1","offset":1,"sizeInBytes":36,"cardinality":2}}}"#,
1021 r#"{"add":{"path":"file1","partitionValues":{},"size":635,"modificationTime":100,"dataChange":true,"deletionVector":{"storageType":"TWO","pathOrInlineDv":"dv2","offset":1,"sizeInBytes":36,"cardinality":2}}}"#,
1023 ];
1024
1025 let batch2 = vec![
1027 r#"{"remove":{"path":"file1","deletionTimestamp":100,"dataChange":true,"deletionVector":{"storageType":"ONE","pathOrInlineDv":"dv1","offset":1,"sizeInBytes":36,"cardinality":2}}}"#,
1029 r#"{"add":{"path":"file1","partitionValues":{},"size":635,"modificationTime":100,"dataChange":true,"deletionVector":{"storageType":"TWO","pathOrInlineDv":"dv2","offset":1,"sizeInBytes":36,"cardinality":2}}}"#,
1031 r#"{"remove":{"path":"file2","deletionTimestamp":100,"dataChange":true,"partitionValues":{}}}"#,
1033 ];
1034
1035 let input_batches = vec![create_batch(batch1)?, create_batch(batch2)?];
1036 let (results, actions_count, add_actions) = run_action_reconciliation_test(input_batches)?;
1037
1038 assert_eq!(results.len(), 2);
1040 assert_eq!(results[0].selection_vector(), &vec![true, true]);
1041 assert_eq!(results[1].selection_vector(), &vec![false, false, true]);
1042 assert_eq!(actions_count, 3);
1043 assert_eq!(add_actions, 2);
1044
1045 Ok(())
1046 }
1047
1048 #[test]
1049 fn test_action_reconciliation_visitor_txn_retention() -> DeltaResult<()> {
1050 let json_strings: StringArray = vec![
1051 r#"{"txn":{"appId":"app1","version":1,"lastUpdated":100}}"#,
1053 r#"{"txn":{"appId":"app2","version":2,"lastUpdated":2000}}"#,
1055 r#"{"txn":{"appId":"app3","version":3}}"#,
1057 r#"{"txn":{"appId":"app4","version":4,"lastUpdated":1000}}"#,
1059 ]
1060 .into();
1061 let batch = parse_json_batch(json_strings);
1062
1063 let mut seen_file_keys = HashSet::new();
1064 let mut seen_txns = HashSet::new();
1065 let mut seen_domains = HashSet::new();
1066 let mut visitor = ActionReconciliationVisitor::new(
1067 &mut seen_file_keys,
1068 true,
1069 vec![true; 4],
1070 0,
1071 false,
1072 false,
1073 &mut seen_txns,
1074 &mut seen_domains,
1075 Some(1000), );
1077
1078 visitor.visit_rows_of(batch.as_ref())?;
1079
1080 let expected = vec![false, true, true, false];
1083 assert_eq!(visitor.selection_vector, expected);
1084 assert_eq!(visitor.actions_count, 2);
1085 assert_eq!(visitor.seen_txns.len(), 2);
1086 assert!(visitor.seen_txns.contains("app2"));
1087 assert!(visitor.seen_txns.contains("app3"));
1088
1089 Ok(())
1090 }
1091
1092 #[test]
1093 fn test_action_reconciliation_actions_iter_with_txn_retention() -> DeltaResult<()> {
1094 let batch1 = vec![
1096 r#"{"protocol":{"minReaderVersion":1,"minWriterVersion":2}}"#,
1097 r#"{"metaData":{"id":"test1","format":{"provider":"parquet","options":{}},"schemaString":"{\"type\":\"struct\",\"fields\":[]}","partitionColumns":[],"configuration":{},"createdTime":1670892997849}}"#,
1098 r#"{"txn":{"appId":"old_app","version":1,"lastUpdated":100}}"#,
1100 r#"{"txn":{"appId":"new_app","version":2,"lastUpdated":2000}}"#,
1102 ];
1103
1104 let batch2 = vec![
1105 r#"{"txn":{"appId":"timeless_app","version":3}}"#,
1107 r#"{"txn":{"appId":"another_old","version":4,"lastUpdated":500}}"#,
1109 ];
1110
1111 let input_batches = vec![create_batch(batch1)?, create_batch(batch2)?];
1112
1113 let processor = ActionReconciliationProcessor::new(0, Some(1000));
1115 let results: Vec<_> = processor
1116 .process_actions_iter(input_batches.into_iter().map(Ok))
1117 .try_collect()?;
1118
1119 assert_eq!(results.len(), 2);
1121
1122 assert_eq!(
1124 results[0].filtered_data.selection_vector(),
1125 vec![true, true, false, true]
1126 );
1127 assert_eq!(results[0].actions_count, 3);
1128
1129 assert_eq!(
1131 results[1].filtered_data.selection_vector(),
1132 vec![true, false]
1133 );
1134 assert_eq!(results[1].actions_count, 1);
1135
1136 Ok(())
1137 }
1138
1139 mod test_mocks {
1143 use super::*;
1144
1145 pub(super) struct MockErrorGetData {
1147 error_on_field: &'static str,
1148 error_type: &'static str,
1149 }
1150
1151 impl MockErrorGetData {
1152 pub(super) fn new(error_on_field: &'static str, error_type: &'static str) -> Self {
1153 Self {
1154 error_on_field,
1155 error_type,
1156 }
1157 }
1158
1159 pub(super) fn default() -> Self {
1160 Self::new("", "")
1161 }
1162 }
1163
1164 impl<'a> GetData<'a> for MockErrorGetData {
1165 fn get_str(&'a self, _: usize, field_name: &str) -> DeltaResult<Option<&'a str>> {
1166 if field_name == self.error_on_field && self.error_type == "str" {
1167 Err(
1168 Error::UnexpectedColumnType(format!("{field_name} is not of type str"))
1169 .with_backtrace(),
1170 )
1171 } else {
1172 Ok(None)
1173 }
1174 }
1175
1176 fn get_int(&'a self, _: usize, field_name: &str) -> DeltaResult<Option<i32>> {
1177 if field_name == self.error_on_field && self.error_type == "int" {
1178 Err(
1179 Error::UnexpectedColumnType(format!("{field_name} is not of type i32"))
1180 .with_backtrace(),
1181 )
1182 } else {
1183 Ok(None)
1184 }
1185 }
1186 }
1187
1188 pub(super) struct FlexibleMock {
1190 pub(super) error_field: &'static str,
1191 }
1192
1193 impl<'a> GetData<'a> for FlexibleMock {
1194 fn get_str(&'a self, _: usize, field_name: &str) -> DeltaResult<Option<&'a str>> {
1195 if field_name == "txn.appId" {
1196 Ok(Some("test_app"))
1197 } else if field_name == "remove.path" {
1198 Ok(Some("test_path"))
1199 } else {
1200 Ok(None)
1201 }
1202 }
1203
1204 fn get_long(&'a self, _: usize, field_name: &str) -> DeltaResult<Option<i64>> {
1205 if field_name.contains(self.error_field) {
1206 Err(
1207 Error::UnexpectedColumnType(format!("{field_name} is not of type i64"))
1208 .with_backtrace(),
1209 )
1210 } else {
1211 Ok(None)
1212 }
1213 }
1214 }
1215 }
1216
1217 use test_mocks::*;
1218
1219 fn create_test_visitor<'a>(
1221 seen_file_keys: &'a mut HashSet<FileActionKey>,
1222 seen_txns: &'a mut HashSet<String>,
1223 seen_domains: &'a mut HashSet<String>,
1224 txn_expiration_timestamp: Option<i64>,
1225 ) -> ActionReconciliationVisitor<'a> {
1226 ActionReconciliationVisitor::new(
1227 seen_file_keys,
1228 true,
1229 vec![true; 1],
1230 0,
1231 false,
1232 false,
1233 seen_txns,
1234 seen_domains,
1235 txn_expiration_timestamp,
1236 )
1237 }
1238
1239 fn create_getters_with_error_at_index(
1241 error_index: usize,
1242 error_field: &'static str,
1243 error_type: &'static str,
1244 ) -> Vec<MockErrorGetData> {
1245 (0..15)
1246 .map(|i| {
1247 if i == error_index {
1248 MockErrorGetData::new(error_field, error_type)
1249 } else {
1250 MockErrorGetData::default()
1251 }
1252 })
1253 .collect()
1254 }
1255
1256 #[test]
1257 fn test_action_reconciliation_visitor_validation_and_type_errors() {
1258 let mut seen_file_keys = HashSet::new();
1260 let mut seen_txns = HashSet::new();
1261 let mut seen_domains = HashSet::new();
1262 let mut visitor =
1263 create_test_visitor(&mut seen_file_keys, &mut seen_txns, &mut seen_domains, None);
1264 let getter = MockErrorGetData::default();
1265 let getters = vec![&getter as &dyn GetData<'_>; 5]; let result = visitor.visit(1, &getters);
1267 assert!(result.is_err());
1268 assert!(result
1269 .unwrap_err()
1270 .to_string()
1271 .contains("Wrong number of visitor getters"));
1272
1273 let test_cases = [
1275 (0, "add.path", "str", "add.path is not of type str"),
1276 (9, "metaData.id", "str", "metaData.id is not of type str"),
1277 (
1278 10,
1279 "protocol.minReaderVersion",
1280 "int",
1281 "protocol.minReaderVersion is not of type i32",
1282 ),
1283 (11, "txn.appId", "str", "txn.appId is not of type str"),
1284 ];
1285
1286 for (getter_index, field_name, error_type, expected_error_text) in test_cases {
1287 let mut seen_file_keys = HashSet::new();
1288 let mut seen_txns = HashSet::new();
1289 let mut seen_domains = HashSet::new();
1290 let mut visitor =
1291 create_test_visitor(&mut seen_file_keys, &mut seen_txns, &mut seen_domains, None);
1292 let getters = create_getters_with_error_at_index(getter_index, field_name, error_type);
1293 let getter_refs: Vec<&dyn GetData<'_>> =
1294 getters.iter().map(|g| g as &dyn GetData<'_>).collect();
1295 let result = visitor.visit(1, &getter_refs);
1296 assert!(result.is_err(), "Expected error for {field_name}");
1297 assert!(result
1298 .unwrap_err()
1299 .to_string()
1300 .contains(expected_error_text));
1301 }
1302 }
1303
1304 #[test]
1305 fn test_action_reconciliation_visitor_complex_field_errors() {
1306 let mut seen_file_keys = HashSet::new();
1308 let mut seen_txns = HashSet::new();
1309 let mut seen_domains = HashSet::new();
1310 let mut visitor = create_test_visitor(
1311 &mut seen_file_keys,
1312 &mut seen_txns,
1313 &mut seen_domains,
1314 Some(1000),
1315 );
1316 let defaults = (0..11)
1317 .map(|_| MockErrorGetData::default())
1318 .collect::<Vec<_>>();
1319 let error_mock = FlexibleMock {
1320 error_field: "lastUpdated",
1321 };
1322 let domain_default = MockErrorGetData::default();
1323 let domain_removed_default = MockErrorGetData::default();
1324 let mut getters: Vec<&dyn GetData<'_>> =
1325 defaults.iter().map(|g| g as &dyn GetData<'_>).collect();
1326 getters.push(&error_mock); getters.push(&error_mock);
1328 getters.push(&domain_default); getters.push(&domain_removed_default); let result = visitor.visit(1, &getters);
1331 assert!(result.is_err());
1332 assert!(result
1333 .unwrap_err()
1334 .to_string()
1335 .contains("lastUpdated is not of type i64"));
1336
1337 let mut seen_file_keys = HashSet::new();
1339 let mut seen_txns = HashSet::new();
1340 let mut seen_domains = HashSet::new();
1341 let mut visitor =
1342 create_test_visitor(&mut seen_file_keys, &mut seen_txns, &mut seen_domains, None);
1343 let defaults = (0..4)
1344 .map(|_| MockErrorGetData::default())
1345 .collect::<Vec<_>>();
1346 let error_mock = FlexibleMock {
1347 error_field: "deletionTimestamp",
1348 };
1349 let defaults2 = (0..9)
1350 .map(|_| MockErrorGetData::default())
1351 .collect::<Vec<_>>();
1352 let mut getters: Vec<&dyn GetData<'_>> =
1353 defaults.iter().map(|g| g as &dyn GetData<'_>).collect();
1354 getters.push(&error_mock); getters.push(&error_mock); getters.extend(defaults2.iter().map(|g| g as &dyn GetData<'_>));
1357 let result = visitor.visit(1, &getters);
1358 assert!(result.is_err());
1359 assert!(result
1360 .unwrap_err()
1361 .to_string()
1362 .contains("deletionTimestamp is not of type i64"));
1363 }
1364
1365 #[test]
1366 fn test_action_reconciliation_processor_error_propagation() -> DeltaResult<()> {
1367 let json_strings: StringArray = vec![
1369 r#"{"add":{"path":"test","partitionValues":{},"size":100,"modificationTime":123,"dataChange":true}}"#,
1371 ].into();
1372 let actions = parse_json_batch(json_strings);
1373 let batch = ActionsBatch::new(actions, true);
1374
1375 let mut processor = ActionReconciliationProcessor::new(0, None);
1379 let result = processor.process_actions_batch(batch);
1380
1381 assert!(result.is_ok());
1383 let action_reconciliation_batch = result.unwrap();
1384 assert_eq!(action_reconciliation_batch.actions_count, 1);
1385 assert_eq!(action_reconciliation_batch.add_actions_count, 1);
1386
1387 Ok(())
1388 }
1389}