Skip to main content

risingwave_frontend/optimizer/plan_node/
stream_iceberg_with_pk_index_writer.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 anyhow::Context;
16use pretty_xmlish::{Pretty, XmlNode};
17use risingwave_common::catalog::{Field, Schema};
18use risingwave_common::types::DataType;
19use risingwave_common::util::sort_util::OrderType;
20use risingwave_connector::sink::catalog::desc::SinkDesc;
21use risingwave_connector::sink::iceberg::LEGACY_PK_INDEX_FILE_PATH;
22use risingwave_pb::stream_plan::compaction_resolver_node::PkColumn;
23use risingwave_pb::stream_plan::stream_node::{NodeBody, PbStreamKind};
24use risingwave_pb::stream_plan::{
25    CompactionResolverNode, DispatchStrategy, DispatcherType, ExchangeNode,
26    IcebergWithPkIndexWriterNode, PbDispatchOutputMapping, PbStreamNode,
27};
28
29use super::stream::prelude::*;
30use crate::TableCatalog;
31use crate::optimizer::plan_node::expr_visitable::ExprVisitable;
32use crate::optimizer::plan_node::utils::{Distill, TableCatalogBuilder, childless_record};
33use crate::optimizer::plan_node::{
34    ExprRewritable, PlanBase, PlanTreeNodeUnary, Stream, StreamExchange, StreamNode,
35    StreamPlanRef as PlanRef,
36};
37use crate::optimizer::property::{
38    Distribution, FunctionalDependencySet, MonotonicityMap, WatermarkColumns,
39};
40use crate::scheduler::SchedulerResult;
41use crate::stream_fragmenter::BuildFragmentGraphState;
42
43/// `StreamIcebergWithPkIndexWriter` is the stateful writer executor for the Iceberg
44/// with pk index sink. It maintains a PK index and writes data files to Iceberg.
45///
46/// Output schema: `[file_path: Varchar, position: Int64]` — delete-position info for
47/// the downstream `PositionDeleteMerger`.
48#[derive(Debug, Clone, PartialEq, Eq, Hash)]
49pub struct StreamIcebergWithPkIndexWriter {
50    pub base: PlanBase<Stream>,
51    pub input: PlanRef,
52    pub sink_desc: SinkDesc,
53    pub pk_index_table: TableCatalog,
54}
55
56impl StreamIcebergWithPkIndexWriter {
57    pub fn from_stream_sink(sink: &super::StreamSink) -> Result<Self> {
58        let output_schema = output_schema();
59        let fd_set = FunctionalDependencySet::new(output_schema.len());
60        let dist = match sink.distribution() {
61            Distribution::Single => Distribution::Single,
62            _ => Distribution::SomeShard,
63        };
64        let base = PlanBase::new_stream(
65            sink.ctx(),
66            output_schema,
67            sink.stream_key().map(|v| v.to_vec()),
68            fd_set,
69            dist,
70            StreamKind::AppendOnly,
71            sink.emit_on_window_close(),
72            WatermarkColumns::new(),
73            MonotonicityMap::new(),
74        );
75        let pk_index_table = build_iceberg_pk_state_table(sink.sink_desc())?;
76        Ok(Self {
77            base,
78            input: sink.input(),
79            sink_desc: sink.sink_desc().clone(),
80            pk_index_table,
81        })
82    }
83}
84
85fn output_schema() -> Schema {
86    Schema::new(vec![
87        Field::with_name(DataType::Varchar, "file_path"),
88        Field::with_name(DataType::Int64, "position"),
89    ])
90}
91
92/// The PK index column locating the data file of a row. Sinks without the legacy file path layout
93/// store the 16-byte data file uuid instead of the full path (see `PkIndexDataFileLocator`).
94fn data_file_field(sink_desc: &SinkDesc) -> Field {
95    let legacy = sink_desc
96        .properties
97        .get(LEGACY_PK_INDEX_FILE_PATH)
98        .is_none_or(|v| !v.eq_ignore_ascii_case("false"));
99    if legacy {
100        Field::with_name(DataType::Varchar, "file_path")
101    } else {
102        Field::with_name(DataType::Bytea, "file_uuid")
103    }
104}
105
106/// Schema of the transient compaction resolver output consumed by the writer's right input.
107fn resolver_output_schema(sink_desc: &SinkDesc) -> Result<Schema> {
108    let downstream_pk = sink_desc
109        .downstream_pk
110        .as_deref()
111        .context("Missing downstream PK in Iceberg sink desc")?;
112    let mut fields: Vec<Field> = downstream_pk
113        .iter()
114        .map(|&idx| Field::from(&sink_desc.columns[idx].column_desc))
115        .collect();
116    fields.push(data_file_field(sink_desc));
117    fields.push(Field::with_name(DataType::Int64, "position"));
118    Ok(Schema::new(fields))
119}
120
121fn build_iceberg_pk_state_table(sink_desc: &SinkDesc) -> Result<TableCatalog> {
122    let mut builder = TableCatalogBuilder::default();
123
124    let downstream_pk = sink_desc
125        .downstream_pk
126        .as_deref()
127        .context("Missing downstream PK in Iceberg sink desc")?;
128    for &idx in downstream_pk {
129        builder.add_column(&Field::from(&sink_desc.columns[idx].column_desc));
130    }
131    builder.add_column(&data_file_field(sink_desc));
132    builder.add_column(&Field::with_name(DataType::Int64, "position"));
133
134    for idx in 0..downstream_pk.len() {
135        builder.add_order_column(idx, OrderType::ascending());
136    }
137
138    let res = builder.build((0..downstream_pk.len()).collect(), downstream_pk.len());
139    Ok(res)
140}
141
142impl Distill for StreamIcebergWithPkIndexWriter {
143    fn distill<'a>(&self) -> XmlNode<'a> {
144        let column_names = self
145            .sink_desc
146            .columns
147            .iter()
148            .map(|col| col.name_with_hidden().to_string())
149            .map(Pretty::from)
150            .collect();
151        let column_names = Pretty::Array(column_names);
152        let mut vec = Vec::with_capacity(2);
153        vec.push(("columns", column_names));
154        if let Some(pk) = &self.sink_desc.downstream_pk {
155            let column_names = pk
156                .iter()
157                .map(|&idx| self.sink_desc.columns[idx].name_with_hidden().to_string())
158                .map(Pretty::from)
159                .collect();
160            let column_names = Pretty::Array(column_names);
161            vec.push(("downstream_pk", column_names));
162        }
163
164        childless_record("StreamIcebergWithPkIndexWriter", vec)
165    }
166}
167
168impl PlanTreeNodeUnary<Stream> for StreamIcebergWithPkIndexWriter {
169    fn input(&self) -> PlanRef {
170        self.input.clone()
171    }
172
173    fn clone_with_input(&self, input: PlanRef) -> Self {
174        Self {
175            base: self.base.clone(),
176            input,
177            sink_desc: self.sink_desc.clone(),
178            pk_index_table: self.pk_index_table.clone(),
179        }
180    }
181}
182
183impl_plan_tree_node_for_unary! { Stream, StreamIcebergWithPkIndexWriter }
184
185impl StreamNode for StreamIcebergWithPkIndexWriter {
186    fn to_stream_prost_body(&self, _state: &mut BuildFragmentGraphState) -> NodeBody {
187        unreachable!(
188            "iceberg pk-index writer cannot be converted into a prost body -- call \
189             `adhoc_to_stream_prost` instead, since it declares a compaction resolver input."
190        )
191    }
192}
193
194impl StreamIcebergWithPkIndexWriter {
195    /// Serializes the writer with its normal upstream and a task-independent compaction resolver.
196    /// The exchange makes the resolver a separate fragment whose actors can remain inactive until
197    /// meta attaches them to the writer for a compaction task.
198    pub fn adhoc_to_stream_prost(
199        &self,
200        state: &mut BuildFragmentGraphState,
201    ) -> SchedulerResult<PbStreamNode> {
202        let pk_index_table = self
203            .pk_index_table
204            .clone()
205            .with_id(state.gen_table_id_wrapped())
206            .to_internal_table_prost();
207        let resolver_fields = resolver_output_schema(&self.sink_desc)
208            .context("build compaction resolver output schema")?
209            .to_prost();
210        let downstream_pk = self
211            .sink_desc
212            .downstream_pk
213            .as_ref()
214            .expect("validated when building the resolver schema");
215        let pk_columns: Vec<PkColumn> = downstream_pk
216            .iter()
217            .map(|&idx| PkColumn {
218                data_file_index: idx as u32,
219                column_desc: Some(self.sink_desc.columns[idx].column_desc.to_protobuf()),
220            })
221            .collect();
222        // The resolver output projects the PK columns first in `pk_columns` order, followed by
223        // the data file column and `position`. These are output-schema indices, not data-file indices.
224        let resolver_stream_key: Vec<u32> = (0..pk_columns.len() as u32).collect();
225
226        // The writer's normal input must have a fragment boundary so that it is rendered as a
227        // merge and can be disconnected while applying compaction.
228        let left_input = if self.input.as_stream_exchange().is_some() {
229            self.input.to_stream_prost(state)?
230        } else {
231            let exchange: PlanRef = StreamExchange::new_no_shuffle(self.input.clone()).into();
232            exchange.to_stream_prost(state)?
233        };
234        let right_dispatcher = match self.distribution() {
235            Distribution::Single => DispatcherType::Simple,
236            _ => DispatcherType::Hash,
237        };
238        let resolver = PbStreamNode {
239            node_body: Some(NodeBody::CompactionResolver(Box::new(
240                CompactionResolverNode {
241                    sink_id: self.sink_desc.id,
242                    properties: self.sink_desc.properties.clone(),
243                    secret_refs: self.sink_desc.secret_refs.clone(),
244                    pk_columns,
245                },
246            ))),
247            identity: "CompactionResolver".into(),
248            operator_id: state.gen_operator_id(),
249            stream_key: resolver_stream_key.clone(),
250            fields: resolver_fields.clone(),
251            stream_kind: PbStreamKind::AppendOnly as i32,
252            ..Default::default()
253        };
254        let right_input = PbStreamNode {
255            node_body: Some(NodeBody::Exchange(Box::new(ExchangeNode {
256                strategy: Some(DispatchStrategy {
257                    r#type: right_dispatcher as i32,
258                    dist_key_indices: match right_dispatcher {
259                        DispatcherType::Hash => resolver_stream_key.clone(),
260                        DispatcherType::Simple => vec![],
261                        DispatcherType::Unspecified
262                        | DispatcherType::Broadcast
263                        | DispatcherType::NoShuffle => unreachable!(),
264                    },
265                    output_mapping: Some(PbDispatchOutputMapping::identical(resolver_fields.len())),
266                }),
267            }))),
268            input: vec![resolver],
269            identity: "IcebergCompactionResolverExchange".into(),
270            operator_id: state.gen_operator_id(),
271            stream_key: resolver_stream_key,
272            fields: resolver_fields,
273            stream_kind: PbStreamKind::AppendOnly as i32,
274        };
275
276        Ok(PbStreamNode {
277            node_body: Some(NodeBody::IcebergWithPkIndexWriter(Box::new(
278                IcebergWithPkIndexWriterNode {
279                    sink_desc: Some(self.sink_desc.to_proto()),
280                    pk_index_table: Some(pk_index_table),
281                },
282            ))),
283            input: vec![left_input, right_input],
284            identity: self.distill_to_string(),
285            operator_id: self.id().to_stream_node_operator_id(),
286            stream_key: self
287                .stream_key()
288                .unwrap_or_default()
289                .iter()
290                .map(|x| *x as u32)
291                .collect(),
292            fields: self.schema().to_prost(),
293            stream_kind: self.stream_kind().to_protobuf() as i32,
294        })
295    }
296}
297
298impl ExprRewritable<Stream> for StreamIcebergWithPkIndexWriter {}
299
300impl ExprVisitable for StreamIcebergWithPkIndexWriter {}
301
302#[cfg(test)]
303mod tests {
304    use std::collections::BTreeMap;
305
306    use risingwave_common::catalog::{
307        ColumnCatalog, ColumnDesc, ColumnId, CreateType, DEFAULT_SUPER_USER_ID, StreamJobStatus,
308    };
309    use risingwave_common::util::sort_util::ColumnOrder;
310    use risingwave_connector::sink::catalog::{SinkId, SinkType};
311
312    use super::*;
313
314    fn test_sink_desc() -> SinkDesc {
315        SinkDesc {
316            id: SinkId::placeholder(),
317            name: "s".to_owned(),
318            definition: "".to_owned(),
319            columns: vec![
320                ColumnCatalog::visible(ColumnDesc::named("id", ColumnId::new(0), DataType::Int32)),
321                ColumnCatalog::visible(ColumnDesc::named("v1", ColumnId::new(1), DataType::Int32)),
322                ColumnCatalog::hidden(ColumnDesc::named(
323                    "_row_id",
324                    ColumnId::new(2),
325                    DataType::Serial,
326                )),
327            ],
328            plan_pk: vec![ColumnOrder::new(2, OrderType::ascending())],
329            downstream_pk: Some(vec![1]),
330            distribution_key: vec![1],
331            properties: BTreeMap::new(),
332            secret_refs: BTreeMap::new(),
333            sink_type: SinkType::Upsert,
334            ignore_delete: false,
335            format_desc: None,
336            db_name: "dev".to_owned(),
337            sink_from_name: "t".to_owned(),
338            target_table: None,
339            extra_partition_col_idx: None,
340            create_type: CreateType::Foreground,
341            is_exactly_once: None,
342            auto_refresh_schema_from_table: None,
343        }
344    }
345
346    #[test]
347    fn test_build_iceberg_pk_state_table_uses_downstream_pk_columns() {
348        let table = build_iceberg_pk_state_table(&test_sink_desc()).unwrap();
349
350        assert_eq!(table.columns()[0].name(), "v1");
351        assert_eq!(table.columns()[1].name(), "file_path");
352        assert_eq!(table.columns()[2].name(), "position");
353        assert_eq!(table.pk().len(), 1);
354        assert_eq!(table.pk()[0].column_index, 0);
355        assert_eq!(table.distribution_key(), &[0]);
356        assert_eq!(table.read_prefix_len_hint, 1);
357        assert_eq!(table.owner, DEFAULT_SUPER_USER_ID);
358        assert_eq!(table.stream_job_status, StreamJobStatus::Creating);
359    }
360
361    #[test]
362    fn test_build_iceberg_pk_state_table_with_multi_column_pk() {
363        // Simulate planner output where the derived pk spans several stream-key columns, e.g. a
364        // hidden upstream column (`order_id`) promoted to visible and carried in verbatim.
365        let mut desc = test_sink_desc();
366        desc.columns.push(ColumnCatalog::visible(ColumnDesc::named(
367            "order_id",
368            ColumnId::new(3),
369            DataType::Int64,
370        )));
371        desc.columns.push(ColumnCatalog::visible(ColumnDesc::named(
372            "shard_id",
373            ColumnId::new(4),
374            DataType::Int64,
375        )));
376        desc.downstream_pk = Some(vec![1, 3, 4]); // v1, order_id, shard_id
377
378        let table = build_iceberg_pk_state_table(&desc).unwrap();
379
380        let names: Vec<_> = table
381            .columns()
382            .iter()
383            .map(|c| c.name().to_owned())
384            .collect();
385        assert_eq!(
386            names,
387            vec!["v1", "order_id", "shard_id", "file_path", "position"]
388        );
389        assert_eq!(table.pk().len(), 3);
390        assert_eq!(table.distribution_key(), &[0, 1, 2]);
391        assert_eq!(table.read_prefix_len_hint, 3);
392    }
393
394    #[test]
395    fn test_build_iceberg_pk_state_table_with_visible_extra_only() {
396        // Simulate planner output: downstream_pk = [user_pk, visible_extra].
397        let mut desc = test_sink_desc();
398        desc.columns.push(ColumnCatalog::visible(ColumnDesc::named(
399            "order_id",
400            ColumnId::new(3),
401            DataType::Int64,
402        )));
403        desc.downstream_pk = Some(vec![1, 3]); // v1, order_id
404
405        let table = build_iceberg_pk_state_table(&desc).unwrap();
406
407        let names: Vec<_> = table
408            .columns()
409            .iter()
410            .map(|c| c.name().to_owned())
411            .collect();
412        assert_eq!(names, vec!["v1", "order_id", "file_path", "position"]);
413        assert_eq!(table.pk().len(), 2);
414        assert_eq!(table.distribution_key(), &[0, 1]);
415        assert_eq!(table.read_prefix_len_hint, 2);
416    }
417
418    #[test]
419    fn test_build_iceberg_pk_state_table_stores_file_uuid() {
420        let mut desc = test_sink_desc();
421        desc.properties
422            .insert(LEGACY_PK_INDEX_FILE_PATH.to_owned(), "false".to_owned());
423
424        let table = build_iceberg_pk_state_table(&desc).unwrap();
425        assert_eq!(table.columns()[1].name(), "file_uuid");
426        assert_eq!(table.columns()[1].data_type(), &DataType::Bytea);
427        assert_eq!(table.columns()[2].name(), "position");
428
429        let resolver_schema = resolver_output_schema(&desc).unwrap();
430        assert_eq!(resolver_schema.fields()[1].name, "file_uuid");
431        assert_eq!(resolver_schema.fields()[1].data_type, DataType::Bytea);
432    }
433}