Skip to main content

buoyant_kernel/action_reconciliation/
log_replay.rs

1//! The [`ActionReconciliationProcessor`] implements specialized log replay logic for performing
2//! action reconciliation. It processes log files in reverse chronological order (newest to oldest)
3//! and selects the set of actions to be included.
4//!
5//! Uses cases include checkpointing and log compaction.
6//!
7//! ## Actions Included
8//!
9//! This processor applies several filtering and deduplication steps to each batch of log actions:
10//!
11//! 1. **Protocol and Metadata**: Retains exactly one of each - keeping only the latest protocol
12//!    and metadata actions.
13//! 2. **Txn Actions**: Keeps exactly one `txn` action for each unique app ID, always selecting
14//!    the latest one encountered.
15//! 3. **File Actions**: Resolves file actions to produce the latest state of the table, keeping
16//!    the most recent valid add actions and unexpired remove actions (tombstones) that are newer
17//!    than `minimum_file_retention_timestamp`.
18//!
19//! ## Architecture
20//!
21//! - [`ActionReconciliationVisitor`]: Implements [`RowVisitor`] to examine each action in a batch and
22//!   determine if it should be included. It maintains state for deduplication across multiple actions
23//!   in a batch and efficiently handles all filtering rules.
24//!
25//! - [`ActionReconciliationProcessor`]: Implements the [`LogReplayProcessor`] trait and orchestrates
26//!   the overall process. For each batch of log actions, it:
27//!   1. Creates a visitor with the current deduplication state
28//!   2. Applies the visitor to filter actions in the batch
29//!   3. Tracks state for deduplication across batches
30//!   4. Produces a [`ActionReconciliationBatch`] result which includes both the filtered data and counts of
31//!      actions selected
32//!
33use 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
47/// The [`ActionReconciliationProcessor`] is an implementation of the [`LogReplayProcessor`]
48/// trait that filters log segment actions.
49pub(crate) struct ActionReconciliationProcessor {
50    /// Tracks file actions that have been seen during log replay to avoid duplicates.
51    /// Contains (data file path, dv_unique_id) pairs as `FileActionKey` instances.
52    seen_file_keys: HashSet<FileActionKey>,
53    /// Indicates whether a protocol action has been seen in the log.
54    seen_protocol: bool,
55    /// Indicates whether a metadata action has been seen in the log.
56    seen_metadata: bool,
57    /// Set of transaction app IDs that have been processed to avoid duplicates.
58    seen_txns: HashSet<String>,
59    /// Set of domain names that have been processed to avoid duplicates.
60    /// For each unique domain, only the first (newest) domain metadata action is kept.
61    seen_domains: HashSet<String>,
62    /// Minimum timestamp for file retention, used for filtering expired tombstones.
63    minimum_file_retention_timestamp: i64,
64    /// Transaction expiration timestamp for filtering old transactions
65    txn_expiration_timestamp: Option<i64>,
66}
67
68/// This struct is the output of the [`ActionReconciliationProcessor`].
69///
70/// It contains the filtered batch of actions to be included, along with statistics about the
71/// number of actions filtered for inclusion.
72///
73/// # Warning
74///
75/// This iterator must be fully consumed to ensure proper collection of statistics. Additionally,
76/// all yielded data must be written to the specified path before e.g. calling
77/// [`CheckpointWriter::finalize`]. Failing to do so may result in data loss or corruption.
78pub(crate) struct ActionReconciliationBatch {
79    /// The filtered batch of actions.
80    pub(crate) filtered_data: FilteredEngineData,
81    /// The number of actions in the batch.
82    pub(crate) actions_count: i64,
83    /// The number of add actions in the batch.
84    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/// Stats for ActionReconciliationIterator
94#[derive(Debug, Default)]
95pub struct ActionReconciliationIteratorState {
96    actions_count: AtomicI64,
97    add_actions_count: AtomicI64,
98    is_exhausted: AtomicBool,
99}
100
101impl ActionReconciliationIteratorState {
102    /// Get the total number of actions processed
103    pub fn actions_count(&self) -> i64 {
104        self.actions_count.load(Ordering::Acquire)
105    }
106
107    /// Get the total number of add actions processed
108    pub fn add_actions_count(&self) -> i64 {
109        self.add_actions_count.load(Ordering::Acquire)
110    }
111
112    /// True if the iterator has been exhausted (all batches processed)
113    pub fn is_exhausted(&self) -> bool {
114        self.is_exhausted.load(Ordering::Acquire)
115    }
116}
117
118/// Iterator over action reconciliation data.
119///
120/// This iterator yields a stream of [`FilteredEngineData`] items while, tracking action
121/// counts. Used by both checkpoint and log compaction workflows.
122pub struct ActionReconciliationIterator {
123    inner: Box<dyn Iterator<Item = DeltaResult<ActionReconciliationBatch>> + Send>,
124    state: Arc<ActionReconciliationIteratorState>,
125}
126
127impl ActionReconciliationIterator {
128    /// Create a new iterator with counters initialized to 0
129    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    /// Get the shared state. This allows sharing of stats.
139    pub fn state(&self) -> Arc<ActionReconciliationIteratorState> {
140        Arc::clone(&self.state)
141    }
142
143    /// Helper to transform a batch: update metrics and extract filtered data
144    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    /// Processes a batch of actions read from the log during reverse chronological replay
185    /// and returns a [`ActionReconciliationBatch`], which contains the filtered actions,
186    /// along with statistics about the included actions.
187    ///
188    /// This method delegates the filtering logic to the [`ActionReconciliationVisitor`], which implements
189    /// the deduplication rules described in the module documentation. The method tracks
190    /// statistics about processed actions (total count, add actions count) and maintains
191    /// state for cross-batch deduplication.
192    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        // Create the action reconciliation visitor to process actions and update selection vector
200        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        // Update protocol and metadata seen flags
214        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    /// We never do data skipping for action reconciliation log replay (entire table state is always reproduced)
227    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
249/// A visitor that filters actions,
250///
251/// This visitor processes actions in newest-to-oldest order (as they appear in log
252/// replay) and applies deduplication logic for both file and non-file actions to
253/// produce the actions.
254///
255/// # File Action Filtering Rules:
256///   Kept Actions:
257/// - The first (newest) add action for each unique (path, dvId) pair
258/// - The first (newest) remove action for each unique (path, dvId) pair, but only if
259///   its deletionTimestamp > minimumFileRetentionTimestamp
260///   Omitted Actions:
261/// - Any file action (add/remove) with the same (path, dvId) as a previously processed action
262/// - All remove actions with deletionTimestamp ≤ minimumFileRetentionTimestamp
263/// - All remove actions with missing deletionTimestamp (defaults to 0)
264///
265/// The resulting filtered file actions represents files present in the table (add actions) and
266/// unexpired tombstones required for vacuum operations (remove actions).
267///
268/// # Non-File Action Filtering:
269/// - Keeps only the first protocol action (newest version)
270/// - Keeps only the first metadata action (most recent table metadata)
271/// - Keeps only the first txn action for each unique app ID
272/// - Keeps only the first domainMetadata action for each unique domain name
273///
274/// # Excluded Actions
275/// - CommitInfo, CDC, and CheckpointMetadata actions should not appear in the action
276///   batches processed by this visitor, as they are excluded by the schema used to
277///   read the log files upstream. If present, they will be ignored by the visitor.
278/// - Sidecar actions should also be excluded—when encountered in the log, the
279///   corresponding sidecar files are read to extract the referenced file actions,
280///   which are then included directly in the action stream instead of the sidecar actions themselves.
281/// - The CheckpointMetadata action is included down the wire when writing a V2 spec checkpoint.
282///
283/// # Memory Usage
284/// This struct has O(N + M + D) memory usage where:
285/// - N = number of txn actions with unique appIds
286/// - M = number of file actions with unique (path, dvId) pairs
287/// - D = number of domainMetadata actions with unique domain names
288///
289/// The resulting filtered set of actions are the reconciled actions.
290pub(crate) struct ActionReconciliationVisitor<'seen> {
291    // Deduplicates file actions (applies logic to filter Adds with corresponding Removes,
292    // and keep unexpired Removes). This deduplicator builds a set of seen file actions.
293    // This set has O(M) memory usage where M = number of file actions with unique (path, dvId) pairs
294    deduplicator: FileActionDeduplicator<'seen>,
295    // Tracks which rows to include in the final output
296    selection_vector: Vec<bool>,
297    // TODO: _last_checkpoint schema should be updated to use u64 instead of i64
298    // for fields that are not expected to be negative. (Issue #786)
299    // i64 to match the `_last_checkpoint` file schema
300    actions_count: i64,
301    // i64 to match the `_last_checkpoint` file schema
302    add_actions_count: i64,
303    // i64 for comparison with remove.deletionTimestamp
304    minimum_file_retention_timestamp: i64,
305    // Flag to track if we've seen a protocol action so we can keep only the first protocol action
306    seen_protocol: bool,
307    // Flag to track if we've seen a metadata action so we can keep only the first metadata action
308    seen_metadata: bool,
309    // Set of transaction IDs to deduplicate by appId
310    // This set has O(N) memory usage where N = number of txn actions with unique appIds
311    seen_txns: &'seen mut HashSet<String>,
312    // Set of domain names to deduplicate domainMetadata by domain
313    // This set has O(D) memory usage where D = number of domainMetadata actions with unique domains
314    seen_domains: &'seen mut HashSet<String>,
315    /// Transaction expiration timestamp for filtering old transactions
316    txn_expiration_timestamp: Option<i64>,
317}
318
319/// A projected column used by `ActionReconciliationVisitor`.
320///
321/// `index` is the position in the `getters: &[&dyn GetData]` slice.
322/// `name` is the fully-qualified field path used when calling `get_*` (and appears in errors).
323///
324/// Invariant: these constants must match the order in
325/// `ActionReconciliationVisitor::selected_column_names_and_types()`.
326#[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    // Projected columns in the same order as `selected_column_names_and_types()`.
341    // DV columns are defined individually for completeness, even when accessed via a start index.
342    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    /// Determines if a remove action tombstone has expired and should be excluded.
398    ///
399    /// A remove action includes a deletion_timestamp indicating when the deletion occurred. Physical
400    /// files are deleted lazily after a user-defined expiration time. Remove actions are kept to allow
401    /// concurrent readers to read snapshots at older versions.
402    ///
403    /// Tombstone expiration rules:
404    /// - If deletion_timestamp <= minimum_file_retention_timestamp: Expired (exclude)
405    /// - If deletion_timestamp > minimum_file_retention_timestamp: Valid (include)
406    /// - If deletion_timestamp is missing: Defaults to 0, treated as expired (exclude)
407    fn is_expired_tombstone<'a>(&self, i: usize, getter: &'a dyn GetData<'a>) -> DeltaResult<bool> {
408        // Ideally this should never be zero, but we are following the same behavior as Delta
409        // Spark and the Java Kernel.
410        // Note: When remove.deletion_timestamp is not present (defaulting to 0), the remove action
411        // will be excluded as it will be treated as expired.
412        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    /// Processes a potential file action to determine if it should be included.
419    ///
420    /// Returns `Ok(Some(true))` if the row contains a valid file action to be included.
421    /// Returns `Ok(Some(false))` if the row contains a file action but it's suppressed (duplicate/expired).
422    /// Returns `Ok(None)` if the row doesn't contain a file action (continue checking other action types).
423    /// Returns `Err(...)` if there was an error processing the action.
424    ///
425    /// Note: This function handles both add and remove actions, applying deduplication logic and
426    /// tombstone expiration rules as needed.
427    fn check_file_action<'a>(
428        &mut self,
429        i: usize,
430        getters: &[&'a dyn GetData<'a>],
431    ) -> DeltaResult<Option<bool>> {
432        // Extract the file action and handle errors immediately
433        let Some((file_key, is_add)) = self.deduplicator.extract_file_action(i, getters, false)?
434        else {
435            return Ok(None); // No file action found, continue checking other types
436        };
437
438        // Check for valid, non-duplicate adds and non-expired removes
439        let is_valid = if self.deduplicator.check_and_record_seen(file_key) {
440            false // duplicate!
441        } else if is_add {
442            self.add_actions_count += 1;
443            true
444        } else {
445            // Expired remove actions are not valid
446            !self.is_expired_tombstone(i, getters[Self::REMOVE_DELETION_TIMESTAMP.index])?
447        };
448        Ok(Some(is_valid))
449    }
450
451    /// Processes a potential protocol action to determine if it should be included.
452    ///
453    /// Returns `Ok(Some(true))` if the row contains a valid protocol action.
454    /// Returns `Ok(Some(false))` if the row contains a protocol action but it's suppressed (duplicate).
455    /// Returns `Ok(None)` if the row doesn't contain a protocol action (continue checking other action types).
456    /// Returns `Err(...)` if there was an error processing the action.
457    fn check_protocol_action<'a>(
458        &mut self,
459        i: usize,
460        getter: &'a dyn GetData<'a>,
461    ) -> DeltaResult<Option<bool>> {
462        // minReaderVersion is a required field, so we check for its presence to determine if this is a protocol action.
463        // Only return the first (newest) protocol action we see, ignoring other types
464        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    /// Processes a potential metadata action to determine if it should be included.
472    ///
473    /// Returns `Ok(Some(true))` if the row contains a valid metadata action.
474    /// Returns `Ok(Some(false))` if the row contains a metadata action but it's suppressed (duplicate).
475    /// Returns `Ok(None)` if the row doesn't contain a metadata action (continue checking other action types).
476    /// Returns `Err(...)` if there was an error processing the action.
477    fn check_metadata_action<'a>(
478        &mut self,
479        i: usize,
480        getter: &'a dyn GetData<'a>,
481    ) -> DeltaResult<Option<bool>> {
482        // id is a required field, so we check for its presence to determine if this is a metadata action.
483        // Only return the first (newest) metadata action we see, ignoring other types
484        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    /// Processes a potential txn action to determine if it should be included.
492    ///
493    /// Returns `Ok(Some(true))` if the row contains a valid txn action.
494    /// Returns `Ok(Some(false))` if the row contains a txn action but it's suppressed (duplicate/expired).
495    /// Returns `Ok(None)` if the row doesn't contain a txn action (continue checking other action types).
496    /// Returns `Err(...)` if there was an error processing the action.
497    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); // Not a txn action, continue checking other types
505        };
506
507        // Check retention if last_updated is present
508        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                    // Transaction is old, exclude it
515                    return Ok(Some(false));
516                }
517            }
518            // Note: transactions without last_updated are kept for backward compatibility
519        }
520
521        // If the app ID already exists in the set, the insertion will return false,
522        // indicating that this is a duplicate.
523        Ok(Some(self.seen_txns.insert(app_id.to_string())))
524    }
525
526    /// Processes a potential domainMetadata action to determine if it should be included.
527    ///
528    /// Returns `Ok(Some(true))` if the row contains a valid domainMetadata action.
529    /// Returns `Ok(Some(false))` if the row contains a domainMetadata action but it's suppressed
530    ///         (duplicate or tombstone with removed=true).
531    /// Returns `Ok(None)` if the row doesn't contain a domainMetadata action (continue checking other action types).
532    /// Returns `Err(...)` if there was an error processing the action.
533    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); // Not a domainMetadata action, continue checking other types
542        };
543
544        // Exclude tombstones (removed=true) from checkpoint per protocol spec
545        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        // If the domain already exists in the set, the insertion will return false,
553        // indicating that this is a duplicate.
554        Ok(Some(self.seen_domains.insert(domain.to_string())))
555    }
556
557    /// Determines if a row in the batch should be included.
558    ///
559    /// This method checks each action type in sequence, short-circuiting when:
560    /// - A valid action is found (`Some(true)`)
561    /// - A suppressed action is found (`Some(false)`)
562    /// - An error occurs (propagated immediately)
563    ///
564    /// Actions are checked in order of expected frequency of occurrence to optimize performance:
565    /// 1. File actions (most frequent)
566    /// 2. Txn actions
567    /// 3. DomainMetadata actions
568    /// 4. Protocol & Metadata actions (least frequent)
569    ///
570    /// Returns `Ok(true)` if the row should be included.
571    /// Returns `Ok(false)` if the row should be skipped.
572    /// Returns `Err(...)` if any validation or extraction failed.
573    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        // The data columns visited must be in the following order, which must match
604        // the order of fields in CHECKPOINT_ACTIONS_SCHEMA / COMPACTION_ACTIONS_SCHEMA:
605        // 1. ADD
606        // 2. REMOVE
607        // 3. METADATA
608        // 4. PROTOCOL
609        // 5. TXN
610        // 6. DOMAIN_METADATA
611        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                // File action columns
618                (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                // Non-file action columns
628                (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    /// Helper function to create test batches from JSON strings
669    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    /// Helper function which applies the [`ActionReconciliationProcessor`] to a set of
675    /// input batches and returns the results.
676    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, // minimum_file_retention_timestamp (no expired tombstones)
702            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,  // Row 0 is an add action (included)
713            true,  // Row 1 is a remove action (included)
714            false, // Row 2 is a commit info action (excluded)
715            true,  // Row 3 is a protocol action (included)
716            true,  // Row 4 is a metadata action (included)
717            false, // Row 5 is a cdc action (excluded)
718            false, // Row 6 is a sidecar action (excluded)
719            true,  // Row 7 is a txn action (included)
720            false, // Row 8 is a checkpointMetadata action (excluded)
721        ];
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    /// Tests the boundary conditions for tombstone expiration logic.
734    /// Specifically checks:
735    /// - Remove actions with deletionTimestamp == minimumFileRetentionTimestamp (should be excluded)
736    /// - Remove actions with deletionTimestamp < minimumFileRetentionTimestamp (should be excluded)
737    /// - Remove actions with deletionTimestamp > minimumFileRetentionTimestamp (should be included)
738    /// - Remove actions with missing deletionTimestamp (defaults to 0, should be excluded)
739    #[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            // Missing timestamp defaults to 0
747            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, // minimum_file_retention_timestamp (threshold set to 100)
760            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        // Only "one_above_threshold" should be kept
770        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, // is_log_batch = false (batch)
791            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        // The action should NOT be added to the seen_file_keys set as it's a reconciled batch
807        // and actions in reconciled batches do not conflict with each other.
808        // This is a key difference from log batches, where actions can conflict.
809        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            // Add action for file1 with deletion vector
817            r#"{"add":{"path":"file1","partitionValues":{},"size":635,"modificationTime":100,"dataChange":true,"deletionVector":{"storageType":"ONE","pathOrInlineDv":"dv1","offset":1,"sizeInBytes":36,"cardinality":2}}}"#,
818            // Remove action for file1 with a different deletion vector
819            r#"{"remove":{"path":"file1","deletionTimestamp":100,"dataChange":true,"deletionVector":{"storageType":"TWO","pathOrInlineDv":"dv2","offset":1,"sizeInBytes":36,"cardinality":2}}}"#,
820            // Remove action for file1 with another different deletion vector
821            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        // Pre-populate with txn app1
861        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,           // The visitor has already seen a protocol action
872            true,           // The visitor has already seen a metadata action
873            &mut seen_txns, // Pre-populated transaction
874            &mut seen_domains,
875            None,
876        );
877
878        visitor.visit_rows_of(batch.as_ref())?;
879
880        // All actions should be skipped as they have already been seen
881        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}}"#, // Duplicate txn
893            r#"{"txn":{"appId":"app2","version":1,"lastUpdated":123456789}}"#, // Different app ID
894            r#"{"protocol":{"minReaderVersion":3,"minWriterVersion":7}}"#,
895            r#"{"protocol":{"minReaderVersion":3,"minWriterVersion":7}}"#, // Duplicate protocol
896            r#"{"metaData":{"id":"testId","format":{"provider":"parquet","options":{}},"schemaString":"{\"type\":\"struct\",\"fields\":[{\"name\":\"value\",\"type\":\"integer\",\"nullable\":true,\"metadata\":{}}]}","partitionColumns":[],"configuration":{},"createdTime":1677811175819}}"#,
897            // Duplicate metadata
898            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, // is_log_batch
909            vec![true; 7],
910            0, // minimum_file_retention_timestamp
911            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        // First occurrence of each type should be included
921        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); // Two different app IDs
924        assert_eq!(visitor.actions_count, 4); // 2 txns + 1 protocol + 1 metadata
925
926        Ok(())
927    }
928
929    /// This test ensures that the processor correctly deduplicates and filters
930    /// non-file actions (metadata, protocol, txn) across multiple batches.
931    #[test]
932    fn test_action_reconciliation_actions_iter_non_file_actions() -> DeltaResult<()> {
933        // Batch 1: protocol, metadata, and txn actions
934        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        // Batch 2: duplicate actions, and a new txn action
941        let batch2 = vec![
942            // Duplicates that should be skipped
943            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            // Unique transaction (appId) should be included
947            r#"{"txn":{"appId":"app2","version":1,"lastUpdated":123456789}}"#,
948        ];
949
950        // Batch 3: a duplicate action (entire batch should be skipped)
951        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        // Verify results
961        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    /// This test ensures that the processor correctly deduplicates and filters
974    /// file actions (add, remove) across multiple batches.
975    #[test]
976    fn test_action_reconciliation_actions_iter_file_actions() -> DeltaResult<()> {
977        // Batch 1: add action (file1) - new, should be included
978        let batch1 = vec![
979            r#"{"add":{"path":"file1","partitionValues":{"c1":"6","c2":"a"},"size":452,"modificationTime":1670892998137,"dataChange":true}}"#,
980        ];
981
982        // Batch 2: remove actions - mixed inclusion
983        let batch2 = vec![
984            // Already seen file, should be excluded
985            r#"{"remove":{"path":"file1","deletionTimestamp":100,"dataChange":true,"partitionValues":{}}}"#,
986            // New file, should be included
987            r#"{"remove":{"path":"file2","deletionTimestamp":100,"dataChange":true,"partitionValues":{}}}"#,
988        ];
989
990        // Batch 3: add action (file2) - already seen, should be excluded
991        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        // Verify results
1003        assert_eq!(results.len(), 2); // The third batch should be filtered out since there are no selected actions
1004        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    /// This test ensures that the processor correctly deduplicates and filters
1013    /// file actions (add, remove) with deletion vectors across multiple batches.
1014    #[test]
1015    fn test_action_reconciliation_actions_iter_file_actions_with_deletion_vectors(
1016    ) -> DeltaResult<()> {
1017        // Batch 1: add actions with deletion vectors
1018        let batch1 = vec![
1019            // (file1, DV_ONE) New, should be included
1020            r#"{"add":{"path":"file1","partitionValues":{},"size":635,"modificationTime":100,"dataChange":true,"deletionVector":{"storageType":"ONE","pathOrInlineDv":"dv1","offset":1,"sizeInBytes":36,"cardinality":2}}}"#,
1021            // (file1, DV_TWO) New, should be included
1022            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        // Batch 2: mixed actions with duplicate and new entries
1026        let batch2 = vec![
1027            // (file1, DV_ONE): Already seen, should be excluded
1028            r#"{"remove":{"path":"file1","deletionTimestamp":100,"dataChange":true,"deletionVector":{"storageType":"ONE","pathOrInlineDv":"dv1","offset":1,"sizeInBytes":36,"cardinality":2}}}"#,
1029            // (file1, DV_TWO): Already seen, should be excluded
1030            r#"{"add":{"path":"file1","partitionValues":{},"size":635,"modificationTime":100,"dataChange":true,"deletionVector":{"storageType":"TWO","pathOrInlineDv":"dv2","offset":1,"sizeInBytes":36,"cardinality":2}}}"#,
1031            // New file, should be included
1032            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        // Verify results
1039        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            // Transaction with old timestamp (should be filtered)
1052            r#"{"txn":{"appId":"app1","version":1,"lastUpdated":100}}"#,
1053            // Transaction with recent timestamp (should be kept)
1054            r#"{"txn":{"appId":"app2","version":2,"lastUpdated":2000}}"#,
1055            // Transaction without lastUpdated (should be kept)
1056            r#"{"txn":{"appId":"app3","version":3}}"#,
1057            // Transaction exactly at expiration timestamp (should be filtered)
1058            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), // expiration timestamp
1076        );
1077
1078        visitor.visit_rows_of(batch.as_ref())?;
1079
1080        // app1 and app4 should be filtered out (too old)
1081        // app2 and app3 should be kept
1082        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        // Test that transaction retention works across multiple batches
1095        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            // Old transaction
1099            r#"{"txn":{"appId":"old_app","version":1,"lastUpdated":100}}"#,
1100            // Recent transaction
1101            r#"{"txn":{"appId":"new_app","version":2,"lastUpdated":2000}}"#,
1102        ];
1103
1104        let batch2 = vec![
1105            // Transaction without lastUpdated
1106            r#"{"txn":{"appId":"timeless_app","version":3}}"#,
1107            // Another old transaction
1108            r#"{"txn":{"appId":"another_old","version":4,"lastUpdated":500}}"#,
1109        ];
1110
1111        let input_batches = vec![create_batch(batch1)?, create_batch(batch2)?];
1112
1113        // Create processor with txn expiration timestamp
1114        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        // Verify results
1120        assert_eq!(results.len(), 2);
1121
1122        // First batch: protocol, metadata, and one recent txn (old_app filtered out)
1123        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        // Second batch: timeless_app kept, another_old filtered out
1130        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    // ERROR COVERAGE TESTS - These tests specifically target error paths to improve code coverage
1140
1141    // Test-only mock utilities module to avoid coverage noise
1142    mod test_mocks {
1143        use super::*;
1144
1145        /// Mock GetData implementation that can simulate type errors for testing error paths
1146        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        /// Flexible mock for complex field error scenarios
1189        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    /// Helper function to create a standard action reconciliation visitor for error testing
1220    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    /// Helper function to create 14 getters with one specific error getter at the given index
1240    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        // Test 1: Wrong getter count validation
1259        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]; // Wrong count (should be 15)!
1266        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        // Test 2: Basic type mismatch errors using parameterized approach
1274        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        // Test txn.lastUpdated with retention enabled
1307        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); // txn fields
1327        getters.push(&error_mock);
1328        getters.push(&domain_default); // domainMetadata.domain
1329        getters.push(&domain_removed_default); // domainMetadata.removed
1330        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        // Test remove.deletionTimestamp
1338        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); // remove.path
1355        getters.push(&error_mock); // remove.deletionTimestamp - ERROR!
1356        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        // Test that errors from the visitor are properly propagated by the processor
1368        let json_strings: StringArray = vec![
1369            // This will create valid data that parses correctly
1370            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        // Create a processor and try to process the batch
1376        // We can't easily trigger an error in the normal flow since parse_json_batch creates valid data
1377        // But this test ensures the error propagation path exists and is tested
1378        let mut processor = ActionReconciliationProcessor::new(0, None);
1379        let result = processor.process_actions_batch(batch);
1380
1381        // This should succeed - the test mainly verifies that the error propagation paths compile
1382        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}