Skip to main content

risingwave_stream/executor/iceberg_with_pk_index/
compaction_resolver.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::time::Instant;
16
17use anyhow::{Context, anyhow};
18use futures::TryStreamExt;
19use hashbrown::{Equivalent, HashMap, HashSet};
20use iceberg::delete_vector::DeleteVector;
21use iceberg::io::{FileIO, FileMetadata};
22use iceberg::spec::{DataContentType, DataFile, ManifestContentType, SnapshotRef};
23use iceberg::table::Table;
24use iceberg::writer::file_writer::location_generator::DefaultLocationGenerator;
25use parquet::arrow::arrow_reader::ArrowReaderMetadata;
26use parquet::arrow::{ParquetRecordBatchStreamBuilder, ProjectionMask};
27use parquet::schema::types::SchemaDescriptor;
28use risingwave_common::array::arrow::IcebergArrowConvert;
29use risingwave_common::array::{ArrayImpl, BytesArray, DataChunk, I64Array, Utf8Array};
30use risingwave_common::bitmap::Bitmap;
31use risingwave_common::id::SinkId;
32use risingwave_common::util::iter_util::ZipEqFast;
33use risingwave_connector::sink::SinkError;
34use risingwave_connector::sink::iceberg::{
35    IcebergConfig, IcebergPositionDeleteCommitResult, PkIndexDataFileLocator,
36    PositionDeleteFileNameGenerators, read_position_deletes_from_file,
37    serialize_data_files_default_spec, write_position_delete_file,
38};
39use risingwave_connector::source::iceberg::ParquetFileReader;
40use risingwave_expr::expr::{
41    BoxedExpression, InputRefExpression, SyncExpressionBoxExt, build_func,
42};
43use risingwave_pb::connector_service::SinkMetadata;
44use risingwave_pb::expr::expr_node::PbType;
45use risingwave_pb::id::IcebergCompactionTaskId;
46use risingwave_pb::stream_plan::iceberg_pk_index_compaction_context::{Phase, ResolverTaskInput};
47use risingwave_pb::stream_service::PbIcebergPkIndexSinkRole;
48use risingwave_rpc_client::MetaClient;
49use tokio::sync::mpsc::UnboundedReceiver;
50use tokio::sync::{Semaphore, mpsc};
51use tokio::task::JoinHandle;
52use uuid::Uuid;
53
54use super::load_table_at_least;
55use crate::executor::prelude::*;
56use crate::task::LocalBarrierManager;
57
58/// Concurrent manifest loads when collecting the delete files of a snapshot.
59const MANIFEST_LOAD_CONCURRENCY: usize = 16;
60/// Concurrent input files whose delete diff is read and re-scanned.
61const DELETE_DIFF_CONCURRENCY: usize = 16;
62/// Concurrent output data files whose parquet footers are loaded to plan the scan.
63const OUTPUT_FILE_OPEN_CONCURRENCY: usize = 16;
64/// Concurrent row-group scans of the output data files while rebuilding the pk index.
65const OUTPUT_SCAN_CONCURRENCY: usize = 8;
66const OUTPUT_SCAN_CHANNEL_CAPACITY: usize = 16;
67
68/// Leaf executor for the iceberg pk-index coordinated compaction.
69///
70/// It has **no stream input**. The actor is part of the sink's static graph but only runs while a
71/// compaction is being applied. It is driven by barriers delivered directly through
72/// `barrier_receiver` and produces resolved survivor rows for the downstream writer.
73///
74/// Lifecycle:
75/// - On the first barrier: forward it (no state to init).
76/// - After resolve completes, on the next barrier (the end barrier): REPORT the conflict DV
77///   files to meta, forward the barrier, and exit.
78///
79/// # Output chunk contract
80///
81/// Schema: `[pk_columns.., data_file, position: Int64]`, where `data_file` is the output file
82/// path (Varchar) in the legacy layout, or its uuid (Bytea) otherwise, matching the writer's PK
83/// index. Every emitted row is a SURVIVOR: `Writer` upserts `pk -> (data_file, position)` in the
84/// index (index-only; the data already lives in the compaction output file). Conflicts (rows
85/// killed during the window) are NOT emitted here.
86pub struct CompactionResolverExecutor {
87    ctx: ActorContextRef,
88    sink_id: SinkId,
89    iceberg_config: IcebergConfig,
90    pk_indices: Vec<usize>,
91    pk_data_types: Vec<DataType>,
92    chunk_size: usize,
93    local_barrier_manager: LocalBarrierManager,
94    barrier_receiver: UnboundedReceiver<Barrier>,
95    meta_client: MetaClient,
96}
97
98fn resolver_task_from_initial_barrier(
99    sink_id: SinkId,
100    barrier: &Barrier,
101) -> StreamExecutorResult<(IcebergCompactionTaskId, ResolverTaskInput)> {
102    match barrier.iceberg_pk_index_compaction() {
103        Some(context)
104            if barrier.is_checkpoint()
105                && context.sink_id == sink_id
106                && context.phase == Phase::Begin as i32 =>
107        {
108            let task_input = context.resolver_task_input.clone().ok_or_else(|| {
109                StreamExecutorError::from(anyhow!(
110                    "compaction resolver sink {} task {} missing resolver task input",
111                    sink_id,
112                    context.task_id
113                ))
114            })?;
115            Ok((context.task_id, task_input))
116        }
117        _ => Err(StreamExecutorError::from(anyhow!(
118            "compaction resolver sink {} expected initial begin barrier, got {:?}",
119            sink_id,
120            barrier
121        ))),
122    }
123}
124
125fn validate_resolver_end_barrier(
126    sink_id: SinkId,
127    barrier: &Barrier,
128    begin: &Barrier,
129    task_id: IcebergCompactionTaskId,
130) -> StreamExecutorResult<()> {
131    match barrier.iceberg_pk_index_compaction() {
132        Some(context)
133            if barrier.is_checkpoint()
134                && barrier.epoch.prev == begin.epoch.curr
135                && context.sink_id == sink_id
136                && context.task_id == task_id
137                && context.phase == Phase::End as i32
138                && context.resolver_task_input.is_none() =>
139        {
140            Ok(())
141        }
142        _ => Err(StreamExecutorError::from(anyhow!(
143            "compaction resolver sink {} task {} expected end barrier, got {:?}",
144            sink_id,
145            task_id,
146            barrier
147        ))),
148    }
149}
150
151impl CompactionResolverExecutor {
152    #[expect(clippy::too_many_arguments)]
153    pub fn new(
154        ctx: ActorContextRef,
155        sink_id: SinkId,
156        iceberg_config: IcebergConfig,
157        pk_indices: Vec<usize>,
158        pk_data_types: Vec<DataType>,
159        chunk_size: usize,
160        local_barrier_manager: LocalBarrierManager,
161        barrier_receiver: UnboundedReceiver<Barrier>,
162        meta_client: MetaClient,
163    ) -> Self {
164        Self {
165            ctx,
166            sink_id,
167            iceberg_config,
168            pk_indices,
169            pk_data_types,
170            chunk_size,
171            local_barrier_manager,
172            barrier_receiver,
173            meta_client,
174        }
175    }
176
177    /// Data types of the survivor output chunk: `[pk_columns.., data_file, position]`.
178    fn output_data_types(&self) -> Vec<DataType> {
179        let mut types = self.pk_data_types.clone();
180        types.push(if self.iceberg_config.pk_index_stores_file_uuid() {
181            DataType::Bytea
182        } else {
183            DataType::Varchar
184        });
185        types.push(DataType::Int64);
186        types
187    }
188
189    #[try_stream(ok = DataChunk, error = SinkError)]
190    async fn resolve<'a>(
191        &'a self,
192        task_input: &'a ResolverTaskInput,
193        expected_snapshot: Option<i64>,
194        conflict_delete_metadata: &'a mut Option<SinkMetadata>,
195    ) {
196        let table = load_table_at_least(&self.iceberg_config, expected_snapshot)
197            .instrument_await("compaction_resolver_load_table")
198            .await?;
199        let file_io = table.file_io();
200        let snapshot_r = table
201            .metadata()
202            .snapshot_by_id(task_input.read_snapshot_id)
203            .with_context(|| {
204                format!(
205                    "compaction read snapshot {} not present in table metadata",
206                    task_input.read_snapshot_id
207                )
208            })?;
209        let snapshot_n = table
210            .metadata()
211            .current_snapshot()
212            .context("table has no current snapshot to resolve compaction against")?;
213
214        // The primary keys deleted during the compaction window, recovered from the input data files.
215        // Without a commit after R, nothing was deleted during the window.
216        let delete_diff_started = Instant::now();
217        let delete_diff_pk_set = if snapshot_r.snapshot_id() == snapshot_n.snapshot_id() {
218            HashSet::new()
219        } else {
220            collect_delete_diff_pks(
221                &table,
222                snapshot_r,
223                snapshot_n,
224                &task_input.input_data_file_paths,
225                &self.pk_indices,
226            )
227            .instrument_await("compaction_resolver_collect_delete_diff")
228            .await?
229        };
230        tracing::info!(
231            sink_id = %self.sink_id,
232            read_snapshot_id = snapshot_r.snapshot_id(),
233            current_snapshot_id = snapshot_n.snapshot_id(),
234            delete_diff_pks = delete_diff_pk_set.len(),
235            elapsed_ms = delete_diff_started.elapsed().as_millis() as u64,
236            "compaction resolver collected delete diff"
237        );
238
239        let data_file_locator = if self.iceberg_config.pk_index_stores_file_uuid() {
240            Some(PkIndexDataFileLocator::new(table.metadata())?)
241        } else {
242            None
243        };
244        let scan_started = Instant::now();
245        let mut survivor_rows = 0;
246        let mut conflicts: HashMap<String, DeleteVector> = HashMap::new();
247        #[for_await]
248        for chunk in self.scan_output_files(
249            file_io,
250            data_file_locator.as_ref(),
251            &task_input.output_data_file_paths,
252            Arc::new(delete_diff_pk_set),
253            &mut conflicts,
254        ) {
255            let chunk = chunk?;
256            survivor_rows += chunk.cardinality();
257            yield chunk;
258        }
259        tracing::info!(
260            sink_id = %self.sink_id,
261            output_files = task_input.output_data_file_paths.len(),
262            survivor_rows,
263            conflict_files = conflicts.len(),
264            elapsed_ms = scan_started.elapsed().as_millis() as u64,
265            "compaction resolver scanned output files"
266        );
267
268        *conflict_delete_metadata =
269            write_conflict_delete_files(&self.iceberg_config, &table, conflicts)
270                .instrument_await("compaction_resolver_write_conflict_deletes")
271                .await?;
272    }
273
274    /// Scans the output data files on spawned tasks, one per row group. Decoding them is
275    /// CPU-bound, so scanning them inside the actor would rebuild the whole pk index on a single
276    /// core, and scanning a file sequentially would pay the object store latency once per row
277    /// group.
278    #[try_stream(ok = DataChunk, error = SinkError)]
279    async fn scan_output_files<'a>(
280        &'a self,
281        file_io: &'a FileIO,
282        data_file_locator: Option<&'a PkIndexDataFileLocator>,
283        output_data_file_paths: &'a [String],
284        delete_diff_pk_set: Arc<HashSet<CompactionPk>>,
285        conflicts: &'a mut HashMap<String, DeleteVector>,
286    ) {
287        let splits: Vec<OutputScanSplit> = futures::stream::iter(
288            output_data_file_paths
289                .iter()
290                .map(|path| plan_output_file_splits(file_io, path, data_file_locator)),
291        )
292        .buffered(OUTPUT_FILE_OPEN_CONCURRENCY)
293        .try_collect::<Vec<_>>()
294        .instrument_await("compaction_resolver_plan_output_scan")
295        .await?
296        .into_iter()
297        .flatten()
298        .collect();
299        tracing::info!(
300            sink_id = %self.sink_id,
301            output_files = output_data_file_paths.len(),
302            row_groups = splits.len(),
303            "compaction resolver planned output scan"
304        );
305
306        let pk_indices: Arc<[usize]> = self.pk_indices.as_slice().into();
307        let (chunk_tx, mut chunk_rx) = mpsc::channel(OUTPUT_SCAN_CHANNEL_CAPACITY);
308        let permits = Arc::new(Semaphore::new(OUTPUT_SCAN_CONCURRENCY));
309        let split_paths: Vec<Arc<str>> = splits.iter().map(|split| split.path.clone()).collect();
310        let mut tasks = AbortOnDrop(
311            splits
312                .into_iter()
313                .map(|split| {
314                    let scan = scan_output_split(
315                        file_io.clone(),
316                        split,
317                        pk_indices.clone(),
318                        self.chunk_size,
319                        delete_diff_pk_set.clone(),
320                        chunk_tx.clone(),
321                    );
322                    let permits = permits.clone();
323                    tokio::spawn(async move {
324                        let _permit = permits
325                            .acquire_owned()
326                            .await
327                            .expect("output scan semaphore is never closed");
328                        scan.await
329                    })
330                })
331                .collect(),
332        );
333        // The channel closes once every scan task has finished and dropped its sender.
334        drop(chunk_tx);
335
336        let output_data_types = self.output_data_types();
337        let mut output_projection = None;
338        while let Some(chunk) = chunk_rx
339            .recv()
340            .instrument_await("compaction_resolver_scan_output_files")
341            .await
342        {
343            let chunk = chunk?;
344            if output_projection.is_none() {
345                output_projection = Some(OutputTypeProjection::new(
346                    chunk.data_types(),
347                    &output_data_types,
348                    self.pk_data_types.len(),
349                )?);
350            }
351            yield output_projection
352                .as_ref()
353                .expect("initialized from the first output chunk")
354                .execute(chunk)
355                .await?;
356        }
357
358        for (path, task) in split_paths.iter().zip_eq_fast(tasks.0.iter_mut()) {
359            let split_conflicts = task
360                .await
361                .with_context(|| format!("output scan task for {path} failed"))
362                .map_err(SinkError::Iceberg)?;
363            if let Some(delete_vector) = split_conflicts {
364                *conflicts.entry(path.to_string()).or_default() |= delete_vector;
365            }
366        }
367    }
368
369    #[try_stream(ok = Message, error = StreamExecutorError)]
370    async fn execute_inner(mut self) {
371        let actor_id = self.ctx.id;
372
373        // First barrier: forward it. There is no state table to initialize.
374        let first_barrier = self.barrier_receiver.recv().await.ok_or_else(|| {
375            StreamExecutorError::channel_closed("compaction resolver barrier receiver")
376        })?;
377        let (task_id, task_input) =
378            resolver_task_from_initial_barrier(self.sink_id, &first_barrier)?;
379        let begin_barrier = first_barrier.clone();
380        yield Message::Barrier(first_barrier);
381
382        let expected_snapshot = self
383            .meta_client
384            .wait_iceberg_pk_index_sink_epoch(self.sink_id, begin_barrier.epoch.prev)
385            .instrument_await("compaction_resolver_wait_sink_commit")
386            .await?;
387
388        let mut conflict_delete_metadata = None;
389        #[for_await]
390        for chunk in self.resolve(
391            &task_input,
392            expected_snapshot,
393            &mut conflict_delete_metadata,
394        ) {
395            let chunk = chunk.map_err(|e| (e, self.sink_id))?;
396            yield Message::Chunk(chunk.into());
397        }
398
399        let Some(barrier) = self.barrier_receiver.recv().await else {
400            return Err(StreamExecutorError::channel_closed(
401                "compaction resolver barrier receiver",
402            ));
403        };
404        validate_resolver_end_barrier(self.sink_id, &barrier, &begin_barrier, task_id)?;
405        if let Some(metadata) = conflict_delete_metadata
406            && metadata.metadata.is_some()
407        {
408            self.local_barrier_manager
409                .report_iceberg_pk_index_sink_metadata(
410                    barrier.epoch,
411                    self.sink_id,
412                    actor_id,
413                    PbIcebergPkIndexSinkRole::CompactionResolver,
414                    Some(metadata),
415                );
416        }
417        yield Message::Barrier(barrier);
418    }
419}
420
421impl Execute for CompactionResolverExecutor {
422    fn execute(self: Box<Self>) -> BoxedMessageStream {
423        self.execute_inner().boxed()
424    }
425}
426
427/// Aborts the spawned tasks when dropped, e.g. when the resolver stream fails or is dropped early.
428struct AbortOnDrop<T>(Vec<JoinHandle<T>>);
429
430impl<T> Drop for AbortOnDrop<T> {
431    fn drop(&mut self) {
432        for task in &self.0 {
433            task.abort();
434        }
435    }
436}
437
438/// Recovers the primary keys deleted between snapshots R and N from the input data files.
439///
440/// Only the input files whose position-delete file changed between R and N are read: an unchanged
441/// delete file means no new deletes on that file during the window.
442async fn collect_delete_diff_pks(
443    table: &Table,
444    snapshot_r: &SnapshotRef,
445    snapshot_n: &SnapshotRef,
446    input_data_file_paths: &[String],
447    pk_indices: &[usize],
448) -> Result<HashSet<CompactionPk>, SinkError> {
449    let file_io = table.file_io();
450    let input_paths: HashSet<&str> = input_data_file_paths.iter().map(String::as_str).collect();
451    let (deletes_r, deletes_n) = futures::future::try_join(
452        collect_input_delete_files(table, snapshot_r, &input_paths),
453        collect_input_delete_files(table, snapshot_n, &input_paths),
454    )
455    .await?;
456    let changed = changed_input_delete_files(input_data_file_paths, &deletes_r, &deletes_n);
457    tracing::info!(
458        input_files = input_data_file_paths.len(),
459        delete_files_r = deletes_r.len(),
460        delete_files_n = deletes_n.len(),
461        changed_delete_files = changed.len(),
462        "compaction resolver collecting delete diff"
463    );
464
465    let pks: Vec<Vec<OwnedRow>> = futures::stream::iter(changed.into_iter().map(
466        |(input_path, delete_r, delete_n)| async move {
467            let (positions_n, positions_r) = futures::future::try_join(
468                read_position_deletes_from_file(file_io, delete_n),
469                async {
470                    match delete_r {
471                        Some(delete_r) => read_position_deletes_from_file(file_io, delete_r)
472                            .await
473                            .map(Some),
474                        None => Ok(None),
475                    }
476                },
477            )
478            .await
479            .map_err(SinkError::Iceberg)?;
480            let mut diff = positions_n;
481            if let Some(positions_r) = &positions_r {
482                diff -= positions_r;
483            }
484            if diff.is_empty() {
485                return Ok(Vec::new());
486            }
487            scan_input_pks_at_positions(file_io, input_path, pk_indices, &diff).await
488        },
489    ))
490    .buffer_unordered(DELETE_DIFF_CONCURRENCY)
491    .try_collect()
492    .await?;
493    Ok(pks.into_iter().flatten().map(CompactionPk).collect())
494}
495
496/// Returns `(input path, delete file at R, delete file at N)` for every input data file whose live
497/// position-delete file at N differs from the one at R.
498fn changed_input_delete_files<'a>(
499    input_data_file_paths: &'a [String],
500    deletes_r: &'a HashMap<String, DataFile>,
501    deletes_n: &'a HashMap<String, DataFile>,
502) -> Vec<(&'a str, Option<&'a DataFile>, &'a DataFile)> {
503    input_data_file_paths
504        .iter()
505        .filter_map(|input_path| {
506            let delete_n = deletes_n.get(input_path.as_str())?;
507            let delete_r = deletes_r.get(input_path.as_str());
508            if delete_r.is_some_and(|delete_r| is_same_delete_file(delete_r, delete_n)) {
509                return None;
510            }
511            Some((input_path.as_str(), delete_r, delete_n))
512        })
513        .collect()
514}
515
516/// Delete files are immutable, so the same location identifies the same deleted positions. A
517/// deletion vector is a blob inside a Puffin file, so its offset and length are part of its location.
518fn is_same_delete_file(a: &DataFile, b: &DataFile) -> bool {
519    a.file_path() == b.file_path()
520        && a.content_offset() == b.content_offset()
521        && a.content_size_in_bytes() == b.content_size_in_bytes()
522}
523
524/// Walks the delete manifests of `snapshot` and returns, per input data file, the live
525/// position-delete file referencing it.
526async fn collect_input_delete_files(
527    table: &Table,
528    snapshot: &SnapshotRef,
529    input_paths: &HashSet<&str>,
530) -> Result<HashMap<String, DataFile>, SinkError> {
531    let file_io = table.file_io();
532    let manifest_list = table
533        .object_cache()
534        .get_manifest_list(snapshot, &table.metadata_ref())
535        .await?;
536
537    // Only delete manifests can carry position-delete files.
538    let manifests: Vec<_> = futures::stream::iter(
539        manifest_list
540            .entries()
541            .iter()
542            .filter(|manifest_file| manifest_file.content == ManifestContentType::Deletes)
543            .map(|manifest_file| manifest_file.load_manifest(file_io)),
544    )
545    .buffer_unordered(MANIFEST_LOAD_CONCURRENCY)
546    .try_collect()
547    .await?;
548
549    let mut map: HashMap<String, DataFile> = HashMap::new();
550    for manifest in &manifests {
551        for entry in manifest.entries() {
552            if !entry.is_alive() {
553                continue;
554            }
555            let data_file = entry.data_file();
556            if data_file.content_type() == DataContentType::PositionDeletes
557                && let Some(referenced) = data_file.referenced_data_file()
558                && input_paths.contains(referenced.as_str())
559                && map.insert(referenced, data_file.clone()).is_some()
560            {
561                return Err(SinkError::Iceberg(anyhow!(
562                    "input data file {} has multiple live position-delete files in snapshot {}",
563                    data_file.referenced_data_file().unwrap(),
564                    snapshot.snapshot_id()
565                )));
566            }
567        }
568    }
569    Ok(map)
570}
571
572/// Builds a projection for PK root columns and maps the projected physical order back to the
573/// downstream PK order.
574fn pk_projection(
575    parquet_schema: &SchemaDescriptor,
576    pk_indices: &[usize],
577) -> Result<(ProjectionMask, Vec<usize>), SinkError> {
578    let root_count = parquet_schema.root_schema().get_fields().len();
579    let mut physical_indices = Vec::with_capacity(pk_indices.len());
580    let mut seen = HashSet::with_capacity(pk_indices.len());
581
582    for &pk_index in pk_indices {
583        if pk_index >= root_count {
584            return Err(SinkError::Iceberg(anyhow!(
585                "pk index {pk_index} is out of range for parquet schema with {root_count} root columns"
586            )));
587        }
588        if !seen.insert(pk_index) {
589            return Err(SinkError::Iceberg(anyhow!("duplicate pk index {pk_index}")));
590        }
591        physical_indices.push(pk_index);
592    }
593
594    physical_indices.sort_unstable();
595    let pk_order = pk_indices
596        .iter()
597        .map(|pk_index| {
598            physical_indices
599                .binary_search(pk_index)
600                .expect("validated pk index must be projected")
601        })
602        .collect();
603    let projection = ProjectionMask::roots(parquet_schema, physical_indices);
604
605    Ok((projection, pk_order))
606}
607
608async fn scan_input_pks_at_positions(
609    file_io: &FileIO,
610    path: &str,
611    pk_indices: &[usize],
612    want_positions: &DeleteVector,
613) -> Result<Vec<OwnedRow>, SinkError> {
614    let mut results = Vec::new();
615    let input_file = file_io.new_input(path)?;
616    let metadata = input_file.metadata().await?;
617    let reader = input_file.reader().await?;
618    let builder = ParquetRecordBatchStreamBuilder::new(ParquetFileReader::new(metadata, reader))
619        .await
620        .map_err(|e| anyhow!(e).context(format!("open parquet reader for {path}")))?;
621    let (projection, pk_order) = pk_projection(builder.parquet_schema(), pk_indices)?;
622    let mut stream = builder
623        .with_projection(projection)
624        .build()
625        .map_err(|e| anyhow!(e).context(format!("build parquet stream for {path}")))?;
626
627    let mut base_pos = 0;
628    let mut iter = want_positions.iter().peekable();
629    while let Some(batch) = stream.next().await {
630        let batch =
631            batch.map_err(|e| anyhow!(e).context(format!("read parquet batch of {path}")))?;
632        let chunk = IcebergArrowConvert
633            .chunk_from_record_batch(&batch)
634            .map_err(|e| anyhow!(e).context(format!("convert parquet batch of {path}")))?
635            .project(&pk_order);
636        while let Some(&iter_pos) = iter.peek() {
637            let chunk_pos = iter_pos as usize - base_pos;
638            if chunk_pos >= chunk.capacity() {
639                break;
640            }
641            let pk = chunk.row_at(chunk_pos).0.to_owned_row();
642            results.push(pk);
643            iter.next();
644        }
645        base_pos += chunk.capacity();
646    }
647
648    Ok(results)
649}
650
651type OutputChunkSender = mpsc::Sender<Result<DataChunk, SinkError>>;
652
653/// Like the cast projection after an Iceberg engine-table scan, restores the writer's
654/// declared PK types using SQL casts. Metadata columns must match exactly.
655/// Build expressions once and reuse unchanged columns.
656/// Delete-diff comparisons remain in physical types on both sides.
657struct OutputTypeProjection {
658    input_types: Vec<DataType>,
659    casts: Vec<Option<BoxedExpression>>,
660}
661
662#[expect(
663    clippy::disallowed_methods,
664    reason = "PK index rebuilds must fail on cast errors instead of substituting NULL keys"
665)]
666impl OutputTypeProjection {
667    fn new(
668        input_types: Vec<DataType>,
669        output_types: &[DataType],
670        pk_column_count: usize,
671    ) -> Result<Self, SinkError> {
672        if input_types.len() != output_types.len() {
673            return Err(SinkError::Iceberg(anyhow!(
674                "compaction resolver output column count mismatch: expected {}, got {}",
675                output_types.len(),
676                input_types.len()
677            )));
678        }
679        let casts = input_types
680            .iter()
681            .zip_eq_fast(output_types)
682            .enumerate()
683            .map(|(index, (source, target))| {
684                if source == target {
685                    return Ok(None);
686                }
687                if index >= pk_column_count {
688                    return Err(SinkError::Iceberg(anyhow!(
689                        "compaction resolver metadata column {index} type mismatch: expected {target}, got {source}"
690                    )));
691                }
692                build_func(
693                    PbType::Cast,
694                    target.clone(),
695                    vec![InputRefExpression::new(source.clone(), index).boxed()],
696                )
697                .map(Some)
698                .with_context(|| {
699                    format!("build compaction resolver cast from {source} to {target}")
700                })
701                .map_err(SinkError::Iceberg)
702            })
703            .collect::<Result<_, _>>()?;
704        Ok(Self { input_types, casts })
705    }
706
707    async fn execute(&self, chunk: DataChunk) -> Result<DataChunk, SinkError> {
708        if chunk.data_types() != self.input_types {
709            return Err(SinkError::Iceberg(anyhow!(
710                "compaction resolver output schema changed between chunks"
711            )));
712        }
713        if self.casts.iter().all(Option::is_none) {
714            return Ok(chunk);
715        }
716        let mut columns = Vec::with_capacity(self.casts.len());
717        for (cast, column) in self.casts.iter().zip_eq_fast(chunk.columns()) {
718            columns.push(match cast {
719                Some(cast) => cast
720                    .eval(&chunk)
721                    .await
722                    .context("restore compaction resolver output types")
723                    .map_err(SinkError::Iceberg)?,
724                None => column.clone(),
725            });
726        }
727        Ok(DataChunk::new(columns, chunk.into_parts_v2().1))
728    }
729}
730
731/// One row group of an output data file, scanned by its own task.
732struct OutputScanSplit {
733    path: Arc<str>,
734    /// UUID stored in the PK index, or `None` for legacy file paths.
735    file_uuid: Option<Uuid>,
736    file_size: u64,
737    /// The parquet footer, loaded once per file and shared by all of its splits.
738    reader_metadata: ArrowReaderMetadata,
739    row_group: usize,
740    /// Position of the first row of the row group in the file.
741    first_row_position: i64,
742}
743
744/// Loads the parquet footer of an output data file and splits the file into its row groups.
745async fn plan_output_file_splits(
746    file_io: &FileIO,
747    path: &str,
748    data_file_locator: Option<&PkIndexDataFileLocator>,
749) -> Result<Vec<OutputScanSplit>, SinkError> {
750    let file_uuid = data_file_locator
751        .map(|locator| locator.file_uuid(path))
752        .transpose()?;
753    let input_file = file_io.new_input(path)?;
754    let file_metadata = input_file.metadata().await?;
755    let file_size = file_metadata.size;
756    let mut reader = ParquetFileReader::new(file_metadata, input_file.reader().await?);
757    let reader_metadata = ArrowReaderMetadata::load_async(&mut reader, Default::default())
758        .await
759        .map_err(|e| anyhow!(e).context(format!("load parquet metadata of {path}")))?;
760
761    let path: Arc<str> = path.into();
762    let mut first_row_position = 0;
763    let splits = (reader_metadata.metadata().row_groups().iter().enumerate())
764        .map(|(row_group, row_group_metadata)| {
765            let split = OutputScanSplit {
766                path: path.clone(),
767                file_uuid,
768                file_size,
769                reader_metadata: reader_metadata.clone(),
770                row_group,
771                first_row_position,
772            };
773            first_row_position += row_group_metadata.num_rows();
774            split
775        })
776        .collect();
777    Ok(splits)
778}
779
780/// Scans one row group of an output data file, sends its survivor rows to `chunk_tx`, and returns
781/// the positions of its conflict rows. A scan error is sent to `chunk_tx` too, so the resolver
782/// fails without waiting for the other scans.
783async fn scan_output_split(
784    file_io: FileIO,
785    split: OutputScanSplit,
786    pk_indices: Arc<[usize]>,
787    chunk_size: usize,
788    delete_diff_pk_set: Arc<HashSet<CompactionPk>>,
789    chunk_tx: OutputChunkSender,
790) -> Option<DeleteVector> {
791    match scan_output_split_inner(
792        &file_io,
793        split,
794        &pk_indices,
795        chunk_size,
796        &delete_diff_pk_set,
797        &chunk_tx,
798    )
799    .await
800    {
801        Ok(conflicts) => conflicts,
802        Err(e) => {
803            // The receiver is gone only if the resolver already stopped.
804            let _ = chunk_tx.send(Err(e)).await;
805            None
806        }
807    }
808}
809
810async fn scan_output_split_inner(
811    file_io: &FileIO,
812    split: OutputScanSplit,
813    pk_indices: &[usize],
814    chunk_size: usize,
815    delete_diff_pk_set: &HashSet<CompactionPk>,
816    chunk_tx: &OutputChunkSender,
817) -> Result<Option<DeleteVector>, SinkError> {
818    let path = &*split.path;
819    let reader = ParquetFileReader::new(
820        FileMetadata {
821            size: split.file_size,
822        },
823        file_io.new_input(path)?.reader().await?,
824    );
825    let builder = ParquetRecordBatchStreamBuilder::new_with_metadata(reader, split.reader_metadata);
826    let (projection, pk_order) = pk_projection(builder.parquet_schema(), pk_indices)?;
827    let mut stream = builder
828        .with_projection(projection)
829        .with_row_groups(vec![split.row_group])
830        .with_batch_size(chunk_size)
831        .build()
832        .map_err(|e| anyhow!(e).context(format!("build parquet stream for {path}")))?;
833
834    let mut conflicts = DeleteVector::default();
835    let mut position = split.first_row_position;
836    while let Some(batch) = stream.next().await {
837        let batch =
838            batch.map_err(|e| anyhow!(e).context(format!("read parquet batch of {path}")))?;
839        let pk_chunk = IcebergArrowConvert
840            .chunk_from_record_batch(&batch)
841            .map_err(|e| anyhow!(e).context(format!("convert parquet batch of {path}")))?
842            .project(&pk_order);
843        let row_count = pk_chunk.capacity();
844        if let Some(chunk) = survivor_chunk(
845            pk_chunk,
846            path,
847            split.file_uuid,
848            position,
849            delete_diff_pk_set,
850            &mut conflicts,
851        ) && chunk_tx.send(Ok(chunk)).await.is_err()
852        {
853            return Ok(None);
854        }
855        position += row_count as i64;
856    }
857
858    Ok((!conflicts.is_empty()).then_some(conflicts))
859}
860
861/// An owned compaction key hashed like `RowRef` for allocation-free borrowed lookups.
862#[derive(Clone, PartialEq, Eq)]
863struct CompactionPk(OwnedRow);
864
865impl std::hash::Hash for CompactionPk {
866    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
867        self.0.hash_datums_into(state);
868    }
869}
870
871impl Equivalent<CompactionPk> for RowRef<'_> {
872    fn equivalent(&self, key: &CompactionPk) -> bool {
873        Row::eq(self, &key.0)
874    }
875}
876
877/// Builds the survivor chunk `[pk_columns.., data_file, position]` of a batch of output rows whose
878/// first row is at `first_position` in `path`. Rows whose pk was deleted during the compaction
879/// window are recorded in `conflicts` instead. Returns `None` if no row survives.
880/// `data_file` is the UUID in UUID mode, or the path in legacy mode.
881///
882/// The chunk is assembled column by column: the pk columns are reused as-is, so the common case
883/// where nothing was deleted never touches individual rows.
884fn survivor_chunk(
885    pk_chunk: DataChunk,
886    path: &str,
887    file_uuid: Option<Uuid>,
888    first_position: i64,
889    delete_diff_pk_set: &HashSet<CompactionPk>,
890    conflicts: &mut DeleteVector,
891) -> Option<DataChunk> {
892    let row_count = pk_chunk.capacity();
893    let positions = first_position..first_position + row_count as i64;
894    let visibility: Bitmap = if delete_diff_pk_set.is_empty() {
895        row_count.into()
896    } else {
897        (0..row_count)
898            .map(|row_idx| {
899                let conflict = delete_diff_pk_set.contains(&pk_chunk.row_at(row_idx).0);
900                if conflict {
901                    conflicts.insert((first_position + row_idx as i64) as u64);
902                }
903                !conflict
904            })
905            .collect()
906    };
907    if !visibility.any() {
908        return None;
909    }
910
911    let (mut columns, _) = pk_chunk.into_parts();
912    columns.push(Arc::new(match file_uuid {
913        Some(uuid) => ArrayImpl::Bytea(
914            std::iter::repeat_n(uuid.as_bytes().as_slice(), row_count).collect::<BytesArray>(),
915        ),
916        None => ArrayImpl::Utf8(std::iter::repeat_n(path, row_count).collect::<Utf8Array>()),
917    }));
918    columns.push(Arc::new(ArrayImpl::Int64(positions.collect::<I64Array>())));
919    let chunk = DataChunk::new(columns, visibility);
920    Some(if chunk.is_vis_compacted() {
921        chunk
922    } else {
923        chunk.compact_vis()
924    })
925}
926
927async fn write_conflict_delete_files(
928    config: &IcebergConfig,
929    table: &Table,
930    conflicts: HashMap<String, DeleteVector>,
931) -> Result<Option<SinkMetadata>, SinkError> {
932    if conflicts.is_empty() {
933        return Ok(None);
934    }
935
936    let location_generator = DefaultLocationGenerator::new(table.metadata())?;
937    let uuid_suffix = Uuid::now_v7();
938    let file_name_generators = PositionDeleteFileNameGenerators::new(uuid_suffix);
939    let format_version = table.metadata().format_version();
940
941    let mut delete_files = Vec::with_capacity(conflicts.len());
942    for (output_file, delete_vector) in conflicts {
943        // Compaction outputs are not committed yet and the resolver only receives their paths,
944        // so these delete files intentionally omit `PartitionKey`. Meta backfills each partition
945        // from the referenced compactor output file during the compaction pre-commit.
946        let file = write_position_delete_file(
947            table,
948            config,
949            &location_generator,
950            &file_name_generators,
951            format_version,
952            output_file,
953            &delete_vector,
954            None,
955        )
956        .await?;
957        delete_files.push(file);
958    }
959
960    let delete_files = serialize_data_files_default_spec(table, delete_files)?;
961    let result = IcebergPositionDeleteCommitResult {
962        schema_id: table.metadata().current_schema_id(),
963        partition_spec_id: table.metadata().default_partition_spec_id(),
964        delete_files,
965        // The output files are uncommitted, so no pre-existing DV file is being overwritten.
966        overwrite_files: vec![],
967    };
968    let sink_metadata = SinkMetadata::try_from(&result)?;
969    Ok(Some(sink_metadata))
970}
971
972#[cfg(test)]
973mod tests {
974    use std::sync::Arc;
975
976    use iceberg::spec::{DataFileBuilder, DataFileFormat, Struct};
977    use parquet::arrow::ArrowWriter;
978    use parquet::basic::Type as PhysicalType;
979    use parquet::file::properties::WriterProperties;
980    use parquet::schema::types::{SchemaDescriptor, Type};
981    use risingwave_common::array::arrow::arrow_schema_58 as arrow_schema;
982    use risingwave_common::array::{Array, ArrayBuilderImpl, DataChunkTestExt};
983    use risingwave_common::types::{MapType, StructType};
984    use risingwave_common::util::epoch::test_epoch;
985    use risingwave_pb::stream_plan::IcebergPkIndexCompactionContext;
986
987    use super::*;
988
989    fn test_parquet_schema() -> SchemaDescriptor {
990        SchemaDescriptor::new(Arc::new(
991            Type::group_type_builder("schema")
992                .with_fields(
993                    ["column_0", "column_1", "column_2", "column_3", "column_4"]
994                        .into_iter()
995                        .map(|name| {
996                            Arc::new(
997                                Type::primitive_type_builder(name, PhysicalType::INT32)
998                                    .build()
999                                    .unwrap(),
1000                            )
1001                        })
1002                        .collect(),
1003                )
1004                .build()
1005                .unwrap(),
1006        ))
1007    }
1008
1009    #[test]
1010    fn test_pk_projection_restores_downstream_pk_order() {
1011        let parquet_schema = test_parquet_schema();
1012
1013        let (_, order) = pk_projection(&parquet_schema, &[2, 0, 1]).unwrap();
1014        assert_eq!(order, vec![2, 0, 1]);
1015
1016        let (_, order) = pk_projection(&parquet_schema, &[4, 1, 3]).unwrap();
1017        assert_eq!(order, vec![2, 0, 1]);
1018    }
1019
1020    #[test]
1021    fn test_pk_projection_reorders_heterogeneous_chunk() {
1022        let chunk = DataChunk::from_pretty(
1023            "i T
1024             7 k",
1025        );
1026        let projected = chunk.project(&[1, 0]);
1027
1028        assert_eq!(
1029            projected,
1030            DataChunk::from_pretty(
1031                "T i
1032                 k 7",
1033            )
1034        );
1035    }
1036
1037    #[test]
1038    fn test_survivor_chunk_assigns_positions_and_skips_conflicts() {
1039        let pk_chunk = DataChunk::from_pretty(
1040            "I
1041             1
1042             2
1043             3",
1044        );
1045        let pk = |id: i64| CompactionPk(OwnedRow::new(vec![Some(ScalarImpl::Int64(id))]));
1046        let mut conflicts = DeleteVector::default();
1047
1048        let chunk = survivor_chunk(
1049            pk_chunk.clone(),
1050            "f",
1051            None,
1052            10,
1053            &HashSet::new(),
1054            &mut conflicts,
1055        )
1056        .unwrap();
1057        assert_eq!(
1058            chunk,
1059            DataChunk::from_pretty(
1060                "I T I
1061                 1 f 10
1062                 2 f 11
1063                 3 f 12",
1064            )
1065        );
1066        assert!(conflicts.is_empty());
1067
1068        let deleted = HashSet::from([pk(2)]);
1069        let chunk =
1070            survivor_chunk(pk_chunk.clone(), "f", None, 10, &deleted, &mut conflicts).unwrap();
1071        assert_eq!(
1072            chunk,
1073            DataChunk::from_pretty(
1074                "I T I
1075                 1 f 10
1076                 3 f 12",
1077            )
1078        );
1079        assert_eq!(conflicts.iter().collect::<Vec<_>>(), vec![11]);
1080
1081        let all_deleted = HashSet::from([pk(1), pk(2), pk(3)]);
1082        let mut conflicts = DeleteVector::default();
1083        assert!(survivor_chunk(pk_chunk, "f", None, 0, &all_deleted, &mut conflicts).is_none());
1084        assert_eq!(conflicts.iter().collect::<Vec<_>>(), vec![0, 1, 2]);
1085    }
1086
1087    #[tokio::test]
1088    async fn test_restore_output_types_restores_smallint_keys() {
1089        let chunk = DataChunk::from_pretty(
1090            "i T I
1091             -32768 f 10
1092             32767 f 11",
1093        );
1094        let path_column = chunk.column_at(1).clone();
1095        let position_column = chunk.column_at(2).clone();
1096        let chunk = restore_output_types(
1097            chunk,
1098            &[DataType::Int16, DataType::Varchar, DataType::Int64],
1099            1,
1100        )
1101        .await
1102        .unwrap();
1103        assert_eq!(
1104            chunk.data_types(),
1105            vec![DataType::Int16, DataType::Varchar, DataType::Int64]
1106        );
1107        assert_eq!(
1108            chunk.column_at(0).as_int16().iter().collect::<Vec<_>>(),
1109            vec![Some(i16::MIN), Some(i16::MAX)]
1110        );
1111        assert!(Arc::ptr_eq(chunk.column_at(1), &path_column));
1112        assert!(Arc::ptr_eq(chunk.column_at(2), &position_column));
1113    }
1114
1115    #[test]
1116    fn test_survivor_chunk_matches_composite_keys_and_nulls() {
1117        let pk_chunk = DataChunk::from_pretty(
1118            "i T
1119             1 alpha
1120             1 alphabet
1121             2 alpha
1122             1 .
1123             2 .
1124             1 alpha",
1125        );
1126        let deleted = HashSet::from([
1127            CompactionPk(OwnedRow::new(vec![
1128                Some(ScalarImpl::Int32(1)),
1129                Some("alpha".into()),
1130            ])),
1131            CompactionPk(OwnedRow::new(vec![Some(ScalarImpl::Int32(1)), None])),
1132        ]);
1133        let mut conflicts = DeleteVector::default();
1134        let chunk = survivor_chunk(pk_chunk, "f", None, 10, &deleted, &mut conflicts).unwrap();
1135        assert_eq!(
1136            chunk,
1137            DataChunk::from_pretty(
1138                "i T T I
1139                 1 alphabet f 11
1140                 2 alpha f 12
1141                 2 . f 14",
1142            )
1143        );
1144        assert_eq!(conflicts.iter().collect::<Vec<_>>(), vec![10, 13, 15]);
1145    }
1146
1147    #[test]
1148    fn test_compaction_pk_matches_row_ref_hash_and_equality() {
1149        use std::hash::{BuildHasher, BuildHasherDefault, DefaultHasher};
1150
1151        let mut values = Vec::new();
1152        let columns = [
1153            (DataType::Boolean, "true"),
1154            (DataType::Int16, "-7"),
1155            (DataType::Int32, "123"),
1156            (DataType::Int64, "4294967297"),
1157            (DataType::Float32, "NaN"),
1158            (DataType::Float64, "-0"),
1159            (DataType::Decimal, "1234.50"),
1160            (DataType::Varchar, "borrowed primary key"),
1161            (DataType::Bytea, r"\x00aabbff"),
1162            (DataType::Jsonb, r#"{"key": [1, null, true]}"#),
1163            (DataType::Interval, "2 days 03:04:05"),
1164            (DataType::Serial, "123"),
1165            (DataType::list(DataType::Int16), "{-3,7,NULL}"),
1166            (
1167                DataType::Struct(StructType::new(vec![
1168                    ("id", DataType::Int16),
1169                    ("name", DataType::Varchar),
1170                ])),
1171                "(7,hello)",
1172            ),
1173            (
1174                DataType::Map(MapType::from_kv(DataType::Int16, DataType::Int16)),
1175                "{1:2,3:NULL}",
1176            ),
1177        ]
1178        .into_iter()
1179        .map(|(data_type, text)| {
1180            let value = ScalarImpl::from_text_for_test(text, &data_type).unwrap();
1181            let mut builder = ArrayBuilderImpl::with_type(2, data_type);
1182            builder.append(Some(value.clone()));
1183            builder.append(None::<ScalarImpl>);
1184            values.push(Some(value));
1185            Arc::new(builder.finish())
1186        })
1187        .collect();
1188        let original = CompactionPk(OwnedRow::new(values));
1189        let nulls = CompactionPk(OwnedRow::new(vec![None; original.0.len()]));
1190        let chunk = DataChunk::new(columns, 2);
1191        let borrowed = chunk.row_at(0).0;
1192        let borrowed_nulls = chunk.row_at(1).0;
1193        let hash_builder = BuildHasherDefault::<DefaultHasher>::default();
1194        for (borrowed, owned) in [(&borrowed, &original), (&borrowed_nulls, &nulls)] {
1195            assert_eq!(
1196                hash_builder.hash_one(borrowed),
1197                hash_builder.hash_one(owned)
1198            );
1199            let keys = HashSet::<CompactionPk>::from([owned.clone()]);
1200            assert!(keys.contains(borrowed));
1201        }
1202        assert!(!borrowed.equivalent(&nulls));
1203        assert!(!borrowed_nulls.equivalent(&original));
1204        assert!(!borrowed.equivalent(&CompactionPk(OwnedRow::empty())));
1205
1206        let keys: HashSet<_> = [original.clone(), original.clone(), nulls.clone(), nulls]
1207            .into_iter()
1208            .collect();
1209        assert_eq!(keys.len(), 2);
1210        assert!(keys.contains(&borrowed));
1211        assert!(keys.contains(&borrowed_nulls));
1212
1213        let empty_chunk = DataChunk::new(vec![], 1);
1214        let empty = empty_chunk.row_at(0).0;
1215        assert_eq!(
1216            hash_builder.hash_one(empty),
1217            hash_builder.hash_one(CompactionPk(OwnedRow::empty()))
1218        );
1219        assert!(HashSet::<CompactionPk>::from([CompactionPk(OwnedRow::empty())]).contains(&empty));
1220        assert!(!empty.equivalent(&original));
1221    }
1222
1223    #[tokio::test]
1224    async fn test_restore_output_types_rejects_metadata_casts() {
1225        for (input_types, output_types) in [
1226            (
1227                vec![DataType::Int32, DataType::Varchar, DataType::Int64],
1228                vec![DataType::Int16, DataType::Bytea, DataType::Int64],
1229            ),
1230            (
1231                vec![DataType::Int32, DataType::Bytea, DataType::Int64],
1232                vec![DataType::Int16, DataType::Varchar, DataType::Int64],
1233            ),
1234            (
1235                vec![DataType::Int32, DataType::Varchar, DataType::Int32],
1236                vec![DataType::Int16, DataType::Varchar, DataType::Int64],
1237            ),
1238        ] {
1239            assert!(
1240                OutputTypeProjection::new(input_types.clone(), &output_types, 1).is_err(),
1241                "must reject metadata casts from {input_types:?} to {output_types:?}"
1242            );
1243        }
1244    }
1245
1246    #[tokio::test]
1247    async fn test_restore_output_types_rejects_mismatches() {
1248        for value in [-32769, 32768] {
1249            let chunk = DataChunk::from_pretty(&format!("i\n{value}"));
1250            assert!(
1251                restore_output_types(chunk, &[DataType::Int16], 1)
1252                    .await
1253                    .is_err()
1254            );
1255        }
1256        let chunk = DataChunk::from_pretty("i\n1");
1257        assert!(
1258            restore_output_types(chunk.clone(), &[DataType::Bytea], 1)
1259                .await
1260                .is_err()
1261        );
1262        assert!(restore_output_types(chunk.clone(), &[], 1).await.is_err());
1263        assert_eq!(
1264            restore_output_types(chunk.clone(), &[DataType::Int32], 1)
1265                .await
1266                .unwrap(),
1267            chunk
1268        );
1269        let projection =
1270            OutputTypeProjection::new(vec![DataType::Int32], &[DataType::Int16], 1).unwrap();
1271        assert!(
1272            projection
1273                .execute(DataChunk::from_pretty("T\nx"))
1274                .await
1275                .is_err()
1276        );
1277    }
1278
1279    async fn restore_output_types(
1280        chunk: DataChunk,
1281        output_types: &[DataType],
1282        pk_column_count: usize,
1283    ) -> Result<DataChunk, SinkError> {
1284        OutputTypeProjection::new(chunk.data_types(), output_types, pk_column_count)?
1285            .execute(chunk)
1286            .await
1287    }
1288
1289    #[tokio::test]
1290    async fn test_restore_output_types_round_trips_iceberg_type_mappings() {
1291        for (data_type, text) in [
1292            (DataType::Int16, "-7"),
1293            (DataType::Jsonb, r#"{"key": [1, null, true]}"#),
1294            (DataType::Interval, "2 days 03:04:05"),
1295            (DataType::Serial, "123"),
1296            (DataType::list(DataType::Int16), "{-3,7,NULL}"),
1297            (
1298                DataType::Struct(StructType::new(vec![
1299                    ("id", DataType::Int16),
1300                    ("name", DataType::Varchar),
1301                ])),
1302                "(7,hello)",
1303            ),
1304            (
1305                DataType::Map(MapType::from_kv(DataType::Int16, DataType::Int16)),
1306                "{1:2,3:NULL}",
1307            ),
1308        ] {
1309            let value = ScalarImpl::from_text_for_test(text, &data_type).unwrap();
1310            let mut builder = ArrayBuilderImpl::with_type(2, data_type.clone());
1311            builder.append(Some(value));
1312            builder.append(None::<ScalarImpl>);
1313            let original = DataChunk::new(vec![Arc::new(builder.finish())], 2);
1314            let schema = Arc::new(arrow_schema::Schema::new(vec![
1315                IcebergArrowConvert
1316                    .to_arrow_field("pk", &data_type)
1317                    .unwrap(),
1318            ]));
1319            let batch = IcebergArrowConvert
1320                .to_record_batch(schema, &original)
1321                .unwrap();
1322            let physical = IcebergArrowConvert.chunk_from_record_batch(&batch).unwrap();
1323            assert_ne!(physical.data_types(), original.data_types(), "{data_type}");
1324            assert_eq!(
1325                restore_output_types(physical, std::slice::from_ref(&data_type), 1)
1326                    .await
1327                    .unwrap(),
1328                original,
1329                "{data_type}"
1330            );
1331        }
1332    }
1333
1334    #[cfg_attr(madsim, ignore = "requires Iceberg's native Tokio runtime")]
1335    #[tokio::test]
1336    async fn test_output_scan_preserves_positions_across_row_groups() {
1337        check_output_scan_preserves_positions_across_row_groups(false).await;
1338    }
1339
1340    #[cfg_attr(madsim, ignore = "requires Iceberg's native Tokio runtime")]
1341    #[tokio::test]
1342    async fn test_output_scan_preserves_file_uuids_across_row_groups() {
1343        check_output_scan_preserves_positions_across_row_groups(true).await;
1344    }
1345
1346    async fn check_output_scan_preserves_positions_across_row_groups(stores_file_uuid: bool) {
1347        let pk_chunk = DataChunk::from_pretty(
1348            "i
1349             1
1350             2
1351             3
1352             4
1353             5
1354             6",
1355        );
1356        let schema = Arc::new(arrow_schema::Schema::new(vec![
1357            IcebergArrowConvert
1358                .to_arrow_field("id", &DataType::Int32)
1359                .unwrap(),
1360        ]));
1361        let batch = IcebergArrowConvert
1362            .to_record_batch(schema.clone(), &pk_chunk)
1363            .unwrap();
1364        let mut bytes = Vec::new();
1365        let props = WriterProperties::builder()
1366            .set_max_row_group_row_count(Some(2))
1367            .build();
1368        let mut writer = ArrowWriter::try_new(&mut bytes, schema, Some(props)).unwrap();
1369        writer.write(&batch).unwrap();
1370        writer.close().unwrap();
1371
1372        let file_io = FileIO::new_with_memory();
1373        let path = "memory:/data/00112233-4455-6677-8899-aabbccddeeff.parquet";
1374        let locator =
1375            stores_file_uuid.then(|| PkIndexDataFileLocator::with_data_location("memory:/data"));
1376        file_io
1377            .new_output(path)
1378            .unwrap()
1379            .write(bytes.into())
1380            .await
1381            .unwrap();
1382        let splits = plan_output_file_splits(&file_io, path, locator.as_ref())
1383            .await
1384            .unwrap();
1385        assert_eq!(
1386            splits
1387                .iter()
1388                .map(|s| s.first_row_position)
1389                .collect::<Vec<_>>(),
1390            vec![0, 2, 4]
1391        );
1392
1393        // Conflicts in both later row groups must use file-relative positions, even when
1394        // splits finish out of order and each row group spans multiple batches.
1395        let deleted = Arc::new(HashSet::from([
1396            CompactionPk(OwnedRow::new(vec![Some(ScalarImpl::Int32(4))])),
1397            CompactionPk(OwnedRow::new(vec![Some(ScalarImpl::Int32(5))])),
1398        ]));
1399        let (tx, mut rx) = mpsc::channel(OUTPUT_SCAN_CHANNEL_CAPACITY);
1400        let mut conflicts = DeleteVector::default();
1401        for split in splits.into_iter().rev() {
1402            if let Some(dv) = scan_output_split(
1403                file_io.clone(),
1404                split,
1405                Arc::from([0]),
1406                1,
1407                deleted.clone(),
1408                tx.clone(),
1409            )
1410            .await
1411            {
1412                conflicts |= dv;
1413            }
1414        }
1415        drop(tx);
1416        let mut survivors = Vec::new();
1417        while let Some(chunk) = rx.recv().await {
1418            let chunk = chunk.unwrap();
1419            let data_file_column = chunk.column_at(1).clone();
1420            let data_file_type = if stores_file_uuid {
1421                DataType::Bytea
1422            } else {
1423                DataType::Varchar
1424            };
1425            let chunk = restore_output_types(
1426                chunk,
1427                &[DataType::Int16, data_file_type, DataType::Int64],
1428                1,
1429            )
1430            .await
1431            .unwrap();
1432            assert!(Arc::ptr_eq(chunk.column_at(1), &data_file_column));
1433            for row in chunk.rows() {
1434                survivors.push((
1435                    row.datum_at(0).unwrap().into_int16(),
1436                    row.datum_at(2).unwrap().into_int64(),
1437                ));
1438                if stores_file_uuid {
1439                    assert_eq!(
1440                        row.datum_at(1).unwrap().into_bytea(),
1441                        &[
1442                            0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb,
1443                            0xcc, 0xdd, 0xee, 0xff,
1444                        ]
1445                    );
1446                } else {
1447                    assert_eq!(row.datum_at(1).unwrap().into_utf8(), path);
1448                }
1449            }
1450        }
1451        survivors.sort_unstable();
1452        assert_eq!(survivors, vec![(1, 0), (2, 1), (3, 2), (6, 5)]);
1453        assert_eq!(conflicts.iter().collect::<Vec<_>>(), vec![3, 4]);
1454    }
1455
1456    fn compaction_barrier(
1457        epoch: u64,
1458        phase: Phase,
1459        resolver_task_input: Option<ResolverTaskInput>,
1460    ) -> Barrier {
1461        Barrier::new_test_barrier(test_epoch(epoch)).with_iceberg_pk_index_compaction(
1462            IcebergPkIndexCompactionContext {
1463                sink_id: SinkId::new(7),
1464                task_id: 11.into(),
1465                phase: phase as i32,
1466                resolver_task_input,
1467            },
1468        )
1469    }
1470
1471    #[test]
1472    fn test_resolver_task_is_initialized_from_b1() {
1473        let task_input = ResolverTaskInput {
1474            output_data_file_paths: vec!["output.parquet".into()],
1475            input_data_file_paths: vec!["input.parquet".into()],
1476            read_snapshot_id: 42,
1477        };
1478        let barrier = compaction_barrier(2, Phase::Begin, Some(task_input.clone()));
1479
1480        let (task_id, actual) =
1481            resolver_task_from_initial_barrier(SinkId::new(7), &barrier).unwrap();
1482        assert_eq!(task_id, IcebergCompactionTaskId::from(11));
1483        assert_eq!(actual, task_input);
1484    }
1485
1486    fn delete_file(path: &str, referenced: &str, content_offset: i64) -> DataFile {
1487        DataFileBuilder::default()
1488            .content(DataContentType::PositionDeletes)
1489            .file_path(path.to_owned())
1490            .file_format(DataFileFormat::Puffin)
1491            .file_size_in_bytes(100)
1492            .record_count(1)
1493            .partition(Struct::empty())
1494            .referenced_data_file(Some(referenced.to_owned()))
1495            .content_offset(Some(content_offset))
1496            .content_size_in_bytes(Some(10))
1497            .build()
1498            .unwrap()
1499    }
1500
1501    #[test]
1502    fn test_changed_input_delete_files_skips_unchanged_delete_files() {
1503        let input_paths: Vec<String> = ["unchanged", "new_blob", "new_dv", "only_r", "no_dv"]
1504            .into_iter()
1505            .map(String::from)
1506            .collect();
1507        let deletes_r = HashMap::from([
1508            (
1509                "unchanged".to_owned(),
1510                delete_file("r.puffin", "unchanged", 4),
1511            ),
1512            (
1513                "new_blob".to_owned(),
1514                delete_file("r.puffin", "new_blob", 14),
1515            ),
1516            ("only_r".to_owned(), delete_file("r.puffin", "only_r", 24)),
1517        ]);
1518        let deletes_n = HashMap::from([
1519            (
1520                "unchanged".to_owned(),
1521                delete_file("r.puffin", "unchanged", 4),
1522            ),
1523            // Same Puffin file, but a different blob in it.
1524            (
1525                "new_blob".to_owned(),
1526                delete_file("r.puffin", "new_blob", 34),
1527            ),
1528            ("new_dv".to_owned(), delete_file("n.puffin", "new_dv", 4)),
1529        ]);
1530
1531        let changed: Vec<_> = changed_input_delete_files(&input_paths, &deletes_r, &deletes_n)
1532            .into_iter()
1533            .map(|(path, delete_r, delete_n)| {
1534                (
1535                    path,
1536                    delete_r.map(|file| file.content_offset()),
1537                    delete_n.content_offset(),
1538                )
1539            })
1540            .collect();
1541        assert_eq!(
1542            changed,
1543            vec![
1544                ("new_blob", Some(Some(14)), Some(34)),
1545                ("new_dv", None, Some(4)),
1546            ]
1547        );
1548    }
1549
1550    #[test]
1551    fn test_resolver_requires_task_input_only_on_b1() {
1552        let begin = compaction_barrier(2, Phase::Begin, Some(ResolverTaskInput::default()));
1553        let end = compaction_barrier(3, Phase::End, None);
1554        validate_resolver_end_barrier(SinkId::new(7), &end, &begin, 11.into()).unwrap();
1555
1556        let invalid_begin = compaction_barrier(2, Phase::Begin, None);
1557        assert!(resolver_task_from_initial_barrier(SinkId::new(7), &invalid_begin).is_err());
1558        let invalid_end = compaction_barrier(3, Phase::End, Some(ResolverTaskInput::default()));
1559        assert!(
1560            validate_resolver_end_barrier(SinkId::new(7), &invalid_end, &begin, 11.into()).is_err()
1561        );
1562    }
1563}