Skip to main content

risingwave_connector/source/iceberg/
planner.rs

1// Copyright 2026 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
15use std::cmp::{Ordering, Reverse};
16use std::collections::BinaryHeap;
17use std::time::{Duration, Instant};
18
19use anyhow::Context;
20use futures::StreamExt;
21use futures::stream::BoxStream;
22use futures_async_stream::try_stream;
23use iceberg::expr::BoundPredicate;
24use iceberg::scan::{FileScanTask, FileScanTaskDeleteFile};
25use iceberg::spec::{DataContentType, DataFileFormat, SchemaRef};
26use iceberg::table::Table;
27use risingwave_common::bail;
28use risingwave_common::catalog::ColumnCatalog;
29use risingwave_common::metrics::{LabelGuardedHistogram, LabelGuardedIntCounter};
30use risingwave_common::types::{JsonbRef, JsonbVal, ScalarRef};
31use risingwave_pb::batch_plan::iceberg_scan_node::IcebergScanType;
32use risingwave_pb::plan_common::IcebergBoundedScan as PbIcebergBoundedScan;
33use risingwave_pb::plan_common::iceberg_bounded_scan::{Scan, Snapshot as PbSnapshot};
34use serde::{Deserialize, Serialize};
35
36use super::metrics::GLOBAL_ICEBERG_SCAN_METRICS;
37use super::{IcebergFileScanTask, IcebergProperties, IcebergScanOpts, IcebergSplit};
38use crate::error::ConnectorResult;
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum IcebergScanTaskBatchMode {
42    /// Keep the requested parallelism by returning empty task batches when there are fewer files
43    /// than workers. This is used by the distributed RisingWave batch scheduler.
44    PreserveParallelism,
45    /// Avoid empty partitions. This is used by DataFusion's local physical plan.
46    Compact,
47}
48
49pub struct IcebergScanTaskPlanner;
50
51pub type IcebergScanTaskStream = BoxStream<'static, ConnectorResult<FileScanTask>>;
52
53#[derive(Debug, Clone, Default)]
54pub struct IcebergScanProjection {
55    columns: Option<Vec<String>>,
56}
57
58impl IcebergScanProjection {
59    pub fn all() -> Self {
60        Self { columns: None }
61    }
62
63    pub fn from_downstream_columns(columns: Option<&[ColumnCatalog]>) -> Self {
64        Self {
65            columns: columns.map(|columns| {
66                columns
67                    .iter()
68                    .filter_map(|col| {
69                        if col.is_hidden() {
70                            None
71                        } else {
72                            Some(col.name().to_owned())
73                        }
74                    })
75                    .collect()
76            }),
77        }
78    }
79
80    fn apply<'a>(
81        &self,
82        scan_builder: iceberg::scan::TableScanBuilder<'a>,
83    ) -> iceberg::scan::TableScanBuilder<'a> {
84        if let Some(columns) = &self.columns {
85            scan_builder.select(columns)
86        } else {
87            scan_builder.select_all()
88        }
89    }
90}
91
92#[derive(Debug, Clone)]
93pub struct IcebergScanMetricsLabels {
94    source_id: String,
95    source_name: String,
96    table_name: String,
97    snapshots_discovered_total: LabelGuardedIntCounter,
98    list_duration_seconds: LabelGuardedHistogram,
99    delete_files_per_data_file: LabelGuardedHistogram,
100    data_files_discovered_total: LabelGuardedIntCounter,
101    equality_delete_files_discovered_total: LabelGuardedIntCounter,
102    position_delete_files_discovered_total: LabelGuardedIntCounter,
103    list_errors_total: LabelGuardedIntCounter,
104    fetch_errors_total: LabelGuardedIntCounter,
105}
106
107impl IcebergScanMetricsLabels {
108    pub fn new(source_id: String, source_name: String, table_name: String) -> Self {
109        let labels = [
110            source_id.as_str(),
111            source_name.as_str(),
112            table_name.as_str(),
113        ];
114        Self {
115            snapshots_discovered_total: GLOBAL_ICEBERG_SCAN_METRICS
116                .iceberg_source_snapshots_discovered_total
117                .with_guarded_label_values(&labels),
118            list_duration_seconds: GLOBAL_ICEBERG_SCAN_METRICS
119                .iceberg_source_list_duration_seconds
120                .with_guarded_label_values(&labels),
121            delete_files_per_data_file: GLOBAL_ICEBERG_SCAN_METRICS
122                .iceberg_source_delete_files_per_data_file
123                .with_guarded_label_values(&labels),
124            data_files_discovered_total: GLOBAL_ICEBERG_SCAN_METRICS
125                .iceberg_source_files_discovered_total
126                .with_guarded_label_values(&[labels[0], labels[1], labels[2], "data"]),
127            equality_delete_files_discovered_total: GLOBAL_ICEBERG_SCAN_METRICS
128                .iceberg_source_files_discovered_total
129                .with_guarded_label_values(&[labels[0], labels[1], labels[2], "eq_delete"]),
130            position_delete_files_discovered_total: GLOBAL_ICEBERG_SCAN_METRICS
131                .iceberg_source_files_discovered_total
132                .with_guarded_label_values(&[labels[0], labels[1], labels[2], "pos_delete"]),
133            list_errors_total: GLOBAL_ICEBERG_SCAN_METRICS
134                .iceberg_source_scan_errors_total
135                .with_guarded_label_values(&[labels[0], labels[1], labels[2], "list_error"]),
136            fetch_errors_total: GLOBAL_ICEBERG_SCAN_METRICS
137                .iceberg_source_scan_errors_total
138                .with_guarded_label_values(&[labels[0], labels[1], labels[2], "fetch_error"]),
139            source_id,
140            source_name,
141            table_name,
142        }
143    }
144
145    pub fn record_scan_error(&self, error_kind: &str) {
146        match error_kind {
147            "list_error" => self.list_errors_total.inc(),
148            "fetch_error" => self.fetch_errors_total.inc(),
149            _ => tracing::warn!(error_kind, "unknown Iceberg scan error metric label"),
150        }
151    }
152
153    pub fn record_snapshot_discovered(&self) {
154        self.snapshots_discovered_total.inc();
155    }
156
157    pub fn record_snapshot_lag(&self, lag_secs: i64) {
158        GLOBAL_ICEBERG_SCAN_METRICS
159            .iceberg_source_snapshot_lag_seconds
160            .with_guarded_label_values(&[
161                self.source_id.as_str(),
162                self.source_name.as_str(),
163                self.table_name.as_str(),
164            ])
165            .set(lag_secs);
166    }
167
168    pub fn record_caught_up(&self) {
169        self.record_snapshot_lag(0);
170    }
171
172    fn record_list_duration(&self, duration: Duration) {
173        self.list_duration_seconds.observe(duration.as_secs_f64());
174    }
175
176    fn record_delete_files_per_data_file(&self, delete_file_count: usize) {
177        self.delete_files_per_data_file
178            .observe(delete_file_count as f64);
179    }
180
181    fn record_file_counts(&self, stats: &IcebergScanPlanStats) {
182        for (metric, count) in [
183            (&self.data_files_discovered_total, stats.data_file_count),
184            (
185                &self.equality_delete_files_discovered_total,
186                stats.eq_delete_count,
187            ),
188            (
189                &self.position_delete_files_discovered_total,
190                stats.pos_delete_count,
191            ),
192        ] {
193            if count > 0 {
194                metric.inc_by(count);
195            }
196        }
197    }
198
199    pub fn record_fetch_error(&self) {
200        self.fetch_errors_total.inc();
201    }
202
203    pub fn set_inflight_file_count(&self, count: usize) {
204        GLOBAL_ICEBERG_SCAN_METRICS
205            .iceberg_source_inflight_file_count
206            .with_guarded_label_values(&[
207                self.source_id.as_str(),
208                self.source_name.as_str(),
209                self.table_name.as_str(),
210            ])
211            .set(count as i64);
212    }
213}
214
215#[derive(Debug, Default)]
216struct IcebergScanPlanStats {
217    data_file_count: u64,
218    eq_delete_count: u64,
219    pos_delete_count: u64,
220}
221
222impl IcebergScanPlanStats {
223    fn record_task(&mut self, scan_task: &FileScanTask) {
224        self.data_file_count += 1;
225        for delete_task in &scan_task.deletes {
226            match delete_task.file_type {
227                DataContentType::EqualityDeletes => self.eq_delete_count += 1,
228                DataContentType::PositionDeletes => self.pos_delete_count += 1,
229                _ => {}
230            }
231        }
232    }
233}
234
235pub struct IcebergScanPlan {
236    pub snapshot_id: i64,
237    pub tasks: IcebergScanTaskStream,
238}
239
240pub enum IcebergIncrementalScan {
241    EmptyTable,
242    UpToDate { current_snapshot_id: i64 },
243    Planned(IcebergScanPlan),
244}
245
246#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
247pub enum IcebergBoundedScan {
248    Snapshot { snapshot_id: i64 },
249}
250
251impl IcebergBoundedScan {
252    pub fn from_proto(scan: PbIcebergBoundedScan) -> ConnectorResult<Self> {
253        match scan.scan {
254            Some(Scan::Snapshot(snapshot)) => Ok(Self::Snapshot {
255                snapshot_id: snapshot.snapshot_id,
256            }),
257            None => bail!("bounded Iceberg scan requires a resolved input boundary"),
258        }
259    }
260
261    pub fn to_proto(self) -> PbIcebergBoundedScan {
262        match self {
263            Self::Snapshot { snapshot_id } => PbIcebergBoundedScan {
264                scan: Some(Scan::Snapshot(PbSnapshot { snapshot_id })),
265            },
266        }
267    }
268}
269
270#[derive(Clone)]
271pub struct IcebergScanPlanner {
272    properties: IcebergProperties,
273    projection: IcebergScanProjection,
274    metrics: Option<IcebergScanMetricsLabels>,
275}
276
277impl IcebergScanPlanner {
278    pub fn new(
279        properties: IcebergProperties,
280        projection: IcebergScanProjection,
281        metrics: Option<IcebergScanMetricsLabels>,
282    ) -> Self {
283        Self {
284            properties,
285            projection,
286            metrics,
287        }
288    }
289
290    pub async fn plan_current_snapshot(&self) -> ConnectorResult<Option<IcebergScanPlan>> {
291        let table = self.properties.load_table().await?;
292        let Some(current_snapshot) = table.metadata().current_snapshot() else {
293            return Ok(None);
294        };
295        self.plan_snapshot(&table, current_snapshot.snapshot_id())
296            .await
297            .map(Some)
298    }
299
300    pub async fn plan_incremental(
301        &self,
302        last_snapshot: Option<i64>,
303    ) -> ConnectorResult<IcebergIncrementalScan> {
304        let table = self.properties.load_table().await?;
305
306        let Some(current_snapshot) = table.metadata().current_snapshot() else {
307            tracing::info!("Skip incremental scan because table is empty");
308            return Ok(IcebergIncrementalScan::EmptyTable);
309        };
310
311        let current_snapshot_id = current_snapshot.snapshot_id();
312        if Some(current_snapshot_id) == last_snapshot {
313            if let Some(metrics) = &self.metrics {
314                metrics.record_caught_up();
315            }
316            tracing::info!(
317                "Current table snapshot is already enumerated: {}, no new snapshot available",
318                current_snapshot_id
319            );
320            return Ok(IcebergIncrementalScan::UpToDate {
321                current_snapshot_id,
322            });
323        }
324
325        if let Some(metrics) = &self.metrics {
326            if let Some(last_snapshot_id) = last_snapshot
327                && let Some(last_ingested_snapshot) = table
328                    .metadata()
329                    .snapshots()
330                    .find(|snapshot| snapshot.snapshot_id() == last_snapshot_id)
331            {
332                let lag_secs = (current_snapshot.timestamp_ms()
333                    - last_ingested_snapshot.timestamp_ms())
334                .max(0)
335                    / 1000;
336                metrics.record_snapshot_lag(lag_secs);
337            }
338            metrics.record_snapshot_discovered();
339        }
340
341        let mut scan_builder = table.scan().to_snapshot_id(current_snapshot_id);
342        if let Some(last_snapshot) = last_snapshot {
343            scan_builder = scan_builder.from_snapshot_id(last_snapshot);
344        }
345        let scan = self.projection.apply(scan_builder).build()?;
346        let tasks = self.instrument_scan_task_stream(scan.plan_files().await?);
347
348        Ok(IcebergIncrementalScan::Planned(IcebergScanPlan {
349            snapshot_id: current_snapshot_id,
350            tasks,
351        }))
352    }
353
354    pub fn record_caught_up(&self) {
355        if let Some(metrics) = &self.metrics {
356            metrics.record_caught_up();
357        }
358    }
359
360    async fn plan_snapshot(
361        &self,
362        table: &Table,
363        snapshot_id: i64,
364    ) -> ConnectorResult<IcebergScanPlan> {
365        let scan = self
366            .projection
367            .apply(table.scan().snapshot_id(snapshot_id))
368            .build()?;
369        let tasks = self.instrument_scan_task_stream(scan.plan_files().await?);
370
371        Ok(IcebergScanPlan { snapshot_id, tasks })
372    }
373
374    fn instrument_scan_task_stream(
375        &self,
376        scan_tasks: iceberg::scan::FileScanTaskStream,
377    ) -> IcebergScanTaskStream {
378        instrument_scan_task_stream(scan_tasks, self.metrics.clone())
379    }
380}
381
382#[try_stream(boxed, ok = FileScanTask, error = crate::error::ConnectorError)]
383async fn instrument_scan_task_stream(
384    scan_tasks: iceberg::scan::FileScanTaskStream,
385    metrics: Option<IcebergScanMetricsLabels>,
386) {
387    let mut list_duration = Duration::default();
388    let mut active_since = Instant::now();
389    let mut stats = IcebergScanPlanStats::default();
390
391    let mut scan_tasks = scan_tasks;
392    while let Some(scan_task) = scan_tasks.next().await {
393        let scan_task = scan_task?;
394        if let Some(metrics) = &metrics {
395            stats.record_task(&scan_task);
396            metrics.record_delete_files_per_data_file(scan_task.deletes.len());
397        }
398        list_duration += active_since.elapsed();
399        yield scan_task;
400        active_since = Instant::now();
401    }
402    list_duration += active_since.elapsed();
403
404    if let Some(metrics) = &metrics {
405        metrics.record_list_duration(list_duration);
406        metrics.record_file_counts(&stats);
407    }
408}
409
410#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
411pub struct PersistedFileScanTask {
412    pub start: u64,
413    pub length: u64,
414    pub record_count: Option<u64>,
415    #[serde(default, skip_serializing_if = "Option::is_none")]
416    pub first_row_id: Option<i64>,
417    #[serde(default, skip_serializing_if = "Option::is_none")]
418    pub data_sequence_number: Option<i64>,
419    pub data_file_path: String,
420    #[serde(default, skip_serializing_if = "Option::is_none")]
421    pub referenced_data_file: Option<String>,
422    pub data_file_content: DataContentType,
423    pub data_file_format: DataFileFormat,
424    pub schema: SchemaRef,
425    pub project_field_ids: Vec<i32>,
426    #[serde(skip_serializing_if = "Option::is_none")]
427    pub predicate: Option<BoundPredicate>,
428    pub deletes: Vec<PersistedFileScanTask>,
429    #[serde(default)]
430    pub sequence_number: i64,
431    #[serde(default)]
432    pub equality_ids: Option<Vec<i32>>,
433    #[serde(default, skip_serializing_if = "is_zero")]
434    pub partition_spec_id: i32,
435    pub file_size_in_bytes: u64,
436    #[serde(default = "default_case_sensitive")]
437    pub case_sensitive: bool,
438}
439
440fn default_case_sensitive() -> bool {
441    true
442}
443
444fn is_zero(value: &i32) -> bool {
445    *value == 0
446}
447
448impl PersistedFileScanTask {
449    pub fn decode(jsonb_ref: JsonbRef<'_>) -> ConnectorResult<FileScanTask> {
450        let json = jsonb_ref.to_owned_scalar().take();
451        let persisted_task: Self = serde_json::from_value(json.clone()).with_context(|| {
452            format!("failed to decode persisted iceberg file scan task from json `{json}`")
453        })?;
454        Ok(Self::to_task(persisted_task))
455    }
456
457    pub fn encode(task: FileScanTask) -> ConnectorResult<JsonbVal> {
458        let persisted_task = Self::from_task(task);
459        Ok(serde_json::to_value(persisted_task)?.into())
460    }
461
462    fn to_task(
463        Self {
464            start,
465            length,
466            record_count,
467            first_row_id,
468            data_sequence_number,
469            data_file_path,
470            referenced_data_file: _,
471            data_file_content: _,
472            data_file_format,
473            schema,
474            project_field_ids,
475            predicate,
476            deletes,
477            sequence_number,
478            equality_ids: _,
479            partition_spec_id: _,
480            file_size_in_bytes,
481            case_sensitive,
482        }: Self,
483    ) -> FileScanTask {
484        FileScanTask {
485            start,
486            length,
487            record_count,
488            first_row_id,
489            data_sequence_number,
490            data_file_path,
491            data_file_format,
492            schema,
493            project_field_ids,
494            predicate,
495            deletes: deletes
496                .into_iter()
497                .map(PersistedFileScanTask::into_delete_task)
498                .collect(),
499            sequence_number,
500            file_size_in_bytes,
501            partition: None,
502            partition_spec: None,
503            name_mapping: None,
504            unified_partition_type: None,
505            case_sensitive,
506            key_metadata: None,
507            file_sequence_number: None,
508        }
509    }
510
511    fn from_task(
512        FileScanTask {
513            start,
514            length,
515            record_count,
516            first_row_id,
517            data_sequence_number,
518            data_file_path,
519            data_file_format,
520            schema,
521            project_field_ids,
522            predicate,
523            deletes,
524            sequence_number,
525            file_sequence_number: _,
526            file_size_in_bytes,
527            case_sensitive,
528            ..
529        }: FileScanTask,
530    ) -> Self {
531        let persisted_deletes = deletes
532            .into_iter()
533            .map(|task| {
534                PersistedFileScanTask::from_delete_task(
535                    task,
536                    schema.clone(),
537                    project_field_ids.clone(),
538                    case_sensitive,
539                )
540            })
541            .collect();
542        Self {
543            start,
544            length,
545            record_count,
546            first_row_id,
547            data_sequence_number,
548            data_file_path,
549            referenced_data_file: None,
550            data_file_content: DataContentType::Data,
551            data_file_format,
552            schema,
553            project_field_ids,
554            predicate,
555            deletes: persisted_deletes,
556            sequence_number,
557            equality_ids: None,
558            partition_spec_id: 0,
559            file_size_in_bytes,
560            case_sensitive,
561        }
562    }
563
564    fn into_delete_task(self) -> FileScanTaskDeleteFile {
565        let Self {
566            start,
567            length,
568            record_count,
569            data_file_path,
570            referenced_data_file,
571            data_file_content,
572            data_file_format,
573            equality_ids,
574            sequence_number,
575            partition_spec_id,
576            file_size_in_bytes,
577            ..
578        } = self;
579        let (content_offset, content_size_in_bytes) = if data_file_format == DataFileFormat::Puffin
580        {
581            (i64::try_from(start).ok(), i64::try_from(length).ok())
582        } else {
583            (None, None)
584        };
585
586        FileScanTaskDeleteFile {
587            file_path: data_file_path,
588            file_size_in_bytes,
589            file_type: data_file_content,
590            partition_spec_id,
591            equality_ids,
592            file_format: data_file_format,
593            referenced_data_file,
594            content_offset,
595            content_size_in_bytes,
596            record_count,
597            sequence_number,
598            // Persisted split state deliberately excludes plaintext encryption key material.
599            key_metadata: None,
600        }
601    }
602
603    fn from_delete_task(
604        task: FileScanTaskDeleteFile,
605        schema: SchemaRef,
606        project_field_ids: Vec<i32>,
607        case_sensitive: bool,
608    ) -> Self {
609        let (start, length) = if task.file_format == DataFileFormat::Puffin {
610            (
611                task.content_offset.unwrap_or_default().max(0) as u64,
612                task.content_size_in_bytes.unwrap_or_default().max(0) as u64,
613            )
614        } else {
615            (0, task.file_size_in_bytes)
616        };
617
618        Self {
619            start,
620            length,
621            record_count: task.record_count,
622            first_row_id: None,
623            data_sequence_number: None,
624            data_file_path: task.file_path,
625            referenced_data_file: task.referenced_data_file,
626            data_file_content: task.file_type,
627            data_file_format: task.file_format,
628            schema,
629            project_field_ids,
630            predicate: None,
631            deletes: Vec::new(),
632            sequence_number: task.sequence_number,
633            equality_ids: task.equality_ids,
634            partition_spec_id: task.partition_spec_id,
635            file_size_in_bytes: task.file_size_in_bytes,
636            case_sensitive,
637        }
638    }
639}
640
641impl IcebergFileScanTask {
642    pub fn scan_type(&self) -> IcebergScanType {
643        match self {
644            IcebergFileScanTask::Data(_) => IcebergScanType::DataScan,
645            IcebergFileScanTask::EqualityDelete(_) => IcebergScanType::EqualityDeleteScan,
646            IcebergFileScanTask::PositionDelete(_) => IcebergScanType::PositionDeleteScan,
647        }
648    }
649
650    pub fn from_tasks(
651        scan_type: IcebergScanType,
652        tasks: Vec<FileScanTask>,
653    ) -> ConnectorResult<Self> {
654        match scan_type {
655            IcebergScanType::DataScan => Ok(IcebergFileScanTask::Data(tasks)),
656            IcebergScanType::EqualityDeleteScan => Ok(IcebergFileScanTask::EqualityDelete(tasks)),
657            IcebergScanType::PositionDeleteScan => Ok(IcebergFileScanTask::PositionDelete(tasks)),
658            _ => {
659                bail!("unsupported Iceberg file scan task type: {:?}", scan_type)
660            }
661        }
662    }
663
664    pub fn into_tasks(self) -> Vec<FileScanTask> {
665        match self {
666            IcebergFileScanTask::Data(tasks)
667            | IcebergFileScanTask::EqualityDelete(tasks)
668            | IcebergFileScanTask::PositionDelete(tasks) => tasks,
669        }
670    }
671}
672
673impl IcebergScanOpts {
674    pub fn new(
675        chunk_size: usize,
676        need_seq_num: bool,
677        need_file_path_and_pos: bool,
678        handle_delete_files: bool,
679    ) -> Self {
680        Self {
681            chunk_size,
682            need_seq_num,
683            need_file_path_and_pos,
684            handle_delete_files,
685        }
686    }
687}
688
689impl IcebergScanTaskPlanner {
690    pub fn plan_splits(
691        task: IcebergFileScanTask,
692        split_num: usize,
693        limit: Option<u64>,
694    ) -> ConnectorResult<Vec<IcebergSplit>> {
695        let scan_type = task.scan_type();
696        if limit.is_some() && scan_type != IcebergScanType::DataScan {
697            bail!("Iceberg scan limit can only be planned for data scan tasks");
698        }
699
700        let task_batches = Self::plan_task_batches(
701            task,
702            split_num,
703            limit,
704            IcebergScanTaskBatchMode::PreserveParallelism,
705        );
706
707        task_batches
708            .into_iter()
709            .enumerate()
710            .map(|(id, tasks)| {
711                Ok(IcebergSplit {
712                    split_id: id.try_into().unwrap(),
713                    task: IcebergFileScanTask::from_tasks(scan_type, tasks)?,
714                    limit,
715                })
716            })
717            .collect()
718    }
719
720    pub fn plan_task_batches(
721        task: IcebergFileScanTask,
722        split_num: usize,
723        limit: Option<u64>,
724        mode: IcebergScanTaskBatchMode,
725    ) -> Vec<Vec<FileScanTask>> {
726        let tasks = task.into_tasks();
727        if limit.is_some() {
728            return vec![tasks];
729        }
730        Self::plan_file_task_batches(tasks, split_num, mode)
731    }
732
733    pub fn plan_file_task_batches(
734        file_scan_tasks: Vec<FileScanTask>,
735        split_num: usize,
736        mode: IcebergScanTaskBatchMode,
737    ) -> Vec<Vec<FileScanTask>> {
738        assert!(split_num > 0, "iceberg scan split number must be positive");
739        if mode == IcebergScanTaskBatchMode::Compact && file_scan_tasks.len() <= split_num {
740            return file_scan_tasks.into_iter().map(|task| vec![task]).collect();
741        }
742
743        Self::split_n_vecs(file_scan_tasks, split_num)
744    }
745
746    /// Uniformly distribute scan tasks to compute nodes.
747    /// It's deterministic so that it can best utilize the data locality.
748    ///
749    /// # Arguments
750    /// * `file_scan_tasks`: The file scan tasks to be split.
751    /// * `split_num`: The number of splits to be created.
752    ///
753    /// 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.
754    /// Ensure that the total length of each group is as balanced as possible.
755    /// The time complexity is O(n log k), where n is the number of file scan tasks and k is the number of splits.
756    /// The space complexity is O(k), where k is the number of splits.
757    /// The algorithm is stable, so the order of the file scan tasks will be preserved.
758    pub fn split_n_vecs(
759        file_scan_tasks: Vec<FileScanTask>,
760        split_num: usize,
761    ) -> Vec<Vec<FileScanTask>> {
762        #[derive(Default)]
763        struct FileScanTaskGroup {
764            idx: usize,
765            tasks: Vec<FileScanTask>,
766            total_length: u64,
767        }
768
769        impl Ord for FileScanTaskGroup {
770            fn cmp(&self, other: &Self) -> Ordering {
771                // when total_length is the same, we will sort by index
772                if self.total_length == other.total_length {
773                    self.idx.cmp(&other.idx)
774                } else {
775                    self.total_length.cmp(&other.total_length)
776                }
777            }
778        }
779
780        impl PartialOrd for FileScanTaskGroup {
781            fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
782                Some(self.cmp(other))
783            }
784        }
785
786        impl Eq for FileScanTaskGroup {}
787
788        impl PartialEq for FileScanTaskGroup {
789            fn eq(&self, other: &Self) -> bool {
790                self.total_length == other.total_length && self.idx == other.idx
791            }
792        }
793
794        let mut heap = BinaryHeap::new();
795        // push all groups into heap
796        for idx in 0..split_num {
797            heap.push(Reverse(FileScanTaskGroup {
798                idx,
799                tasks: vec![],
800                total_length: 0,
801            }));
802        }
803
804        for file_task in file_scan_tasks {
805            let mut group = heap.peek_mut().unwrap();
806            group.0.total_length += file_task.length;
807            group.0.tasks.push(file_task);
808        }
809
810        // convert heap into vec and extract tasks
811        heap.into_vec()
812            .into_iter()
813            .map(|reverse_group| reverse_group.0.tasks)
814            .collect()
815    }
816}