Skip to main content

risingwave_connector/sink/iceberg/
config.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::collections::{BTreeMap, HashMap};
16use std::fmt::Debug;
17use std::sync::Arc;
18
19use anyhow::anyhow;
20use iceberg::spec::{FormatVersion, MAIN_BRANCH};
21use iceberg::table::Table;
22use iceberg::transaction::{MANIFEST_MIN_MERGE_COUNT_DEFAULT, MANIFEST_TARGET_SIZE_BYTES_DEFAULT};
23use iceberg::{Catalog, TableIdent};
24use parquet::basic::Compression;
25use serde::de::{self, Deserializer, Visitor};
26use serde::{Deserialize, Serialize};
27use serde_with::{DisplayFromStr, serde_as};
28use with_options::WithOptions;
29
30use super::{SINK_TYPE_APPEND_ONLY, SINK_TYPE_OPTION, SINK_TYPE_UPSERT, SinkError};
31use crate::connector_common::{
32    IcebergCatalogKind, IcebergCommon, IcebergTableIdentifier, ResolvedIcebergCatalogConfig,
33    iceberg_java_catalog_props_from_options,
34};
35use crate::enforce_secret::EnforceSecret;
36use crate::sink::Result;
37use crate::sink::decouple_checkpoint_log_sink::iceberg_default_commit_checkpoint_interval;
38use crate::{deserialize_bool_from_string, deserialize_optional_string_seq_from_string};
39
40pub const ICEBERG_COW_BRANCH: &str = "ingestion";
41
42pub const ICEBERG_WRITE_MODE_MERGE_ON_READ: &str = "merge-on-read";
43pub const ICEBERG_WRITE_MODE_COPY_ON_WRITE: &str = "copy-on-write";
44pub const ICEBERG_COMPACTION_TYPE_AUTO: &str = "auto";
45pub const ICEBERG_COMPACTION_TYPE_FULL: &str = "full";
46pub const ICEBERG_COMPACTION_TYPE_SMALL_FILES: &str = "small-files";
47pub const ICEBERG_COMPACTION_TYPE_FILES_WITH_DELETE: &str = "files-with-delete";
48
49pub const PARTITION_DATA_ID_START: i32 = 1000;
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
52#[serde(rename_all = "kebab-case")]
53pub enum IcebergWriteMode {
54    #[default]
55    MergeOnRead,
56    CopyOnWrite,
57}
58
59impl IcebergWriteMode {
60    pub fn as_str(self) -> &'static str {
61        match self {
62            IcebergWriteMode::MergeOnRead => ICEBERG_WRITE_MODE_MERGE_ON_READ,
63            IcebergWriteMode::CopyOnWrite => ICEBERG_WRITE_MODE_COPY_ON_WRITE,
64        }
65    }
66}
67
68impl std::str::FromStr for IcebergWriteMode {
69    type Err = SinkError;
70
71    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
72        match s {
73            ICEBERG_WRITE_MODE_MERGE_ON_READ => Ok(IcebergWriteMode::MergeOnRead),
74            ICEBERG_WRITE_MODE_COPY_ON_WRITE => Ok(IcebergWriteMode::CopyOnWrite),
75            _ => Err(SinkError::Config(anyhow!(format!(
76                "invalid write_mode: {}, must be one of: {}, {}",
77                s, ICEBERG_WRITE_MODE_MERGE_ON_READ, ICEBERG_WRITE_MODE_COPY_ON_WRITE
78            )))),
79        }
80    }
81}
82
83impl TryFrom<&str> for IcebergWriteMode {
84    type Error = <Self as std::str::FromStr>::Err;
85
86    fn try_from(value: &str) -> std::result::Result<Self, Self::Error> {
87        value.parse()
88    }
89}
90
91impl TryFrom<String> for IcebergWriteMode {
92    type Error = <Self as std::str::FromStr>::Err;
93
94    fn try_from(value: String) -> std::result::Result<Self, Self::Error> {
95        value.as_str().parse()
96    }
97}
98
99impl std::fmt::Display for IcebergWriteMode {
100    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101        f.write_str(self.as_str())
102    }
103}
104
105// Configuration constants
106pub const ENABLE_COMPACTION: &str = "enable_compaction";
107pub const COMPACTION_INTERVAL_SEC: &str = "compaction_interval_sec";
108pub const ENABLE_SNAPSHOT_EXPIRATION: &str = "enable_snapshot_expiration";
109pub const WRITE_MODE: &str = "write_mode";
110pub const FORMAT_VERSION: &str = "format_version";
111pub const SNAPSHOT_EXPIRATION_RETAIN_LAST: &str = "snapshot_expiration_retain_last";
112pub const SNAPSHOT_EXPIRATION_MAX_AGE_MILLIS: &str = "snapshot_expiration_max_age_millis";
113pub const SNAPSHOT_EXPIRATION_CLEAR_EXPIRED_FILES: &str = "snapshot_expiration_clear_expired_files";
114pub const SNAPSHOT_EXPIRATION_CLEAR_EXPIRED_META_DATA: &str =
115    "snapshot_expiration_clear_expired_meta_data";
116pub const ENABLE_MANIFEST_REWRITE: &str = "enable_manifest_rewrite";
117pub const MANIFEST_REWRITE_TARGET_SIZE_BYTES: &str = "manifest_rewrite_target_size_bytes";
118pub const MANIFEST_REWRITE_MIN_COUNT_TO_MERGE: &str = "manifest_rewrite_min_count_to_merge";
119pub const ENABLE_ORPHAN_FILE_CLEANUP: &str = "enable_orphan_file_cleanup";
120pub const ORPHAN_FILE_CLEANUP_MIN_AGE_MILLIS: &str = "orphan_file_cleanup_min_age_millis";
121pub const COMPACTION_MAX_SNAPSHOTS_NUM: &str = "compaction.max_snapshots_num";
122
123pub const COMPACTION_SMALL_FILES_THRESHOLD_MB: &str = "compaction.small_files_threshold_mb";
124
125pub const COMPACTION_DELETE_FILES_COUNT_THRESHOLD: &str = "compaction.delete_files_count_threshold";
126
127pub const COMPACTION_TRIGGER_SNAPSHOT_COUNT: &str = "compaction.trigger_snapshot_count";
128
129pub const COMPACTION_TARGET_FILE_SIZE_MB: &str = "compaction.target_file_size_mb";
130
131pub const COMPACTION_TYPE: &str = "compaction.type";
132
133pub const COMPACTION_WRITE_PARQUET_COMPRESSION: &str = "compaction.write_parquet_compression";
134pub const COMPACTION_WRITE_PARQUET_MAX_ROW_GROUP_ROWS: &str =
135    "compaction.write_parquet_max_row_group_rows";
136pub const COMPACTION_WRITE_PARQUET_MAX_ROW_GROUP_BYTES: &str =
137    "compaction.write_parquet_max_row_group_bytes";
138pub const ORDER_KEY: &str = "order_key";
139pub const DEFAULT_COMPACTION_MAX_SNAPSHOTS_NUM: usize = 1000;
140pub const ICEBERG_DEFAULT_WRITE_PARQUET_MAX_ROW_GROUP_BYTES: usize = 128 * 1024 * 1024;
141pub const ORPHAN_FILE_CLEANUP_MIN_AGE_MILLIS_DEFAULT: u64 = 7 * 24 * 60 * 60 * 1000;
142pub const ORPHAN_FILE_CLEANUP_MIN_AGE_MILLIS_MINIMUM: u64 = 24 * 60 * 60 * 1000;
143pub const ENABLE_PK_INDEX: &str = "enable_pk_index";
144pub const LEGACY_PK_INDEX_FILE_PATH: &str = "legacy_pk_index_file_path";
145
146pub const PARQUET_CREATED_BY: &str = concat!("risingwave version ", env!("CARGO_PKG_VERSION"));
147
148fn default_commit_retry_num() -> u32 {
149    8
150}
151
152fn default_iceberg_write_mode() -> IcebergWriteMode {
153    IcebergWriteMode::MergeOnRead
154}
155
156fn default_iceberg_format_version() -> FormatVersion {
157    FormatVersion::V2
158}
159
160fn default_true() -> bool {
161    true
162}
163
164fn default_some_true() -> Option<bool> {
165    Some(true)
166}
167
168fn parse_format_version_str(value: &str) -> std::result::Result<FormatVersion, String> {
169    let parsed = value
170        .trim()
171        .parse::<u8>()
172        .map_err(|_| "`format-version` must be one of 1, 2, or 3".to_owned())?;
173    match parsed {
174        1 => Ok(FormatVersion::V1),
175        2 => Ok(FormatVersion::V2),
176        3 => Ok(FormatVersion::V3),
177        _ => Err("`format-version` must be one of 1, 2, or 3".to_owned()),
178    }
179}
180
181fn deserialize_format_version<'de, D>(
182    deserializer: D,
183) -> std::result::Result<FormatVersion, D::Error>
184where
185    D: Deserializer<'de>,
186{
187    struct FormatVersionVisitor;
188
189    impl<'de> Visitor<'de> for FormatVersionVisitor {
190        type Value = FormatVersion;
191
192        fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
193            formatter.write_str("format-version as 1, 2, or 3")
194        }
195
196        fn visit_u64<E>(self, value: u64) -> std::result::Result<Self::Value, E>
197        where
198            E: de::Error,
199        {
200            let value = u8::try_from(value)
201                .map_err(|_| E::custom("`format-version` must be one of 1, 2, or 3"))?;
202            parse_format_version_str(&value.to_string()).map_err(E::custom)
203        }
204
205        fn visit_i64<E>(self, value: i64) -> std::result::Result<Self::Value, E>
206        where
207            E: de::Error,
208        {
209            let value = u8::try_from(value)
210                .map_err(|_| E::custom("`format-version` must be one of 1, 2, or 3"))?;
211            parse_format_version_str(&value.to_string()).map_err(E::custom)
212        }
213
214        fn visit_str<E>(self, value: &str) -> std::result::Result<Self::Value, E>
215        where
216            E: de::Error,
217        {
218            parse_format_version_str(value).map_err(E::custom)
219        }
220
221        fn visit_string<E>(self, value: String) -> std::result::Result<Self::Value, E>
222        where
223            E: de::Error,
224        {
225            self.visit_str(&value)
226        }
227    }
228
229    deserializer.deserialize_any(FormatVersionVisitor)
230}
231
232/// Compaction type for Iceberg sink
233#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
234#[serde(rename_all = "kebab-case")]
235pub enum CompactionType {
236    /// Auto compaction - compacts the union of small and delete-heavy files
237    Auto,
238    /// Full compaction - rewrites all data files
239    Full,
240    /// Small files compaction - only compact small files
241    SmallFiles,
242    /// Files with delete compaction - only compact files that have associated delete files
243    FilesWithDelete,
244}
245
246impl CompactionType {
247    pub fn as_str(&self) -> &'static str {
248        match self {
249            CompactionType::Auto => ICEBERG_COMPACTION_TYPE_AUTO,
250            CompactionType::Full => ICEBERG_COMPACTION_TYPE_FULL,
251            CompactionType::SmallFiles => ICEBERG_COMPACTION_TYPE_SMALL_FILES,
252            CompactionType::FilesWithDelete => ICEBERG_COMPACTION_TYPE_FILES_WITH_DELETE,
253        }
254    }
255}
256
257impl std::str::FromStr for CompactionType {
258    type Err = SinkError;
259
260    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
261        match s {
262            ICEBERG_COMPACTION_TYPE_AUTO => Ok(CompactionType::Auto),
263            ICEBERG_COMPACTION_TYPE_FULL => Ok(CompactionType::Full),
264            ICEBERG_COMPACTION_TYPE_SMALL_FILES => Ok(CompactionType::SmallFiles),
265            ICEBERG_COMPACTION_TYPE_FILES_WITH_DELETE => Ok(CompactionType::FilesWithDelete),
266            _ => Err(SinkError::Config(anyhow!(format!(
267                "invalid compaction_type: {}, must be one of: {}, {}, {}, {}",
268                s,
269                ICEBERG_COMPACTION_TYPE_AUTO,
270                ICEBERG_COMPACTION_TYPE_FULL,
271                ICEBERG_COMPACTION_TYPE_SMALL_FILES,
272                ICEBERG_COMPACTION_TYPE_FILES_WITH_DELETE
273            )))),
274        }
275    }
276}
277
278impl TryFrom<&str> for CompactionType {
279    type Error = <Self as std::str::FromStr>::Err;
280
281    fn try_from(value: &str) -> std::result::Result<Self, Self::Error> {
282        value.parse()
283    }
284}
285
286impl TryFrom<String> for CompactionType {
287    type Error = <Self as std::str::FromStr>::Err;
288
289    fn try_from(value: String) -> std::result::Result<Self, Self::Error> {
290        value.as_str().parse()
291    }
292}
293
294impl std::fmt::Display for CompactionType {
295    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
296        write!(f, "{}", self.as_str())
297    }
298}
299
300#[serde_as]
301#[derive(Debug, Clone, PartialEq, Eq, Deserialize, WithOptions)]
302pub struct IcebergConfig {
303    pub r#type: String, // accept "append-only" or "upsert"
304
305    #[serde(default, deserialize_with = "deserialize_bool_from_string")]
306    pub force_append_only: bool,
307
308    #[serde(flatten)]
309    pub(crate) common: IcebergCommon,
310
311    #[serde(flatten)]
312    pub(crate) table: IcebergTableIdentifier,
313
314    #[serde(
315        rename = "primary_key",
316        default,
317        deserialize_with = "deserialize_optional_string_seq_from_string"
318    )]
319    pub primary_key: Option<Vec<String>>,
320
321    // Props for java catalog props.
322    #[serde(skip)]
323    pub java_catalog_props: HashMap<String, String>,
324
325    #[serde(default)]
326    #[with_option(iceberg_engine)]
327    pub partition_by: Option<String>,
328
329    #[serde(default)]
330    #[with_option(iceberg_engine)]
331    pub order_key: Option<String>,
332
333    /// Commit every n(>0) checkpoints, default is 60.
334    #[serde(default = "iceberg_default_commit_checkpoint_interval")]
335    #[serde_as(as = "DisplayFromStr")]
336    #[with_option(allow_alter_on_fly, iceberg_engine)]
337    pub commit_checkpoint_interval: u64,
338
339    #[serde(default, deserialize_with = "deserialize_bool_from_string")]
340    pub create_table_if_not_exists: bool,
341
342    /// For REST catalogs such as AWS Glue, derive a missing table location from the
343    /// namespace's `location` property. Defaults to false. An existing location
344    /// derived from `warehouse.path` takes precedence; a missing or empty namespace
345    /// location leaves server-side location assignment unchanged.
346    #[serde(default, deserialize_with = "deserialize_bool_from_string")]
347    pub default_table_location_from_namespace: bool,
348
349    /// Whether it is `exactly_once`, the default is true.
350    #[serde(default = "default_some_true")]
351    #[serde_as(as = "Option<DisplayFromStr>")]
352    pub is_exactly_once: Option<bool>,
353    // Retry commit num when iceberg commit fail. default is 8.
354    // # TODO
355    // Iceberg table may store the retry commit num in table meta.
356    // We should try to find and use that as default commit retry num first.
357    #[serde(default = "default_commit_retry_num")]
358    pub commit_retry_num: u32,
359
360    /// Whether to enable iceberg compaction.
361    #[serde(
362        rename = "enable_compaction",
363        default,
364        deserialize_with = "deserialize_bool_from_string"
365    )]
366    #[with_option(allow_alter_on_fly, iceberg_engine)]
367    pub enable_compaction: bool,
368
369    /// The interval of iceberg compaction
370    #[serde(rename = "compaction_interval_sec", default)]
371    #[serde_as(as = "Option<DisplayFromStr>")]
372    #[with_option(allow_alter_on_fly, iceberg_engine)]
373    pub compaction_interval_sec: Option<u64>,
374
375    /// Whether to enable iceberg expired snapshots.
376    #[serde(
377        rename = "enable_snapshot_expiration",
378        default = "default_true",
379        deserialize_with = "deserialize_bool_from_string"
380    )]
381    #[with_option(allow_alter_on_fly, iceberg_engine)]
382    pub enable_snapshot_expiration: bool,
383
384    /// The iceberg write mode, can be `merge-on-read` or `copy-on-write`.
385    #[serde(rename = "write_mode", default = "default_iceberg_write_mode")]
386    #[with_option(iceberg_engine)]
387    pub write_mode: IcebergWriteMode,
388
389    /// Iceberg format version for table creation.
390    #[serde(
391        rename = "format_version",
392        default = "default_iceberg_format_version",
393        deserialize_with = "deserialize_format_version"
394    )]
395    #[with_option(iceberg_engine)]
396    pub format_version: FormatVersion,
397
398    /// The maximum age (in milliseconds) for snapshots before they expire
399    /// For example, if set to 3600000, snapshots older than 1 hour will be expired
400    #[serde(rename = "snapshot_expiration_max_age_millis", default)]
401    #[serde_as(as = "Option<DisplayFromStr>")]
402    #[with_option(allow_alter_on_fly, iceberg_engine)]
403    pub snapshot_expiration_max_age_millis: Option<i64>,
404
405    /// The number of snapshots to retain
406    #[serde(rename = "snapshot_expiration_retain_last", default)]
407    #[serde_as(as = "Option<DisplayFromStr>")]
408    #[with_option(allow_alter_on_fly, iceberg_engine)]
409    pub snapshot_expiration_retain_last: Option<i32>,
410
411    #[serde(
412        rename = "snapshot_expiration_clear_expired_files",
413        default = "default_true",
414        deserialize_with = "deserialize_bool_from_string"
415    )]
416    #[with_option(allow_alter_on_fly, iceberg_engine)]
417    pub snapshot_expiration_clear_expired_files: bool,
418
419    #[serde(
420        rename = "snapshot_expiration_clear_expired_meta_data",
421        default = "default_true",
422        deserialize_with = "deserialize_bool_from_string"
423    )]
424    #[with_option(allow_alter_on_fly, iceberg_engine)]
425    pub snapshot_expiration_clear_expired_meta_data: bool,
426
427    /// Whether to periodically rewrite fragmented Iceberg data manifests.
428    #[serde(
429        rename = "enable_manifest_rewrite",
430        default,
431        deserialize_with = "deserialize_bool_from_string"
432    )]
433    #[with_option(allow_alter_on_fly, iceberg_engine)]
434    pub enable_manifest_rewrite: bool,
435
436    /// Target size in bytes for rewritten Iceberg data manifests.
437    #[serde(rename = "manifest_rewrite_target_size_bytes", default)]
438    #[serde_as(as = "Option<DisplayFromStr>")]
439    #[with_option(allow_alter_on_fly, iceberg_engine)]
440    pub manifest_rewrite_target_size_bytes: Option<u64>,
441
442    /// Minimum number of manifests required to rewrite an under-filled batch.
443    #[serde(rename = "manifest_rewrite_min_count_to_merge", default)]
444    #[serde_as(as = "Option<DisplayFromStr>")]
445    #[with_option(allow_alter_on_fly, iceberg_engine)]
446    pub manifest_rewrite_min_count_to_merge: Option<usize>,
447
448    /// Whether to periodically remove files that are unreachable from Iceberg metadata.
449    /// Cleanup runs on the global Iceberg orphan-file cleanup interval.
450    #[serde(
451        rename = "enable_orphan_file_cleanup",
452        default,
453        deserialize_with = "deserialize_bool_from_string"
454    )]
455    #[with_option(allow_alter_on_fly, iceberg_engine)]
456    pub enable_orphan_file_cleanup: bool,
457
458    /// Minimum file age in milliseconds before an unreachable file may be removed.
459    /// Defaults to 7 days and must be at least 24 hours.
460    #[serde(rename = "orphan_file_cleanup_min_age_millis", default)]
461    #[serde_as(as = "Option<DisplayFromStr>")]
462    #[with_option(allow_alter_on_fly, iceberg_engine)]
463    pub orphan_file_cleanup_min_age_millis: Option<u64>,
464
465    /// The maximum number of snapshots allowed since the last rewrite operation
466    /// If set, sink will check snapshot count and wait if exceeded
467    /// If unset, defaults to 1000 only when compaction is enabled
468    #[serde(rename = "compaction.max_snapshots_num", default)]
469    #[serde_as(as = "Option<DisplayFromStr>")]
470    #[with_option(allow_alter_on_fly, iceberg_engine)]
471    pub max_snapshots_num_before_compaction: Option<usize>,
472
473    #[serde(rename = "compaction.small_files_threshold_mb", default)]
474    #[serde_as(as = "Option<DisplayFromStr>")]
475    #[with_option(allow_alter_on_fly, iceberg_engine)]
476    pub small_files_threshold_mb: Option<u64>,
477
478    #[serde(rename = "compaction.delete_files_count_threshold", default)]
479    #[serde_as(as = "Option<DisplayFromStr>")]
480    #[with_option(allow_alter_on_fly, iceberg_engine)]
481    pub delete_files_count_threshold: Option<usize>,
482
483    /// Minimum percentage of deleted physical rows for PK-index compaction.
484    #[serde(rename = "compaction.delete_ratio_percent", default)]
485    #[serde_as(as = "Option<DisplayFromStr>")]
486    #[with_option(allow_alter_on_fly, iceberg_engine)]
487    pub delete_ratio_percent: Option<u32>,
488
489    #[serde(rename = "compaction.trigger_snapshot_count", default)]
490    #[serde_as(as = "Option<DisplayFromStr>")]
491    #[with_option(allow_alter_on_fly, iceberg_engine)]
492    pub trigger_snapshot_count: Option<usize>,
493
494    #[serde(rename = "compaction.target_file_size_mb", default)]
495    #[serde_as(as = "Option<DisplayFromStr>")]
496    #[with_option(allow_alter_on_fly, iceberg_engine)]
497    pub target_file_size_mb: Option<u64>,
498
499    /// Compaction type: `auto`, `full`, `small-files`, or `files-with-delete`
500    /// If not set, defaults to `auto` when Iceberg compaction is licensed, otherwise `full`
501    #[serde(rename = "compaction.type", default)]
502    #[with_option(allow_alter_on_fly, iceberg_engine)]
503    pub compaction_type: Option<CompactionType>,
504
505    /// Parquet compression codec
506    /// Supported values: uncompressed, snappy, gzip, lzo, brotli, lz4, zstd
507    /// Default is zstd
508    #[serde(rename = "compaction.write_parquet_compression", default)]
509    #[with_option(allow_alter_on_fly, iceberg_engine)]
510    pub write_parquet_compression: Option<String>,
511
512    /// Deprecated: maximum number of rows in a Parquet row group.
513    /// Accepted for backward compatibility, but ignored by the writer.
514    #[serde(rename = "compaction.write_parquet_max_row_group_rows", default)]
515    #[serde_as(as = "Option<DisplayFromStr>")]
516    #[with_option(allow_alter_on_fly, iceberg_engine)]
517    pub write_parquet_max_row_group_rows: Option<usize>,
518
519    /// Maximum size of a Parquet row group in bytes
520    /// Default is 128 `MiB`, matching Iceberg defaults.
521    #[serde(rename = "compaction.write_parquet_max_row_group_bytes", default)]
522    #[serde_as(as = "Option<DisplayFromStr>")]
523    #[with_option(allow_alter_on_fly, iceberg_engine)]
524    pub write_parquet_max_row_group_bytes: Option<usize>,
525
526    /// Whether to enable PK index for upsert sink. Default is false.
527    /// For upsert iceberg sinks (V2/V3, merge-on-read): maintain a pk index and write
528    /// position deletes instead of equality deletes.
529    #[serde(
530        rename = "enable_pk_index",
531        default,
532        deserialize_with = "deserialize_bool_from_string"
533    )]
534    #[with_option(iceberg_engine)]
535    pub enable_pk_index: bool,
536
537    /// Whether the PK index of a pk-index sink stores full data file paths. Default is true.
538    /// When false, the sink writes every data file as `{data_location}/{uuid}.parquet` and the
539    /// PK index only stores the 16-byte uuid, from which the path is rebuilt. New pk-index sinks
540    /// are created with false; sinks created before this option existed keep the legacy layout.
541    /// It must not change after the sink is created.
542    ///
543    /// While it is false, the table's data location must never change: neither the
544    /// `write.data.path` or `write.folder-storage.path` table property nor the table location.
545    /// RisingWave never changes them, but it cannot stop other engines from doing so. After such
546    /// a change, uuids already in the PK index rebuild paths that do not exist, and the position
547    /// deletes written for those rows silently have no effect.
548    #[serde(
549        rename = "legacy_pk_index_file_path",
550        default = "default_true",
551        deserialize_with = "deserialize_bool_from_string"
552    )]
553    pub legacy_pk_index_file_path: bool,
554
555    #[serde(flatten)]
556    pub unknown_fields: std::collections::HashMap<String, String>,
557}
558
559crate::impl_sink_unknown_fields!(IcebergConfig);
560
561impl EnforceSecret for IcebergConfig {
562    fn enforce_secret<'a>(
563        prop_iter: impl Iterator<Item = &'a str>,
564    ) -> crate::error::ConnectorResult<()> {
565        for prop in prop_iter {
566            IcebergCommon::enforce_one(prop)?;
567        }
568        Ok(())
569    }
570
571    fn enforce_one(prop: &str) -> crate::error::ConnectorResult<()> {
572        IcebergCommon::enforce_one(prop)
573    }
574}
575
576impl IcebergConfig {
577    /// Validate that append-only sinks use merge-on-read mode
578    /// Copy-on-write is strictly worse than merge-on-read for append-only workloads
579    pub fn validate_append_only_write_mode(
580        sink_type: &str,
581        write_mode: IcebergWriteMode,
582    ) -> Result<()> {
583        if sink_type == SINK_TYPE_APPEND_ONLY && write_mode == IcebergWriteMode::CopyOnWrite {
584            return Err(SinkError::Config(anyhow!(
585                "'copy-on-write' mode is not supported for append-only iceberg sink. \
586                 Please use 'merge-on-read' instead, which is strictly better for append-only workloads."
587            )));
588        }
589        Ok(())
590    }
591
592    /// Whether this is a pk-index sink whose PK index stores data file uuids instead of paths.
593    pub fn pk_index_stores_file_uuid(&self) -> bool {
594        self.enable_pk_index && !self.legacy_pk_index_file_path
595    }
596
597    pub(crate) fn validate_enable_pk_index(&self) -> Result<()> {
598        if !self.enable_pk_index {
599            return Ok(());
600        }
601
602        if self.r#type != SINK_TYPE_UPSERT {
603            return Err(SinkError::Config(anyhow!(
604                "`enable_pk_index` is only supported for upsert iceberg sink"
605            )));
606        }
607
608        if self.write_mode != IcebergWriteMode::MergeOnRead {
609            return Err(SinkError::Config(anyhow!(
610                "`enable_pk_index` is only supported for upsert iceberg sink with merge-on-read mode"
611            )));
612        }
613
614        if self.format_version < FormatVersion::V2 {
615            return Err(SinkError::Config(anyhow!(
616                "`enable_pk_index` is only supported for upsert iceberg sink with format version >= 2"
617            )));
618        }
619
620        if self.force_append_only {
621            return Err(SinkError::Config(anyhow!(
622                "`enable_pk_index` cannot be true when `force_append_only` is true"
623            )));
624        }
625
626        Ok(())
627    }
628
629    pub fn from_btreemap(values: BTreeMap<String, String>) -> Result<Self> {
630        let mut config =
631            serde_json::from_value::<IcebergConfig>(serde_json::to_value(&values).unwrap())
632                .map_err(|e| SinkError::Config(anyhow!(e)))?;
633
634        if config.enable_compaction && !values.contains_key(COMPACTION_MAX_SNAPSHOTS_NUM) {
635            config.max_snapshots_num_before_compaction = Some(DEFAULT_COMPACTION_MAX_SNAPSHOTS_NUM);
636        }
637
638        if config.r#type != SINK_TYPE_APPEND_ONLY && config.r#type != SINK_TYPE_UPSERT {
639            return Err(SinkError::Config(anyhow!(
640                "`{}` must be {}, or {}",
641                SINK_TYPE_OPTION,
642                SINK_TYPE_APPEND_ONLY,
643                SINK_TYPE_UPSERT
644            )));
645        }
646
647        if config.r#type == SINK_TYPE_UPSERT {
648            if let Some(primary_key) = &config.primary_key {
649                if primary_key.is_empty() {
650                    return Err(SinkError::Config(anyhow!(
651                        "`primary-key` must not be empty in {}",
652                        SINK_TYPE_UPSERT
653                    )));
654                }
655            } else if !config.enable_pk_index {
656                // When `enable_pk_index = true`, the planner auto-derives the iceberg pk
657                // from the upstream stream key, so the user does not need to spell it out
658                // in WITH options. The derived pk is written back into properties before
659                // this validation is consulted again at sink-construction time.
660                return Err(SinkError::Config(anyhow!(
661                    "Must set `primary-key` in {}",
662                    SINK_TYPE_UPSERT
663                )));
664            }
665        }
666
667        // Enforce merge-on-read for append-only sinks
668        Self::validate_append_only_write_mode(&config.r#type, config.write_mode)?;
669        config.validate_enable_pk_index()?;
670        config.validate_manifest_rewrite_format(config.format_version)?;
671
672        if config.default_table_location_from_namespace && !config.common.is_rest_catalog()? {
673            return Err(SinkError::Config(anyhow!(
674                "`default_table_location_from_namespace` is only supported for REST catalogs"
675            )));
676        }
677
678        // All configs start with "catalog." will be treated as java configs.
679        config.java_catalog_props = iceberg_java_catalog_props_from_options(
680            values
681                .iter()
682                .map(|(key, value)| (key.as_str(), value.as_str())),
683        );
684        config
685            .unknown_fields
686            .retain(|key, _| key != "connector" && !key.starts_with("catalog."));
687
688        if config.commit_checkpoint_interval == 0 {
689            return Err(SinkError::Config(anyhow!(
690                "`commit-checkpoint-interval` must be greater than 0"
691            )));
692        }
693
694        if config.compaction_interval_sec == Some(0) {
695            return Err(SinkError::Config(anyhow!(
696                "`compaction_interval_sec` must be greater than 0"
697            )));
698        }
699
700        if config.trigger_snapshot_count == Some(0) {
701            return Err(SinkError::Config(anyhow!(
702                "`compaction.trigger_snapshot_count` must be greater than 0"
703            )));
704        }
705
706        if config.max_snapshots_num_before_compaction == Some(0) {
707            return Err(SinkError::Config(anyhow!(
708                "`compaction.max_snapshots_num` must be greater than 0"
709            )));
710        }
711
712        if config.small_files_threshold_mb == Some(0) {
713            return Err(SinkError::Config(anyhow!(
714                "`compaction.small_files_threshold_mb` must be greater than 0"
715            )));
716        }
717
718        if config.delete_files_count_threshold == Some(0) {
719            return Err(SinkError::Config(anyhow!(
720                "`compaction.delete_files_count_threshold` must be greater than 0"
721            )));
722        }
723
724        if config
725            .delete_ratio_percent
726            .is_some_and(|percent| !(1..=100).contains(&percent))
727        {
728            return Err(SinkError::Config(anyhow!(
729                "`compaction.delete_ratio_percent` must be between 1 and 100"
730            )));
731        }
732
733        if config.target_file_size_mb == Some(0) {
734            return Err(SinkError::Config(anyhow!(
735                "`compaction.target_file_size_mb` must be greater than 0"
736            )));
737        }
738
739        if config.write_parquet_max_row_group_rows == Some(0) {
740            return Err(SinkError::Config(anyhow!(
741                "`compaction.write_parquet_max_row_group_rows` must be greater than 0"
742            )));
743        }
744
745        if config.write_parquet_max_row_group_bytes == Some(0) {
746            return Err(SinkError::Config(anyhow!(
747                "`compaction.write_parquet_max_row_group_bytes` must be greater than 0"
748            )));
749        }
750
751        if config.manifest_rewrite_target_size_bytes == Some(0) {
752            return Err(SinkError::Config(anyhow!(
753                "`manifest_rewrite_target_size_bytes` must be greater than 0"
754            )));
755        }
756
757        if config.manifest_rewrite_min_count_to_merge == Some(0) {
758            return Err(SinkError::Config(anyhow!(
759                "`manifest_rewrite_min_count_to_merge` must be greater than 0"
760            )));
761        }
762
763        if config
764            .orphan_file_cleanup_min_age_millis
765            .is_some_and(|min_age_millis| {
766                min_age_millis < ORPHAN_FILE_CLEANUP_MIN_AGE_MILLIS_MINIMUM
767            })
768        {
769            return Err(SinkError::Config(anyhow!(
770                "`orphan_file_cleanup_min_age_millis` must be at least {} (24 hours)",
771                ORPHAN_FILE_CLEANUP_MIN_AGE_MILLIS_MINIMUM
772            )));
773        }
774
775        if config.enable_orphan_file_cleanup || config.orphan_file_cleanup_min_age_millis.is_some()
776        {
777            config.ensure_orphan_file_cleanup_supported()?;
778        }
779
780        // Validate table identifier (e.g., database.name should not contain dots)
781        config
782            .table
783            .validate()
784            .map_err(|e| SinkError::Config(anyhow!(e)))?;
785
786        if config.write_parquet_max_row_group_rows.is_some() {
787            tracing::warn!(
788                "`compaction.write_parquet_max_row_group_rows` is deprecated and ignored; use `compaction.write_parquet_max_row_group_bytes` instead"
789            );
790        }
791
792        Ok(config)
793    }
794
795    pub fn catalog_type(&self) -> &str {
796        self.common.catalog_type()
797    }
798
799    pub fn catalog_kind(&self) -> Result<IcebergCatalogKind> {
800        self.common
801            .resolve_catalog_kind()
802            .map_err(|err| SinkError::Config(anyhow!(err)))
803    }
804
805    pub fn ensure_orphan_file_cleanup_supported(&self) -> Result<()> {
806        if matches!(self.catalog_kind()?, IcebergCatalogKind::Storage) {
807            return Err(SinkError::Config(anyhow!(
808                "Iceberg orphan file cleanup is not supported for `catalog.type = 'storage'`"
809            )));
810        }
811
812        Ok(())
813    }
814
815    fn resolved_catalog_config(&self) -> Result<ResolvedIcebergCatalogConfig<'_>> {
816        self.common
817            .resolve_catalog_config(self.java_catalog_props.clone())
818            .map_err(|err| SinkError::Config(anyhow!(err)))
819    }
820
821    pub async fn load_table(&self) -> Result<Table> {
822        #[cfg(any(test, madsim))]
823        if self.catalog_type() == "mock_v3" {
824            let catalog =
825                crate::sink::iceberg::mock_v3_catalog_registry::get().ok_or_else(|| {
826                    SinkError::Config(anyhow!(
827                        "mock_v3 catalog_type set but no mock catalog registered"
828                    ))
829                })?;
830            let table_id = self
831                .table
832                .to_table_ident()
833                .map_err(|e| SinkError::Config(anyhow!(e).context("Unable to parse table name")))?;
834            let table = catalog
835                .load_table(&table_id)
836                .await
837                .map_err(|e| SinkError::Config(anyhow!(e).context("Failed to load mock table")))?;
838            return Ok(table);
839        }
840        self.resolved_catalog_config()?
841            .load_table(&self.table)
842            .await
843            .map_err(Into::into)
844    }
845
846    pub async fn create_catalog(&self) -> Result<Arc<dyn Catalog>> {
847        #[cfg(any(test, madsim))]
848        if self.catalog_type() == "mock_v3" {
849            return Ok(
850                crate::sink::iceberg::mock_v3_catalog_registry::get().ok_or_else(|| {
851                    anyhow::anyhow!("mock_v3 catalog_type set but no mock catalog registered")
852                })?,
853            );
854        }
855        self.resolved_catalog_config()?
856            .create_catalog()
857            .await
858            .map_err(Into::into)
859    }
860
861    pub fn full_table_name(&self) -> Result<TableIdent> {
862        self.table.to_table_ident().map_err(Into::into)
863    }
864
865    pub fn catalog_name(&self) -> String {
866        self.common.catalog_name()
867    }
868
869    pub fn table_format_version(&self) -> FormatVersion {
870        self.format_version
871    }
872
873    pub fn validate_manifest_rewrite_format(&self, format_version: FormatVersion) -> Result<()> {
874        if self.enable_manifest_rewrite && format_version >= FormatVersion::V3 {
875            return Err(SinkError::Config(anyhow!(
876                "`enable_manifest_rewrite` is not supported for Iceberg format version 3 because rewrite manifests cannot preserve row lineage"
877            )));
878        }
879        Ok(())
880    }
881
882    pub fn compaction_interval_sec(&self) -> u64 {
883        // default to 1 hour
884        self.compaction_interval_sec.unwrap_or(3600)
885    }
886
887    /// Calculate the timestamp (in milliseconds) before which snapshots should be expired
888    /// Returns `current_time_ms` - `max_age_millis`
889    pub fn snapshot_expiration_timestamp_ms(&self, current_time_ms: i64) -> Option<i64> {
890        self.snapshot_expiration_max_age_millis
891            .map(|max_age_millis| current_time_ms - max_age_millis)
892    }
893
894    pub fn manifest_rewrite_target_size_bytes(&self) -> u64 {
895        self.manifest_rewrite_target_size_bytes
896            .unwrap_or(MANIFEST_TARGET_SIZE_BYTES_DEFAULT as u64)
897    }
898
899    pub fn manifest_rewrite_min_count_to_merge(&self) -> usize {
900        self.manifest_rewrite_min_count_to_merge
901            .unwrap_or(MANIFEST_MIN_MERGE_COUNT_DEFAULT as usize)
902    }
903
904    pub fn orphan_file_cleanup_min_age_millis(&self) -> u64 {
905        self.orphan_file_cleanup_min_age_millis
906            .unwrap_or(ORPHAN_FILE_CLEANUP_MIN_AGE_MILLIS_DEFAULT)
907    }
908
909    pub fn trigger_snapshot_count(&self) -> usize {
910        self.trigger_snapshot_count.unwrap_or(usize::MAX)
911    }
912
913    pub fn small_files_threshold_mb(&self) -> u64 {
914        self.small_files_threshold_mb.unwrap_or(64)
915    }
916
917    pub fn delete_files_count_threshold(&self) -> usize {
918        self.delete_files_count_threshold.unwrap_or(256)
919    }
920
921    pub fn delete_ratio_percent(&self) -> u32 {
922        self.delete_ratio_percent.unwrap_or(30)
923    }
924
925    pub fn target_file_size_mb(&self) -> u64 {
926        self.target_file_size_mb.unwrap_or(1024)
927    }
928
929    /// Get the parquet compression codec
930    /// Default is "zstd"
931    pub fn write_parquet_compression(&self) -> &str {
932        self.write_parquet_compression.as_deref().unwrap_or("zstd")
933    }
934
935    /// Get the maximum number of rows in a Parquet row group.
936    pub fn write_parquet_max_row_group_rows(&self) -> Option<usize> {
937        self.write_parquet_max_row_group_rows
938    }
939
940    /// Get the maximum size in bytes of a Parquet row group.
941    pub fn write_parquet_max_row_group_bytes(&self) -> Option<usize> {
942        self.write_parquet_max_row_group_bytes
943            .or(Some(ICEBERG_DEFAULT_WRITE_PARQUET_MAX_ROW_GROUP_BYTES))
944    }
945
946    /// Parse the compression codec string into Parquet Compression enum.
947    /// Invalid values fall back to SNAPPY.
948    pub fn get_parquet_compression(&self) -> Compression {
949        parse_parquet_compression(self.write_parquet_compression())
950    }
951}
952
953/// Parse compression codec string to Parquet Compression enum
954pub fn parse_parquet_compression(codec: &str) -> Compression {
955    match codec.to_lowercase().as_str() {
956        "uncompressed" => Compression::UNCOMPRESSED,
957        "snappy" => Compression::SNAPPY,
958        "gzip" => Compression::GZIP(Default::default()),
959        "lzo" => Compression::LZO,
960        "brotli" => Compression::BROTLI(Default::default()),
961        "lz4" => Compression::LZ4,
962        "zstd" => Compression::ZSTD(Default::default()),
963        _ => {
964            tracing::warn!(
965                "Unknown compression codec '{}', falling back to SNAPPY",
966                codec
967            );
968            Compression::SNAPPY
969        }
970    }
971}
972
973// Helper Functions
974
975pub fn commit_branch(sink_type: &str, write_mode: IcebergWriteMode) -> String {
976    if should_enable_iceberg_cow(sink_type, write_mode) {
977        ICEBERG_COW_BRANCH.to_owned()
978    } else {
979        MAIN_BRANCH.to_owned()
980    }
981}
982
983pub fn should_enable_iceberg_cow(sink_type: &str, write_mode: IcebergWriteMode) -> bool {
984    sink_type == SINK_TYPE_UPSERT && write_mode == IcebergWriteMode::CopyOnWrite
985}
986
987impl crate::with_options::WithOptions for IcebergWriteMode {}
988
989impl crate::with_options::WithOptions for FormatVersion {}
990
991impl crate::with_options::WithOptions for CompactionType {}