risingwave_common/config/
mod.rs

1// Copyright 2025 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
15//! This pub module defines the structure of the configuration file `risingwave.toml`.
16//!
17//! [`RwConfig`] corresponds to the whole config file and each other config struct corresponds to a
18//! section in `risingwave.toml`.
19
20pub mod batch;
21pub use batch::BatchConfig;
22pub mod frontend;
23pub use frontend::FrontendConfig;
24pub mod hba;
25pub use hba::{AddressPattern, AuthMethod, ConnectionType, HbaConfig, HbaEntry};
26pub mod meta;
27pub use meta::{
28    CheckpointCompression, CompactionConfig, DefaultParallelism, MetaBackend, MetaConfig,
29    MetaStoreConfig,
30};
31pub mod streaming;
32pub use streaming::{AsyncStackTraceOption, StreamingConfig};
33pub mod server;
34pub use server::{HeapProfilingConfig, ServerConfig};
35pub mod udf;
36pub use udf::UdfConfig;
37pub mod storage;
38pub use storage::{
39    CacheEvictionConfig, EvictionConfig, ObjectStoreConfig, StorageConfig, StorageMemoryConfig,
40    extract_storage_memory_config,
41};
42pub mod merge;
43pub mod mutate;
44pub mod none_as_empty_string;
45pub mod system;
46pub mod utils;
47
48use std::collections::BTreeMap;
49use std::fs;
50use std::num::NonZeroUsize;
51
52use anyhow::Context;
53use clap::ValueEnum;
54use educe::Educe;
55pub use merge::*;
56use risingwave_common_proc_macro::ConfigDoc;
57pub use risingwave_common_proc_macro::OverrideConfig;
58use risingwave_pb::meta::SystemParams;
59use serde::{Deserialize, Serialize, Serializer};
60use serde_default::DefaultFromSerde;
61use serde_json::Value;
62pub use system::SystemConfig;
63pub use utils::*;
64
65use crate::for_all_params;
66
67/// Use the maximum value for HTTP/2 connection window size to avoid deadlock among multiplexed
68/// streams on the same connection.
69pub const MAX_CONNECTION_WINDOW_SIZE: u32 = (1 << 31) - 1;
70/// Use a large value for HTTP/2 stream window size to improve the performance of remote exchange,
71/// as we don't rely on this for back-pressure.
72pub const STREAM_WINDOW_SIZE: u32 = 32 * 1024 * 1024; // 32 MB
73
74/// [`RwConfig`] corresponds to the whole config file `risingwave.toml`. Each field corresponds to a
75/// section.
76#[derive(Educe, Clone, Serialize, Deserialize, Default, ConfigDoc)]
77#[educe(Debug)]
78pub struct RwConfig {
79    #[serde(default)]
80    #[config_doc(nested)]
81    pub server: ServerConfig,
82
83    #[serde(default)]
84    #[config_doc(nested)]
85    pub meta: MetaConfig,
86
87    #[serde(default)]
88    #[config_doc(nested)]
89    pub batch: BatchConfig,
90
91    #[serde(default)]
92    #[config_doc(nested)]
93    pub frontend: FrontendConfig,
94
95    #[serde(default)]
96    #[config_doc(nested)]
97    pub streaming: StreamingConfig,
98
99    #[serde(default)]
100    #[config_doc(nested)]
101    pub storage: StorageConfig,
102
103    #[serde(default)]
104    #[educe(Debug(ignore))]
105    #[config_doc(nested)]
106    pub system: SystemConfig,
107
108    #[serde(default)]
109    #[config_doc(nested)]
110    pub udf: UdfConfig,
111
112    #[serde(flatten)]
113    #[config_doc(omitted)]
114    pub unrecognized: Unrecognized<Self>,
115}
116
117/// `[meta.developer.meta_compute_client_config]`
118/// `[meta.developer.meta_stream_client_config]`
119/// `[meta.developer.meta_frontend_client_config]`
120/// `[batch.developer.batch_compute_client_config]`
121/// `[batch.developer.batch_frontend_client_config]`
122/// `[streaming.developer.stream_compute_client_config]`
123#[serde_with::apply(Option => #[serde(with = "none_as_empty_string")])]
124#[derive(Clone, Debug, Serialize, Deserialize, DefaultFromSerde, ConfigDoc)]
125pub struct RpcClientConfig {
126    #[serde(default = "default::developer::rpc_client_connect_timeout_secs")]
127    pub connect_timeout_secs: u64,
128    /// Maximum concurrency when setting up an RPC client pool.
129    /// Set to 0 to keep the previous unlimited behavior.
130    #[serde(default = "default::developer::rpc_client_pool_setup_concurrency")]
131    pub pool_setup_concurrency: usize,
132}
133
134pub use risingwave_common_metrics::MetricLevel;
135
136impl RwConfig {
137    pub const fn default_connection_pool_size(&self) -> u16 {
138        self.server.connection_pool_size
139    }
140
141    /// Returns [`streaming::StreamingDeveloperConfig::exchange_connection_pool_size`] if set,
142    /// otherwise [`ServerConfig::connection_pool_size`].
143    pub fn streaming_exchange_connection_pool_size(&self) -> u16 {
144        self.streaming
145            .developer
146            .exchange_connection_pool_size
147            .unwrap_or_else(|| self.default_connection_pool_size())
148    }
149
150    /// Returns [`batch::BatchDeveloperConfig::exchange_connection_pool_size`] if set,
151    /// otherwise [`ServerConfig::connection_pool_size`].
152    pub fn batch_exchange_connection_pool_size(&self) -> u16 {
153        self.batch
154            .developer
155            .exchange_connection_pool_size
156            .unwrap_or_else(|| self.default_connection_pool_size())
157    }
158}
159
160pub mod default {
161
162    pub mod developer {
163        pub fn meta_cached_traces_num() -> u32 {
164            256
165        }
166
167        pub fn meta_cached_traces_memory_limit_bytes() -> usize {
168            1 << 27 // 128 MiB
169        }
170
171        pub fn batch_output_channel_size() -> usize {
172            64
173        }
174
175        pub fn batch_receiver_channel_size() -> usize {
176            1000
177        }
178
179        pub fn batch_root_stage_channel_size() -> usize {
180            100
181        }
182
183        pub fn batch_chunk_size() -> usize {
184            1024
185        }
186
187        pub fn batch_local_execute_buffer_size() -> usize {
188            64
189        }
190
191        /// Default to unset to be compatible with the behavior before this config is introduced,
192        /// that is, follow the value of `server.connection_pool_size`.
193        pub fn batch_exchange_connection_pool_size() -> Option<u16> {
194            None
195        }
196
197        pub fn stream_enable_executor_row_count() -> bool {
198            false
199        }
200
201        pub fn connector_message_buffer_size() -> usize {
202            16
203        }
204
205        pub fn unsafe_stream_extreme_cache_size() -> usize {
206            10
207        }
208
209        pub fn stream_topn_cache_min_capacity() -> usize {
210            10
211        }
212
213        pub fn stream_chunk_size() -> usize {
214            256
215        }
216
217        pub fn stream_exchange_initial_permits() -> usize {
218            2048
219        }
220
221        pub fn stream_exchange_batched_permits() -> usize {
222            256
223        }
224
225        pub fn stream_exchange_concurrent_barriers() -> usize {
226            1
227        }
228
229        pub fn stream_exchange_concurrent_dispatchers() -> usize {
230            0
231        }
232
233        pub fn stream_dml_channel_initial_permits() -> usize {
234            32768
235        }
236
237        pub fn stream_max_barrier_batch_size() -> u32 {
238            1024
239        }
240
241        pub fn stream_hash_agg_max_dirty_groups_heap_size() -> usize {
242            64 << 20 // 64MB
243        }
244
245        pub fn enable_trivial_move() -> bool {
246            true
247        }
248
249        pub fn enable_check_task_level_overlap() -> bool {
250            false
251        }
252
253        pub fn max_trivial_move_task_count_per_loop() -> usize {
254            256
255        }
256
257        pub fn max_get_task_probe_times() -> usize {
258            5
259        }
260
261        pub fn actor_cnt_per_worker_parallelism_soft_limit() -> usize {
262            100
263        }
264
265        pub fn actor_cnt_per_worker_parallelism_hard_limit() -> usize {
266            400
267        }
268
269        pub fn hummock_time_travel_sst_info_fetch_batch_size() -> usize {
270            10_000
271        }
272
273        pub fn hummock_time_travel_sst_info_insert_batch_size() -> usize {
274            100
275        }
276
277        pub fn time_travel_vacuum_interval_sec() -> u64 {
278            30
279        }
280
281        pub fn time_travel_vacuum_max_version_count() -> Option<u32> {
282            Some(10000)
283        }
284
285        pub fn hummock_time_travel_epoch_version_insert_batch_size() -> usize {
286            1000
287        }
288
289        pub fn hummock_gc_history_insert_batch_size() -> usize {
290            1000
291        }
292
293        pub fn hummock_time_travel_filter_out_objects_batch_size() -> usize {
294            1000
295        }
296
297        pub fn hummock_time_travel_filter_out_objects_v1() -> bool {
298            false
299        }
300
301        pub fn hummock_time_travel_filter_out_objects_list_version_batch_size() -> usize {
302            10
303        }
304
305        pub fn hummock_time_travel_filter_out_objects_list_delta_batch_size() -> usize {
306            1000
307        }
308
309        pub fn memory_controller_threshold_aggressive() -> f64 {
310            0.9
311        }
312
313        pub fn memory_controller_threshold_graceful() -> f64 {
314            0.81
315        }
316
317        pub fn memory_controller_threshold_stable() -> f64 {
318            0.72
319        }
320
321        pub fn memory_controller_eviction_factor_aggressive() -> f64 {
322            2.0
323        }
324
325        pub fn memory_controller_eviction_factor_graceful() -> f64 {
326            1.5
327        }
328
329        pub fn memory_controller_eviction_factor_stable() -> f64 {
330            1.0
331        }
332
333        pub fn memory_controller_update_interval_ms() -> usize {
334            100
335        }
336
337        pub fn memory_controller_sequence_tls_step() -> u64 {
338            128
339        }
340
341        pub fn memory_controller_sequence_tls_lag() -> u64 {
342            32
343        }
344
345        pub fn stream_enable_arrangement_backfill() -> bool {
346            true
347        }
348
349        pub fn stream_enable_snapshot_backfill() -> bool {
350            true
351        }
352
353        pub fn enable_shared_source() -> bool {
354            true
355        }
356
357        pub fn stream_high_join_amplification_threshold() -> usize {
358            2048
359        }
360
361        /// Default to 1 to be compatible with the behavior before this config is introduced.
362        pub fn stream_exchange_connection_pool_size() -> Option<u16> {
363            Some(1)
364        }
365
366        pub fn enable_actor_tokio_metrics() -> bool {
367            true
368        }
369
370        pub fn stream_enable_auto_schema_change() -> bool {
371            true
372        }
373
374        pub fn switch_jdbc_pg_to_native() -> bool {
375            false
376        }
377
378        pub fn streaming_hash_join_entry_state_max_rows() -> usize {
379            // NOTE(kwannoel): This is just an arbitrary number.
380            30000
381        }
382
383        pub fn streaming_join_hash_map_evict_interval_rows() -> u32 {
384            16
385        }
386
387        pub fn streaming_now_progress_ratio() -> Option<f32> {
388            None
389        }
390
391        pub fn stream_snapshot_iter_rebuild_interval_secs() -> u64 {
392            10 * 60
393        }
394
395        pub fn enable_explain_analyze_stats() -> bool {
396            true
397        }
398
399        pub fn rpc_client_connect_timeout_secs() -> u64 {
400            5
401        }
402
403        pub fn rpc_client_pool_setup_concurrency() -> usize {
404            0
405        }
406
407        pub fn iceberg_list_interval_sec() -> u64 {
408            10
409        }
410
411        pub fn iceberg_fetch_batch_size() -> u64 {
412            1024
413        }
414
415        pub fn iceberg_sink_positional_delete_cache_size() -> usize {
416            1024
417        }
418
419        pub fn iceberg_sink_write_parquet_max_row_group_rows() -> usize {
420            100_000
421        }
422
423        pub fn materialize_force_overwrite_on_no_check() -> bool {
424            false
425        }
426
427        pub fn refresh_scheduler_interval_sec() -> u64 {
428            60
429        }
430
431        pub fn sync_log_store_pause_duration_ms() -> usize {
432            64
433        }
434
435        pub fn sync_log_store_buffer_size() -> usize {
436            2048
437        }
438
439        pub fn table_change_log_insert_batch_size() -> u64 {
440            1000
441        }
442
443        pub fn table_change_log_delete_batch_size() -> u64 {
444            1000
445        }
446
447        pub fn enable_state_table_vnode_stats_pruning() -> bool {
448            false
449        }
450    }
451}
452
453pub const MAX_META_CACHE_SHARD_BITS: usize = 4;
454pub const MIN_BUFFER_SIZE_PER_SHARD: usize = 256;
455pub const MAX_BLOCK_CACHE_SHARD_BITS: usize = 6; // It means that there will be 64 shards lru-cache to avoid lock conflict.
456
457#[cfg(test)]
458pub mod tests {
459    use expect_test::expect;
460    use risingwave_license::LicenseKey;
461
462    use super::*;
463
464    fn default_config_for_docs() -> RwConfig {
465        let mut config = RwConfig::default();
466        // Set `license_key` to empty in the docs to avoid any confusion.
467        config.system.license_key = Some(LicenseKey::empty());
468        config
469    }
470
471    /// This test ensures that `config/example.toml` is up-to-date with the default values specified
472    /// in this file. Developer should run `./risedev generate-example-config` to update it if this
473    /// test fails.
474    #[test]
475    fn test_example_up_to_date() {
476        const HEADER: &str = "# This file is generated by ./risedev generate-example-config
477# Check detailed comments in src/common/src/config.rs";
478
479        let actual = expect_test::expect_file!["../../../config/example.toml"];
480        let default = toml::to_string(&default_config_for_docs()).expect("failed to serialize");
481
482        let expected = format!("{HEADER}\n\n{default}");
483        actual.assert_eq(&expected);
484
485        let expected = rw_config_to_markdown();
486        let actual = expect_test::expect_file!["../../../config/docs.md"];
487        actual.assert_eq(&expected);
488    }
489
490    #[derive(Debug)]
491    struct ConfigItemDoc {
492        desc: String,
493        default: String,
494    }
495
496    fn rw_config_to_markdown() -> String {
497        let mut config_rustdocs = BTreeMap::<String, Vec<(String, String)>>::new();
498        RwConfig::config_docs("".to_owned(), &mut config_rustdocs);
499
500        // Section -> Config Name -> ConfigItemDoc
501        let mut configs: BTreeMap<String, BTreeMap<String, ConfigItemDoc>> = config_rustdocs
502            .into_iter()
503            .map(|(k, v)| {
504                let docs: BTreeMap<String, ConfigItemDoc> = v
505                    .into_iter()
506                    .map(|(name, desc)| {
507                        (
508                            name,
509                            ConfigItemDoc {
510                                desc,
511                                default: "".to_owned(), // unset
512                            },
513                        )
514                    })
515                    .collect();
516                (k, docs)
517            })
518            .collect();
519
520        let toml_doc: BTreeMap<String, toml::Value> =
521            toml::from_str(&toml::to_string(&default_config_for_docs()).unwrap()).unwrap();
522        toml_doc.into_iter().for_each(|(name, value)| {
523            set_default_values("".to_owned(), name, value, &mut configs);
524        });
525
526        let mut markdown = "# RisingWave System Configurations\n\n".to_owned()
527            + "This page is automatically generated by `./risedev generate-example-config`\n";
528        for (section, configs) in configs {
529            if configs.is_empty() {
530                continue;
531            }
532            markdown.push_str(&format!("\n## {}\n\n", section));
533            markdown.push_str("| Config | Description | Default |\n");
534            markdown.push_str("|--------|-------------|---------|\n");
535            for (config, doc) in configs {
536                markdown.push_str(&format!(
537                    "| {} | {} | {} |\n",
538                    config, doc.desc, doc.default
539                ));
540            }
541        }
542        markdown
543    }
544
545    fn set_default_values(
546        section: String,
547        name: String,
548        value: toml::Value,
549        configs: &mut BTreeMap<String, BTreeMap<String, ConfigItemDoc>>,
550    ) {
551        // Set the default value if it's a config name-value pair, otherwise it's a sub-section (Table) that should be recursively processed.
552        if let toml::Value::Table(table) = value {
553            let section_configs: BTreeMap<String, toml::Value> = table.into_iter().collect();
554            let sub_section = if section.is_empty() {
555                name
556            } else {
557                format!("{}.{}", section, name)
558            };
559            section_configs
560                .into_iter()
561                .for_each(|(k, v)| set_default_values(sub_section.clone(), k, v, configs))
562        } else if let Some(t) = configs.get_mut(&section)
563            && let Some(item_doc) = t.get_mut(&name)
564        {
565            item_doc.default = format!("{}", value);
566        }
567    }
568
569    #[test]
570    fn test_object_store_configs_backward_compatibility() {
571        // Define configs with the old name and make sure it still works
572        {
573            let config: RwConfig = toml::from_str(
574                r#"
575            [storage.object_store]
576            object_store_set_atomic_write_dir = true
577
578            [storage.object_store.s3]
579            object_store_keepalive_ms = 1
580            object_store_send_buffer_size = 1
581            object_store_recv_buffer_size = 1
582            object_store_nodelay = false
583
584            [storage.object_store.s3.developer]
585            object_store_retry_unknown_service_error = true
586            object_store_retryable_service_error_codes = ['dummy']
587
588
589            "#,
590            )
591            .unwrap();
592
593            assert!(config.storage.object_store.set_atomic_write_dir);
594            assert_eq!(config.storage.object_store.s3.keepalive_ms, Some(1));
595            assert_eq!(config.storage.object_store.s3.send_buffer_size, Some(1));
596            assert_eq!(config.storage.object_store.s3.recv_buffer_size, Some(1));
597            assert_eq!(config.storage.object_store.s3.nodelay, Some(false));
598            assert!(
599                config
600                    .storage
601                    .object_store
602                    .s3
603                    .developer
604                    .retry_unknown_service_error
605            );
606            assert_eq!(
607                config
608                    .storage
609                    .object_store
610                    .s3
611                    .developer
612                    .retryable_service_error_codes,
613                vec!["dummy".to_owned()]
614            );
615        }
616
617        // Define configs with the new name and make sure it works
618        {
619            let config: RwConfig = toml::from_str(
620                r#"
621            [storage.object_store]
622            set_atomic_write_dir = true
623
624            [storage.object_store.s3]
625            keepalive_ms = 1
626            send_buffer_size = 1
627            recv_buffer_size = 1
628            nodelay = false
629
630            [storage.object_store.s3.developer]
631            retry_unknown_service_error = true
632            retryable_service_error_codes = ['dummy']
633
634
635            "#,
636            )
637            .unwrap();
638
639            assert!(config.storage.object_store.set_atomic_write_dir);
640            assert_eq!(config.storage.object_store.s3.keepalive_ms, Some(1));
641            assert_eq!(config.storage.object_store.s3.send_buffer_size, Some(1));
642            assert_eq!(config.storage.object_store.s3.recv_buffer_size, Some(1));
643            assert_eq!(config.storage.object_store.s3.nodelay, Some(false));
644            assert!(
645                config
646                    .storage
647                    .object_store
648                    .s3
649                    .developer
650                    .retry_unknown_service_error
651            );
652            assert_eq!(
653                config
654                    .storage
655                    .object_store
656                    .s3
657                    .developer
658                    .retryable_service_error_codes,
659                vec!["dummy".to_owned()]
660            );
661        }
662    }
663
664    #[test]
665    fn test_meta_configs_backward_compatibility() {
666        // Test periodic_space_reclaim_compaction_interval_sec
667        {
668            let config: RwConfig = toml::from_str(
669                r#"
670            [meta]
671            periodic_split_compact_group_interval_sec = 1
672            table_write_throughput_threshold = 10
673            min_table_split_write_throughput = 5
674            "#,
675            )
676            .unwrap();
677
678            assert_eq!(
679                config
680                    .meta
681                    .periodic_scheduling_compaction_group_split_interval_sec,
682                1
683            );
684            assert_eq!(config.meta.table_high_write_throughput_threshold, 10);
685            assert_eq!(config.meta.table_low_write_throughput_threshold, 5);
686        }
687    }
688
689    #[test]
690    fn test_meta_max_normalize_splits_per_round_must_be_positive() {
691        let config = toml::from_str::<RwConfig>(
692            r#"
693            [meta]
694            max_normalize_splits_per_round = 0
695            "#,
696        )
697        .unwrap_err();
698
699        expect![[r#"
700            TOML parse error at line 3, column 46
701              |
702            3 |             max_normalize_splits_per_round = 0
703              |                                              ^
704            meta.max_normalize_splits_per_round must be greater than 0
705        "#]]
706        .assert_eq(&config.to_string());
707    }
708
709    // Previously, we have prefixes like `stream_` for all configs under `streaming.developer`.
710    // Later we removed the prefixes, but we still want to guarantee the backward compatibility.
711    #[test]
712    fn test_prefix_alias() {
713        let config: RwConfig = toml::from_str(
714            "
715            [streaming.developer]
716            stream_chunk_size = 114514
717
718            [streaming.developer.stream_compute_client_config]
719            connect_timeout_secs = 42
720            pool_setup_concurrency = 10
721            ",
722        )
723        .unwrap();
724
725        assert_eq!(config.streaming.developer.chunk_size, 114514);
726        assert_eq!(
727            config
728                .streaming
729                .developer
730                .compute_client_config
731                .connect_timeout_secs,
732            42
733        );
734        assert_eq!(
735            config
736                .streaming
737                .developer
738                .compute_client_config
739                .pool_setup_concurrency,
740            10
741        );
742    }
743
744    #[test]
745    fn test_prefix_alias_duplicate() {
746        let config = toml::from_str::<RwConfig>(
747            "
748            [streaming.developer]
749            stream_chunk_size = 114514
750            chunk_size = 1919810
751            ",
752        )
753        .unwrap_err();
754
755        expect![[r#"
756            TOML parse error at line 2, column 13
757              |
758            2 |             [streaming.developer]
759              |             ^^^^^^^^^^^^^^^^^^^^^
760            duplicate field `chunk_size`
761        "#]]
762        .assert_eq(&config.to_string());
763
764        let config = toml::from_str::<RwConfig>(
765            "
766            [streaming.developer.stream_compute_client_config]
767            connect_timeout_secs = 5
768
769            [streaming.developer.compute_client_config]
770            connect_timeout_secs = 10
771            ",
772        )
773        .unwrap_err();
774
775        expect![[r#"
776            TOML parse error at line 2, column 24
777              |
778            2 |             [streaming.developer.stream_compute_client_config]
779              |                        ^^^^^^^^^
780            duplicate field `compute_client_config`
781        "#]]
782        .assert_eq(&config.to_string());
783    }
784
785    #[test]
786    fn test_storage_max_prefetch_block_number_must_be_positive() {
787        let config = toml::from_str::<RwConfig>(
788            r#"
789            [storage]
790            max_prefetch_block_number = 0
791            "#,
792        )
793        .unwrap_err();
794
795        expect![[r#"
796            TOML parse error at line 3, column 41
797              |
798            3 |             max_prefetch_block_number = 0
799              |                                         ^
800            storage.max_prefetch_block_number must be greater than 0
801        "#]]
802        .assert_eq(&config.to_string());
803    }
804}