Skip to main content

risingwave_connector/source/iceberg/
mod.rs

1// Copyright 2024 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15pub mod parquet_file_handler;
16pub mod planner;
17pub mod update_planner;
18pub mod update_reader;
19pub mod update_state;
20
21pub mod metrics;
22use std::collections::{HashMap, HashSet};
23use std::sync::Arc;
24
25use anyhow::anyhow;
26use async_trait::async_trait;
27use futures::StreamExt;
28use futures_async_stream::{for_await, try_stream};
29use iceberg::Catalog;
30use iceberg::expr::{BoundPredicate, Predicate as IcebergPredicate};
31use iceberg::scan::FileScanTask;
32use iceberg::spec::{FormatVersion, Schema, TableMetadata};
33use iceberg::table::Table;
34pub use parquet_file_handler::*;
35use phf::{Set, phf_set};
36pub use planner::{
37    IcebergBoundedScan, IcebergIncrementalScan, IcebergScanMetricsLabels, IcebergScanPlan,
38    IcebergScanPlanner, IcebergScanProjection, IcebergScanTaskBatchMode, IcebergScanTaskPlanner,
39    PersistedFileScanTask,
40};
41use risingwave_common::array::arrow::IcebergArrowConvert;
42use risingwave_common::array::{
43    ArrayBuilder, ArrayImpl, DataChunk, I64Array, Utf8Array, VariantArrayBuilder,
44};
45use risingwave_common::bail;
46use risingwave_common::types::JsonbVal;
47use risingwave_common_estimate_size::EstimateSize;
48use risingwave_pb::batch_plan::iceberg_scan_node::IcebergScanType;
49use serde::{Deserialize, Serialize};
50
51pub use self::metrics::{GLOBAL_ICEBERG_SCAN_METRICS, IcebergFileScanMetrics, IcebergScanMetrics};
52use crate::connector_common::{
53    IcebergCommon, IcebergTableIdentifier, iceberg_java_catalog_props_from_options,
54};
55use crate::enforce_secret::{EnforceSecret, EnforceSecretError};
56use crate::error::{ConnectorError, ConnectorResult};
57use crate::parser::ParserConfig;
58use crate::source::{
59    BoxSourceChunkStream, Column, SourceContextRef, SourceEnumeratorContextRef, SourceProperties,
60    SplitEnumerator, SplitId, SplitMetaData, SplitReader, UnknownFields,
61};
62pub const ICEBERG_CONNECTOR: &str = "iceberg";
63pub const STREAMING_UPDATES_KEY: &str = "streaming_updates";
64
65fn validate_update_projection(schema: &Schema, field_ids: &[i32]) -> ConnectorResult<()> {
66    let mut ids = HashSet::new();
67    for id in field_ids {
68        risingwave_common::ensure!(
69            ids.insert(*id)
70                && !iceberg::metadata_columns::is_metadata_field(*id)
71                && schema
72                    .as_struct()
73                    .fields()
74                    .iter()
75                    .any(|field| field.id == *id),
76            "update projection requires unique stored top-level fields, not virtual metadata"
77        );
78    }
79    Ok(())
80}
81
82#[derive(Clone, Debug, Deserialize, with_options::WithOptions)]
83pub struct IcebergProperties {
84    /// Opt in to Insert/Delete ingestion of RisingWave PK-index sink output.
85    #[serde(default, deserialize_with = "crate::deserialize_bool_from_string")]
86    pub streaming_updates: bool,
87
88    #[serde(flatten)]
89    pub common: IcebergCommon,
90
91    #[serde(flatten)]
92    pub table: IcebergTableIdentifier,
93
94    // For jdbc catalog
95    #[serde(rename = "catalog.jdbc.user")]
96    pub jdbc_user: Option<String>,
97    #[serde(rename = "catalog.jdbc.password")]
98    pub jdbc_password: Option<String>,
99
100    #[serde(flatten)]
101    pub unknown_fields: HashMap<String, String>,
102}
103
104impl EnforceSecret for IcebergProperties {
105    const ENFORCE_SECRET_PROPERTIES: Set<&'static str> = phf_set! {
106        "catalog.jdbc.password",
107    };
108
109    fn enforce_secret<'a>(prop_iter: impl Iterator<Item = &'a str>) -> ConnectorResult<()> {
110        for prop in prop_iter {
111            IcebergCommon::enforce_one(prop)?;
112            if Self::ENFORCE_SECRET_PROPERTIES.contains(prop) {
113                return Err(EnforceSecretError {
114                    key: prop.to_owned(),
115                }
116                .into());
117            }
118        }
119        Ok(())
120    }
121}
122
123impl IcebergProperties {
124    fn java_catalog_props(&self) -> HashMap<String, String> {
125        let mut java_catalog_props = iceberg_java_catalog_props_from_options(
126            self.unknown_fields
127                .iter()
128                .map(|(key, value)| (key.as_str(), value.as_str())),
129        );
130        if let Some(jdbc_user) = self.jdbc_user.clone() {
131            java_catalog_props.insert("jdbc.user".to_owned(), jdbc_user);
132        }
133        if let Some(jdbc_password) = self.jdbc_password.clone() {
134            java_catalog_props.insert("jdbc.password".to_owned(), jdbc_password);
135        }
136        java_catalog_props
137    }
138
139    pub async fn create_catalog(&self) -> ConnectorResult<Arc<dyn Catalog>> {
140        self.common
141            .resolve_catalog_config(self.java_catalog_props())?
142            .create_catalog()
143            .await
144    }
145
146    pub async fn load_table(&self) -> ConnectorResult<Table> {
147        self.common
148            .resolve_catalog_config(self.java_catalog_props())?
149            .load_table(&self.table)
150            .await
151    }
152}
153
154impl SourceProperties for IcebergProperties {
155    type Split = IcebergSplit;
156    type SplitEnumerator = IcebergSplitEnumerator;
157    type SplitReader = IcebergFileReader;
158
159    const SOURCE_NAME: &'static str = ICEBERG_CONNECTOR;
160}
161
162impl UnknownFields for IcebergProperties {
163    fn unknown_fields(&self) -> HashMap<String, String> {
164        self.unknown_fields.clone()
165    }
166}
167
168#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
169pub enum IcebergFileScanTask {
170    Data(Vec<FileScanTask>),
171    EqualityDelete(Vec<FileScanTask>),
172    PositionDelete(Vec<FileScanTask>),
173}
174
175impl IcebergFileScanTask {
176    pub fn tasks(&self) -> &[FileScanTask] {
177        match self {
178            IcebergFileScanTask::Data(file_scan_tasks)
179            | IcebergFileScanTask::EqualityDelete(file_scan_tasks)
180            | IcebergFileScanTask::PositionDelete(file_scan_tasks) => file_scan_tasks,
181        }
182    }
183
184    pub fn is_empty(&self) -> bool {
185        self.tasks().is_empty()
186    }
187
188    pub fn files(&self) -> Vec<String> {
189        self.tasks()
190            .iter()
191            .map(|task| task.data_file_path.clone())
192            .collect()
193    }
194
195    pub fn predicate(&self) -> Option<&BoundPredicate> {
196        let first_task = self.tasks().first()?;
197        first_task.predicate.as_ref()
198    }
199
200    fn strip_non_serializable_planning_context(&mut self) {
201        let tasks = match self {
202            IcebergFileScanTask::Data(tasks)
203            | IcebergFileScanTask::EqualityDelete(tasks)
204            | IcebergFileScanTask::PositionDelete(tasks) => tasks,
205        };
206
207        for task in tasks {
208            // These fields are deliberately not serializable in Iceberg. The previous
209            // Iceberg dependency skipped them during serde, so retain that split format.
210            task.partition = None;
211            task.partition_spec = None;
212            task.name_mapping = None;
213            task.unified_partition_type = None;
214        }
215    }
216}
217
218#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
219pub struct IcebergSplit {
220    pub split_id: i64,
221    pub task: IcebergFileScanTask,
222    #[serde(default, skip_serializing_if = "Option::is_none")]
223    pub limit: Option<u64>,
224}
225
226impl IcebergSplit {
227    #[allow(deprecated)]
228    pub fn empty(iceberg_scan_type: IcebergScanType) -> Self {
229        let task = match iceberg_scan_type {
230            IcebergScanType::DataScan => IcebergFileScanTask::Data(vec![]),
231            IcebergScanType::EqualityDeleteScan => IcebergFileScanTask::EqualityDelete(vec![]),
232            IcebergScanType::PositionDeleteScan => IcebergFileScanTask::PositionDelete(vec![]),
233            IcebergScanType::Unspecified | IcebergScanType::CountStar => {
234                // These scan types do not carry file tasks. Keep the split serializable without
235                // introducing a new empty-task variant.
236                IcebergFileScanTask::Data(vec![])
237            }
238        };
239        Self {
240            split_id: 0,
241            task,
242            limit: None,
243        }
244    }
245}
246
247impl SplitMetaData for IcebergSplit {
248    fn id(&self) -> SplitId {
249        self.split_id.to_string().into()
250    }
251
252    fn restore_from_json(value: JsonbVal) -> ConnectorResult<Self> {
253        serde_json::from_value(value.take()).map_err(|e| anyhow!(e).into())
254    }
255
256    fn encode_to_json(&self) -> JsonbVal {
257        let mut split = self.clone();
258        split.task.strip_non_serializable_planning_context();
259        serde_json::to_value(split)
260            .expect("iceberg split serialization should not fail")
261            .into()
262    }
263
264    fn update_offset(&mut self, _last_seen_offset: String) -> ConnectorResult<()> {
265        // Iceberg source progress is tracked by persisted file tasks in the stream state table.
266        // A split does not carry an intra-file offset until partial-file reads are supported.
267        Ok(())
268    }
269}
270
271#[derive(Debug, Clone)]
272pub struct IcebergSplitEnumerator {
273    config: IcebergProperties,
274}
275
276#[derive(Debug, Clone)]
277pub struct IcebergDeleteParameters {
278    pub equality_delete_columns: Vec<String>,
279    pub has_position_delete: bool,
280    pub snapshot_id: Option<i64>,
281}
282
283#[async_trait]
284impl SplitEnumerator for IcebergSplitEnumerator {
285    type Properties = IcebergProperties;
286    type Split = IcebergSplit;
287
288    async fn new(
289        properties: Self::Properties,
290        context: SourceEnumeratorContextRef,
291    ) -> ConnectorResult<Self> {
292        Ok(Self::new_inner(properties, context))
293    }
294
295    async fn list_splits(&mut self) -> ConnectorResult<Vec<Self::Split>> {
296        // Like file source, iceberg streaming source has a List Executor and a Fetch Executor,
297        // instead of relying on SplitEnumerator on meta.
298        // TODO: add some validation logic here.
299        Ok(vec![])
300    }
301}
302impl IcebergSplitEnumerator {
303    pub fn new_inner(properties: IcebergProperties, _context: SourceEnumeratorContextRef) -> Self {
304        Self { config: properties }
305    }
306}
307
308#[derive(Debug, Clone, PartialEq, Eq, Hash)]
309pub enum IcebergTimeTravelInfo {
310    Version(i64),
311    TimestampMs(i64),
312}
313
314#[derive(Debug, Clone)]
315pub struct IcebergListResult {
316    pub data_files: Vec<FileScanTask>,
317    pub equality_delete_files: Vec<FileScanTask>,
318    pub position_delete_files: Vec<FileScanTask>,
319    pub equality_delete_columns: Vec<String>,
320    pub format_version: FormatVersion,
321    pub schema: std::sync::Arc<iceberg::spec::Schema>,
322}
323
324impl IcebergSplitEnumerator {
325    pub fn get_snapshot_id(
326        table: &Table,
327        time_travel_info: Option<IcebergTimeTravelInfo>,
328    ) -> ConnectorResult<Option<i64>> {
329        Self::get_snapshot_id_from_metadata(table.metadata(), time_travel_info)
330    }
331
332    fn get_snapshot_id_from_metadata(
333        metadata: &TableMetadata,
334        time_travel_info: Option<IcebergTimeTravelInfo>,
335    ) -> ConnectorResult<Option<i64>> {
336        let snapshot_id = match time_travel_info {
337            Some(IcebergTimeTravelInfo::Version(version)) => {
338                let Some(snapshot) = metadata.snapshot_by_id(version) else {
339                    bail!("Cannot find the snapshot id in the iceberg table.");
340                };
341                Some(snapshot.snapshot_id())
342            }
343            Some(IcebergTimeTravelInfo::TimestampMs(timestamp)) => {
344                let snapshot_log = metadata
345                    .history()
346                    .iter()
347                    .rev()
348                    .find(|snapshot_log| snapshot_log.timestamp_ms() <= timestamp);
349                match snapshot_log {
350                    Some(snapshot_log) => Some(snapshot_log.snapshot_id),
351                    None => {
352                        // convert unix time to human-readable time
353                        let time = chrono::DateTime::from_timestamp_millis(timestamp);
354                        if let Some(time) = time {
355                            tracing::warn!("Cannot find a snapshot older than {}", time);
356                        } else {
357                            tracing::warn!("Cannot find a snapshot");
358                        }
359                        return Ok(None);
360                    }
361                }
362            }
363            None => metadata.current_snapshot_id(),
364        };
365        Ok(snapshot_id)
366    }
367
368    pub async fn list_scan_tasks(
369        &self,
370        time_travel_info: Option<IcebergTimeTravelInfo>,
371        predicate: IcebergPredicate,
372    ) -> ConnectorResult<Option<IcebergListResult>> {
373        let table = self.config.load_table().await?;
374        let snapshot_id = Self::get_snapshot_id(&table, time_travel_info)?;
375
376        let Some(snapshot_id) = snapshot_id else {
377            return Ok(None);
378        };
379        let res = self
380            .list_scan_tasks_inner(&table, snapshot_id, predicate)
381            .await?;
382        Ok(Some(res))
383    }
384
385    async fn list_scan_tasks_inner(
386        &self,
387        table: &Table,
388        snapshot_id: i64,
389        predicate: IcebergPredicate,
390    ) -> ConnectorResult<IcebergListResult> {
391        let format_version = table.metadata().format_version();
392        let table_schema = table.metadata().current_schema();
393        tracing::debug!("iceberg_table_schema: {:?}", table_schema);
394
395        let mut position_delete_files = vec![];
396        let mut position_delete_files_set = HashSet::new();
397        let mut data_files = vec![];
398        let mut equality_delete_files = vec![];
399        let mut equality_delete_files_set = HashSet::new();
400        let mut equality_delete_ids = None;
401        let mut scan_builder = table.scan().snapshot_id(snapshot_id).select_all();
402        if predicate != IcebergPredicate::AlwaysTrue {
403            scan_builder = scan_builder.with_filter(predicate.clone());
404        }
405        let scan = scan_builder.build()?;
406        let file_scan_stream = scan.plan_files().await?;
407
408        #[for_await]
409        for task in file_scan_stream {
410            let task: FileScanTask = task?;
411
412            // Collect delete files for separate scan types, but keep task.deletes intact
413            for delete_file in &task.deletes {
414                match delete_file.file_type {
415                    iceberg::spec::DataContentType::Data => {
416                        bail!("Data file should not in task deletes");
417                    }
418                    iceberg::spec::DataContentType::EqualityDeletes => {
419                        if equality_delete_files_set.insert(delete_file.file_path.clone()) {
420                            if equality_delete_ids.is_none() {
421                                equality_delete_ids = delete_file.equality_ids.clone();
422                            } else if equality_delete_ids != delete_file.equality_ids {
423                                bail!(
424                                    "The schema of iceberg equality delete file must be consistent"
425                                );
426                            }
427                            equality_delete_files.push(delete_file.to_file_scan_task(&task));
428                        }
429                    }
430                    iceberg::spec::DataContentType::PositionDeletes => {
431                        if position_delete_files_set.insert(delete_file.file_path.clone()) {
432                            position_delete_files.push(delete_file.to_file_scan_task(&task));
433                        }
434                    }
435                }
436            }
437
438            // Top-level scan tasks always represent data files. Keep their delete
439            // descriptors intact so the SDK reader can apply them when requested.
440            data_files.push(task);
441        }
442        let schema = table_schema.clone();
443        let equality_delete_columns = equality_delete_ids
444            .unwrap_or_default()
445            .into_iter()
446            .map(|id| match schema.name_by_field_id(id) {
447                Some(name) => Ok::<std::string::String, ConnectorError>(name.to_owned()),
448                None => bail!("Delete field id {} not found in schema", id),
449            })
450            .collect::<ConnectorResult<Vec<_>>>()?;
451
452        Ok(IcebergListResult {
453            data_files,
454            equality_delete_files,
455            position_delete_files,
456            equality_delete_columns,
457            format_version,
458            schema,
459        })
460    }
461
462    /// Uniformly distribute scan tasks to compute nodes.
463    /// It's deterministic so that it can best utilize the data locality.
464    ///
465    /// # Arguments
466    /// * `file_scan_tasks`: The file scan tasks to be split.
467    /// * `split_num`: The number of splits to be created.
468    ///
469    /// This algorithm is based on a min-heap. It will push all groups into the heap, and then pop the smallest group and add the file scan task to it.
470    /// Ensure that the total length of each group is as balanced as possible.
471    /// The time complexity is O(n log k), where n is the number of file scan tasks and k is the number of splits.
472    /// The space complexity is O(k), where k is the number of splits.
473    /// The algorithm is stable, so the order of the file scan tasks will be preserved.
474    pub fn split_n_vecs(
475        file_scan_tasks: Vec<FileScanTask>,
476        split_num: usize,
477    ) -> Vec<Vec<FileScanTask>> {
478        IcebergScanTaskPlanner::split_n_vecs(file_scan_tasks, split_num)
479    }
480}
481
482pub struct IcebergScanOpts {
483    pub chunk_size: usize,
484    pub need_seq_num: bool,
485    pub need_file_path_and_pos: bool,
486    pub handle_delete_files: bool,
487}
488
489/// Scan a data file. Delete files are handled by the iceberg-rust `reader.read` implementation.
490#[try_stream(ok = DataChunk, error = ConnectorError)]
491pub async fn scan_task_to_chunk_with_deletes(
492    table: Table,
493    mut data_file_scan_task: FileScanTask,
494    IcebergScanOpts {
495        chunk_size,
496        need_seq_num,
497        need_file_path_and_pos,
498        handle_delete_files,
499    }: IcebergScanOpts,
500    metrics: Option<IcebergFileScanMetrics>,
501) {
502    let num_delete_files = data_file_scan_task.deletes.len();
503    let expected_record_count = data_file_scan_task.record_count;
504    let file_start = std::time::Instant::now();
505
506    let read_metrics = metrics.clone();
507    let mut read_bytes = scopeguard::guard(0u64, move |read_bytes| {
508        if let Some(metrics) = read_metrics {
509            metrics.record_read_bytes(read_bytes);
510        }
511    });
512
513    let data_file_path = data_file_scan_task.data_file_path.clone();
514    let data_sequence_number = data_file_scan_task.sequence_number;
515
516    tracing::debug!(
517        "scan_task_to_chunk_with_deletes: data_file={}, handle_delete_files={}, total_delete_files={}",
518        data_file_path,
519        handle_delete_files,
520        data_file_scan_task.deletes.len()
521    );
522
523    if !handle_delete_files {
524        // Keep the delete files from being applied when the caller opts out.
525        data_file_scan_task.deletes.clear();
526    }
527
528    // Read the data file; delete application is delegated to the reader.
529    let reader = table
530        .reader_builder()
531        .with_batch_size(chunk_size)
532        .with_row_group_filtering_enabled(true)
533        .build();
534    let file_scan_stream = tokio_stream::once(Ok(data_file_scan_task.clone()));
535
536    let mut record_batch_stream: iceberg::scan::ArrowRecordBatchStream =
537        reader.read(Box::pin(file_scan_stream))?.stream();
538
539    // The reader rejects a file with shredded variant columns before yielding any batch.
540    // Retry without the variant columns; NULL columns are spliced back in below.
541    let mut null_padded_variant_positions: Option<Vec<usize>> = None;
542    let record_batch_stream: iceberg::scan::ArrowRecordBatchStream =
543        match record_batch_stream.next().await {
544            Some(Err(e)) if is_shredded_variant_rejection(&e) => {
545                let (variant_field_ids, variant_positions, variant_names) =
546                    projected_variant_columns(&data_file_scan_task);
547                if variant_field_ids.is_empty() {
548                    return Err(e.into());
549                }
550                tracing::warn!(
551                    data_file_path,
552                    columns = ?variant_names,
553                    "shredded variant columns are not supported yet; reading them as NULL",
554                );
555                null_padded_variant_positions = Some(variant_positions);
556
557                let mut reduced_task = data_file_scan_task;
558                reduced_task
559                    .project_field_ids
560                    .retain(|id| !variant_field_ids.contains(id));
561                let reader = table
562                    .reader_builder()
563                    .with_batch_size(chunk_size)
564                    .with_row_group_filtering_enabled(true)
565                    .build();
566                reader
567                    .read(Box::pin(tokio_stream::once(Ok(reduced_task))))?
568                    .stream()
569            }
570            first => Box::pin(futures::stream::iter(first).chain(record_batch_stream)),
571        };
572    let mut record_batch_stream = record_batch_stream.enumerate();
573
574    let mut total_rows_read: u64 = 0;
575
576    // Process each record batch. Delete application is handled by the SDK.
577    while let Some((batch_index, record_batch)) = record_batch_stream.next().await {
578        let record_batch = record_batch?;
579        let batch_start_pos = (batch_index * chunk_size) as i64;
580
581        let mut chunk = IcebergArrowConvert.chunk_from_record_batch(&record_batch)?;
582        if let Some(positions) = &null_padded_variant_positions {
583            chunk = pad_null_variant_columns(chunk, positions, record_batch.num_rows());
584        }
585        let row_count = chunk.capacity();
586        total_rows_read += row_count as u64;
587
588        // Add metadata columns if requested
589        if need_seq_num {
590            let (mut columns, visibility) = chunk.into_parts();
591            columns.push(Arc::new(ArrayImpl::Int64(I64Array::from_iter(
592                std::iter::repeat_n(data_sequence_number, row_count),
593            ))));
594            chunk = DataChunk::from_parts(columns.into(), visibility);
595        }
596
597        if need_file_path_and_pos {
598            let (mut columns, visibility) = chunk.into_parts();
599            columns.push(Arc::new(ArrayImpl::Utf8(Utf8Array::from_iter(
600                std::iter::repeat_n(data_file_path.as_str(), row_count),
601            ))));
602
603            // Generate position values for each row in the batch
604            let positions: Vec<i64> =
605                (batch_start_pos..(batch_start_pos + row_count as i64)).collect();
606            columns.push(Arc::new(ArrayImpl::Int64(I64Array::from_iter(positions))));
607
608            chunk = DataChunk::from_parts(columns.into(), visibility);
609        }
610
611        *read_bytes += chunk.estimated_heap_size() as u64;
612        yield chunk;
613    }
614
615    // Record per-file metrics after reading all batches.
616    if let Some(metrics) = metrics {
617        metrics.record_file_read_duration(file_start.elapsed().as_secs_f64());
618
619        if total_rows_read > 0 {
620            metrics.record_rows_read(total_rows_read);
621        }
622
623        metrics.record_file_read();
624
625        // APPROXIMATE: Estimate delete rows applied. The delta between expected_record_count
626        // and actual rows read may also include predicate pushdown / row-group pruning effects,
627        // so this metric can overcount. It is still useful as an approximate signal for
628        // detecting whether delete files cause significant row filtering.
629        if handle_delete_files
630            && num_delete_files > 0
631            && let Some(expected) = expected_record_count
632        {
633            let deleted = expected.saturating_sub(total_rows_read);
634            if deleted > 0 {
635                metrics.record_delete_rows_applied(deleted);
636            }
637        }
638    }
639}
640
641/// Whether the error is the reader's per-file rejection of shredded variant columns.
642// `IcebergError` hides the inner error, so the raw one is needed to inspect kind/message.
643#[expect(clippy::disallowed_types)]
644fn is_shredded_variant_rejection(e: &iceberg::Error) -> bool {
645    e.kind() == iceberg::ErrorKind::FeatureUnsupported && e.message().contains("shredded variant")
646}
647
648/// The projected VARIANT columns of a task: their field ids, their positions in the
649/// projected column order, and their names.
650fn projected_variant_columns(task: &FileScanTask) -> (Vec<i32>, Vec<usize>, Vec<String>) {
651    let mut field_ids = Vec::new();
652    let mut positions = Vec::new();
653    let mut names = Vec::new();
654    for (position, field_id) in task.project_field_ids.iter().enumerate() {
655        if let Some(field) = task.schema.field_by_id(*field_id)
656            && matches!(field.field_type.as_ref(), iceberg::spec::Type::Variant(_))
657        {
658            field_ids.push(*field_id);
659            positions.push(position);
660            names.push(field.name.clone());
661        }
662    }
663    (field_ids, positions, names)
664}
665
666/// Insert all-NULL variant columns at the given projected positions.
667fn pad_null_variant_columns(chunk: DataChunk, positions: &[usize], row_count: usize) -> DataChunk {
668    let (mut columns, visibility) = chunk.into_parts();
669    for &position in positions {
670        let mut builder = VariantArrayBuilder::new(row_count);
671        for _ in 0..row_count {
672            builder.append_null();
673        }
674        columns.insert(position, Arc::new(ArrayImpl::Variant(builder.finish())));
675    }
676    DataChunk::from_parts(columns.into(), visibility)
677}
678
679#[derive(Debug)]
680pub struct IcebergFileReader {}
681
682#[async_trait]
683impl SplitReader for IcebergFileReader {
684    type Properties = IcebergProperties;
685    type Split = IcebergSplit;
686
687    async fn new(
688        _props: IcebergProperties,
689        _splits: Vec<IcebergSplit>,
690        _parser_config: ParserConfig,
691        _source_ctx: SourceContextRef,
692        _columns: Option<Vec<Column>>,
693    ) -> ConnectorResult<Self> {
694        unimplemented!()
695    }
696
697    fn into_stream(self) -> BoxSourceChunkStream {
698        unimplemented!()
699    }
700}
701
702#[cfg(test)]
703mod tests {
704    use std::collections::HashMap;
705    use std::sync::Arc;
706
707    use iceberg::scan::FileScanTask;
708    use iceberg::spec::{
709        FormatVersion, MAIN_BRANCH, NestedField, Operation, PrimitiveType, Schema, Snapshot,
710        SortOrder, Struct, Summary, TableMetadataBuilder, Type, UnboundPartitionSpec,
711    };
712
713    use super::*;
714
715    fn test_snapshot(
716        snapshot_id: i64,
717        parent_snapshot_id: Option<i64>,
718        timestamp_ms: i64,
719    ) -> Snapshot {
720        Snapshot::builder()
721            .with_snapshot_id(snapshot_id)
722            .with_parent_snapshot_id(parent_snapshot_id)
723            .with_sequence_number(snapshot_id)
724            .with_timestamp_ms(timestamp_ms)
725            .with_manifest_list(format!("/snap-{snapshot_id}.avro"))
726            .with_summary(Summary {
727                operation: Operation::Append,
728                additional_properties: HashMap::new(),
729            })
730            .with_schema_id(0)
731            .build()
732    }
733
734    fn test_table_metadata_builder() -> TableMetadataBuilder {
735        TableMetadataBuilder::new(
736            Schema::builder()
737                .with_fields(vec![
738                    NestedField::new(1, "id", Type::Primitive(PrimitiveType::Long), false).into(),
739                ])
740                .build()
741                .unwrap(),
742            UnboundPartitionSpec::builder().build(),
743            SortOrder::unsorted_order(),
744            "s3://warehouse/db/table".to_owned(),
745            FormatVersion::V2,
746            HashMap::new(),
747        )
748        .unwrap()
749    }
750
751    #[test]
752    fn test_get_snapshot_id_uses_main_branch_history_for_timestamp() {
753        let metadata = test_table_metadata_builder()
754            .set_branch_snapshot(test_snapshot(1, None, 1_000), MAIN_BRANCH)
755            .unwrap()
756            .build()
757            .unwrap()
758            .metadata;
759        let metadata = metadata
760            .into_builder(Some("s3://warehouse/db/table/v2.metadata.json".to_owned()))
761            .set_branch_snapshot(test_snapshot(2, Some(1), 2_000), MAIN_BRANCH)
762            .unwrap()
763            .build()
764            .unwrap()
765            .metadata;
766        let metadata = metadata
767            .into_builder(Some("s3://warehouse/db/table/v3.metadata.json".to_owned()))
768            .set_branch_snapshot(test_snapshot(3, Some(1), 3_000), "audit")
769            .unwrap()
770            .build()
771            .unwrap()
772            .metadata;
773
774        assert_eq!(
775            IcebergSplitEnumerator::get_snapshot_id_from_metadata(
776                &metadata,
777                Some(IcebergTimeTravelInfo::TimestampMs(3_500)),
778            )
779            .unwrap(),
780            Some(2)
781        );
782        assert_eq!(
783            IcebergSplitEnumerator::get_snapshot_id_from_metadata(
784                &metadata,
785                Some(IcebergTimeTravelInfo::TimestampMs(1_500)),
786            )
787            .unwrap(),
788            Some(1)
789        );
790    }
791
792    #[test]
793    fn test_get_snapshot_id_version_without_current_snapshot() {
794        let metadata = test_table_metadata_builder()
795            .add_snapshot(test_snapshot(7, None, 1_000))
796            .unwrap()
797            .build()
798            .unwrap()
799            .metadata;
800
801        assert_eq!(metadata.current_snapshot_id(), None);
802        assert_eq!(
803            IcebergSplitEnumerator::get_snapshot_id_from_metadata(
804                &metadata,
805                Some(IcebergTimeTravelInfo::Version(7)),
806            )
807            .unwrap(),
808            Some(7)
809        );
810        assert_eq!(
811            IcebergSplitEnumerator::get_snapshot_id_from_metadata(&metadata, None).unwrap(),
812            None
813        );
814    }
815
816    fn create_file_scan_task(length: u64, id: u64) -> FileScanTask {
817        FileScanTask {
818            length,
819            start: 0,
820            record_count: Some(0),
821            first_row_id: None,
822            data_sequence_number: None,
823            data_file_path: format!("test_{}.parquet", id),
824            data_file_format: iceberg::spec::DataFileFormat::Parquet,
825            schema: Arc::new(Schema::builder().build().unwrap()),
826            project_field_ids: vec![],
827            predicate: None,
828            deletes: vec![],
829            sequence_number: 0,
830            file_sequence_number: Some(0),
831            file_size_in_bytes: 0,
832            partition: None,
833            partition_spec: None,
834            name_mapping: None,
835            unified_partition_type: None,
836            case_sensitive: true,
837            key_metadata: None,
838        }
839    }
840
841    #[test]
842    fn test_split_serialization_strips_iceberg_planning_context() {
843        let mut task = create_file_scan_task(100, 1);
844        task.partition = Some(Struct::empty());
845        task.partition_spec = Some(Arc::new(iceberg::spec::PartitionSpec::unpartition_spec()));
846
847        let split = IcebergSplit {
848            split_id: 1,
849            task: IcebergFileScanTask::Data(vec![task]),
850            limit: None,
851        };
852        let restored = IcebergSplit::restore_from_json(split.encode_to_json()).unwrap();
853        let task = &restored.task.tasks()[0];
854
855        assert!(task.partition.is_none());
856        assert!(task.partition_spec.is_none());
857        assert!(task.name_mapping.is_none());
858        assert!(task.unified_partition_type.is_none());
859    }
860
861    #[test]
862    fn test_split_n_vecs_basic() {
863        let file_scan_tasks = (1..=12)
864            .map(|i| create_file_scan_task(i + 100, i))
865            .collect::<Vec<_>>(); // Ensure the correct function is called
866
867        let groups = IcebergSplitEnumerator::split_n_vecs(file_scan_tasks, 3);
868
869        assert_eq!(groups.len(), 3);
870
871        let group_lengths: Vec<u64> = groups
872            .iter()
873            .map(|group| group.iter().map(|task| task.length).sum())
874            .collect();
875
876        let max_length = *group_lengths.iter().max().unwrap();
877        let min_length = *group_lengths.iter().min().unwrap();
878        assert!(max_length - min_length <= 10, "Groups should be balanced");
879
880        let total_tasks: usize = groups.iter().map(|group| group.len()).sum();
881        assert_eq!(total_tasks, 12);
882    }
883
884    #[test]
885    fn test_split_n_vecs_empty() {
886        let file_scan_tasks = Vec::new();
887        let groups = IcebergSplitEnumerator::split_n_vecs(file_scan_tasks, 3);
888        assert_eq!(groups.len(), 3);
889        assert!(groups.iter().all(|group| group.is_empty()));
890    }
891
892    #[test]
893    fn test_split_n_vecs_single_task() {
894        let file_scan_tasks = vec![create_file_scan_task(100, 1)];
895        let groups = IcebergSplitEnumerator::split_n_vecs(file_scan_tasks, 3);
896        assert_eq!(groups.len(), 3);
897        assert_eq!(groups.iter().filter(|group| !group.is_empty()).count(), 1);
898    }
899
900    #[test]
901    fn test_split_n_vecs_uneven_distribution() {
902        let file_scan_tasks = vec![
903            create_file_scan_task(1000, 1),
904            create_file_scan_task(100, 2),
905            create_file_scan_task(100, 3),
906            create_file_scan_task(100, 4),
907            create_file_scan_task(100, 5),
908        ];
909
910        let groups = IcebergSplitEnumerator::split_n_vecs(file_scan_tasks, 2);
911        assert_eq!(groups.len(), 2);
912
913        let group_with_large_task = groups
914            .iter()
915            .find(|group| group.iter().any(|task| task.length == 1000))
916            .unwrap();
917        assert_eq!(group_with_large_task.len(), 1);
918    }
919
920    #[test]
921    fn test_split_n_vecs_same_files_distribution() {
922        let file_scan_tasks = vec![
923            create_file_scan_task(100, 1),
924            create_file_scan_task(100, 2),
925            create_file_scan_task(100, 3),
926            create_file_scan_task(100, 4),
927            create_file_scan_task(100, 5),
928            create_file_scan_task(100, 6),
929            create_file_scan_task(100, 7),
930            create_file_scan_task(100, 8),
931        ];
932
933        let groups = IcebergSplitEnumerator::split_n_vecs(file_scan_tasks.clone(), 4)
934            .iter()
935            .map(|g| {
936                g.iter()
937                    .map(|task| task.data_file_path.clone())
938                    .collect::<Vec<_>>()
939            })
940            .collect::<Vec<_>>();
941
942        for _ in 0..10000 {
943            let groups_2 = IcebergSplitEnumerator::split_n_vecs(file_scan_tasks.clone(), 4)
944                .iter()
945                .map(|g| {
946                    g.iter()
947                        .map(|task| task.data_file_path.clone())
948                        .collect::<Vec<_>>()
949                })
950                .collect::<Vec<_>>();
951
952            assert_eq!(groups, groups_2);
953        }
954    }
955}