Skip to main content

risingwave_common/session_config/
mod.rs

1// Copyright 2022 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
15mod iceberg_query_storage_mode;
16mod locality_backfill_mode;
17mod non_zero64;
18mod opt;
19pub mod parallelism;
20mod query_mode;
21mod search_path;
22pub mod sink_decouple;
23mod statement_timeout;
24mod transaction_isolation_level;
25mod visibility_mode;
26
27use anyhow::Context;
28use chrono_tz::Tz;
29pub use iceberg_query_storage_mode::IcebergQueryStorageMode;
30use itertools::Itertools;
31pub use locality_backfill_mode::LocalityBackfillMode;
32pub use opt::OptionConfig;
33pub use query_mode::QueryMode;
34use risingwave_common_proc_macro::{ConfigDoc, SessionConfig};
35pub use search_path::{SearchPath, USER_NAME_WILD_CARD};
36use serde::{Deserialize, Serialize};
37pub use statement_timeout::StatementTimeout;
38use thiserror::Error;
39
40use self::non_zero64::ConfigNonZeroU64;
41use crate::config::mutate::TomlTableMutateExt;
42use crate::config::streaming::{CacheRefillPolicy, JoinEncodingType, OverWindowCachePolicy};
43use crate::config::{ConfigMergeError, StreamingConfig, merge_streaming_config_section};
44use crate::hash::VirtualNode;
45use crate::session_config::parallelism::{ConfigBackfillParallelism, ConfigParallelism};
46use crate::session_config::sink_decouple::SinkDecouple;
47use crate::session_config::transaction_isolation_level::IsolationLevel;
48pub use crate::session_config::visibility_mode::VisibilityMode;
49use crate::{PG_VERSION, SERVER_ENCODING, SERVER_VERSION_NUM, STANDARD_CONFORMING_STRINGS};
50
51pub const SESSION_CONFIG_LIST_SEP: &str = ", ";
52
53#[derive(Error, Debug)]
54pub enum SessionConfigError {
55    #[error("Invalid value `{value}` for `{entry}`")]
56    InvalidValue {
57        entry: &'static str,
58        value: String,
59        source: anyhow::Error,
60    },
61
62    #[error("Unrecognized config entry `{0}`")]
63    UnrecognizedEntry(String),
64}
65
66type SessionConfigResult<T> = std::result::Result<T, SessionConfigError>;
67
68const AUTO_LOCALITY_BACKFILL_MIN_SIZE: u64 = 10 * 1024 * 1024 * 1024;
69
70fn default_auto_locality_backfill_min_size() -> u64 {
71    AUTO_LOCALITY_BACKFILL_MIN_SIZE
72}
73
74fn default_legacy_locality_backfill_mode() -> LocalityBackfillMode {
75    LocalityBackfillMode::Always
76}
77
78// NOTE(kwannoel): We declare it separately as a constant,
79// otherwise seems like it can't infer the type of -1 when written inline.
80const DISABLE_BACKFILL_RATE_LIMIT: i32 = -1;
81const DISABLE_SOURCE_RATE_LIMIT: i32 = -1;
82const DISABLE_DML_RATE_LIMIT: i32 = -1;
83const DISABLE_SINK_RATE_LIMIT: i32 = -1;
84
85/// Default to bypass cluster limits iff in debug mode.
86const BYPASS_CLUSTER_LIMITS: bool = cfg!(debug_assertions);
87
88/// This is the Session Config of RisingWave.
89///
90/// All config entries implement `Display` and `FromStr` for getter and setter, to be read and
91/// altered within a session.
92///
93/// Users can change the default value of a configuration entry using `ALTER SYSTEM SET`. To
94/// facilitate this, a `serde` implementation is used as the wire format for retrieving initial
95/// configurations and updates from the meta service. It's important to note that the meta
96/// service stores the overridden value of each configuration entry per row with `Display` in
97/// the meta store, rather than using the `serde` format. However, we still delegate the `serde`
98/// impl of all fields to `Display`/`FromStr` to make it consistent.
99#[serde_with::apply(_ => #[serde_as(as = "serde_with::DisplayFromStr")] )]
100#[serde_with::serde_as]
101#[derive(Clone, Debug, Deserialize, Serialize, SessionConfig, ConfigDoc, PartialEq)]
102pub struct SessionConfig {
103    /// If `RW_IMPLICIT_FLUSH` is on, then every INSERT/UPDATE/DELETE statement will block
104    /// until the entire dataflow is refreshed. In other words, every related table & MV will
105    /// be able to see the write.
106    #[parameter(default = false, alias = "rw_implicit_flush")]
107    implicit_flush: bool,
108
109    /// If `DML_WAIT_PERSISTENCE` is on, then every INSERT/UPDATE/DELETE statement waits until
110    /// the transaction is included in a checkpoint. This is ignored when `IMPLICIT_FLUSH` is on.
111    #[parameter(default = false)]
112    dml_wait_persistence: bool,
113
114    /// If `CREATE_COMPACTION_GROUP_FOR_MV` is on, dedicated compaction groups will be created in
115    /// MV creation.
116    #[parameter(default = false)]
117    create_compaction_group_for_mv: bool,
118
119    /// A temporary config variable to force query running in either local or distributed mode.
120    /// The default value is auto which means let the system decide to run batch queries in local
121    /// or distributed mode automatically.
122    #[parameter(default = QueryMode::default())]
123    query_mode: QueryMode,
124
125    /// For Iceberg engine tables, which storage to use for batch SELECT: Iceberg (columnar) or
126    /// Hummock (row). Only affects batch SELECT on tables with ENGINE = ICEBERG.
127    #[parameter(default = IcebergQueryStorageMode::default())]
128    iceberg_query_storage_mode: IcebergQueryStorageMode,
129
130    /// Sets the number of digits displayed for floating-point values.
131    /// See <https://www.postgresql.org/docs/current/runtime-config-client.html#:~:text=for%20more%20information.-,extra_float_digits,-(integer)>
132    #[parameter(default = 1)]
133    extra_float_digits: i32,
134
135    /// Sets the application name to be reported in statistics and logs.
136    /// See <https://www.postgresql.org/docs/14/runtime-config-logging.html#:~:text=What%20to%20Log-,application_name,-(string)>
137    #[parameter(default = "", flags = "REPORT")]
138    application_name: String,
139
140    /// It is typically set by an application upon connection to the server.
141    /// see <https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-DATESTYLE>
142    #[parameter(default = "", rename = "datestyle")]
143    date_style: String,
144
145    /// Force the use of lookup join instead of hash join when possible for local batch execution.
146    #[parameter(default = true, alias = "rw_batch_enable_lookup_join")]
147    batch_enable_lookup_join: bool,
148
149    /// Enable usage of sortAgg instead of hash agg when order property is satisfied in batch
150    /// execution
151    #[parameter(default = true, alias = "rw_batch_enable_sort_agg")]
152    batch_enable_sort_agg: bool,
153
154    /// Enable distributed DML, so an insert, delete, and update statement can be executed in a distributed way (e.g. running in multiple compute nodes).
155    /// No atomicity guarantee in this mode. Its goal is to gain the best ingestion performance for initial batch ingestion where users always can drop their table when failure happens.
156    #[parameter(default = false, rename = "batch_enable_distributed_dml")]
157    batch_enable_distributed_dml: bool,
158
159    /// Evaluate expression in strict mode for batch queries.
160    /// If set to false, an expression failure will not cause an error but leave a null value
161    /// on the result set.
162    #[parameter(default = true)]
163    batch_expr_strict_mode: bool,
164
165    /// The max gap allowed to transform small range scan into multi point lookup.
166    #[parameter(default = 8)]
167    max_split_range_gap: i32,
168
169    /// Sets the order in which schemas are searched when an object (table, data type, function, etc.)
170    /// is referenced by a simple name with no schema specified.
171    /// See <https://www.postgresql.org/docs/14/runtime-config-client.html#GUC-SEARCH-PATH>
172    #[parameter(default = SearchPath::default())]
173    search_path: SearchPath,
174
175    /// If `VISIBILITY_MODE` is all, we will support querying data without checkpoint.
176    #[parameter(default = VisibilityMode::default())]
177    visibility_mode: VisibilityMode,
178
179    /// Read each serving node's latest locally committed data without waiting for a frontend epoch.
180    /// Each point lookup, range scan, lookup-join probe, and task may observe a different committed
181    /// epoch, even within one scan or statement. Statements in a transaction may also differ.
182    /// Each storage snapshot remains stable. Explicit historical reads and subscription snapshots
183    /// retain their existing semantics. Iceberg reads exclude pending log-store rows. Overrides
184    /// barrier reads. Enable only after all participating frontend and serving nodes support this
185    /// option.
186    #[parameter(default = false)]
187    batch_read_latest_committed: bool,
188
189    /// See <https://www.postgresql.org/docs/current/transaction-iso.html>
190    #[parameter(default = IsolationLevel::default())]
191    transaction_isolation: IsolationLevel,
192
193    /// Select as of specific epoch.
194    /// Sets the historical epoch for querying data. If 0, querying latest data.
195    #[parameter(default = ConfigNonZeroU64::default())]
196    query_epoch: ConfigNonZeroU64,
197
198    /// Session timezone. Defaults to UTC.
199    #[parameter(default = "UTC", check_hook = check_timezone)]
200    timezone: String,
201
202    /// The execution parallelism for streaming queries, including tables, materialized views,
203    /// indexes, and sinks. Defaults to `default`, which preserves the legacy adaptive
204    /// scheduling behavior during effective resolution.
205    #[parameter(default = ConfigParallelism::Default, flags = "SESSION_INIT")]
206    streaming_parallelism: ConfigParallelism,
207
208    /// Specific parallelism for backfill. Only `default` and a fixed positive integer are
209    /// supported here. Adaptive backfill strategies are deferred to a later change.
210    #[parameter(
211        default = ConfigBackfillParallelism::Default,
212        check_hook = check_streaming_parallelism_for_backfill,
213        flags = "SESSION_INIT"
214    )]
215    streaming_parallelism_for_backfill: ConfigBackfillParallelism,
216
217    /// Specific parallelism for table. Defaults to `default`, which preserves the legacy
218    /// bounded adaptive behavior only when the global parallelism itself remains `default`.
219    /// Otherwise it follows the explicit global parallelism.
220    #[parameter(default = ConfigParallelism::Default, flags = "SESSION_INIT")]
221    streaming_parallelism_for_table: ConfigParallelism,
222
223    /// Specific parallelism for sink. By default, it will fall back to `STREAMING_PARALLELISM`.
224    #[parameter(default = ConfigParallelism::Default, flags = "SESSION_INIT")]
225    streaming_parallelism_for_sink: ConfigParallelism,
226
227    /// Specific parallelism for index. By default, it will fall back to `STREAMING_PARALLELISM`.
228    #[parameter(default = ConfigParallelism::Default, flags = "SESSION_INIT")]
229    streaming_parallelism_for_index: ConfigParallelism,
230
231    /// Specific parallelism for source. Defaults to `default`, which preserves the legacy
232    /// bounded adaptive behavior only when the global parallelism itself remains `default`.
233    /// Otherwise it follows the explicit global parallelism.
234    #[parameter(default = ConfigParallelism::Default, flags = "SESSION_INIT")]
235    streaming_parallelism_for_source: ConfigParallelism,
236
237    /// Specific parallelism for materialized view. By default, it will fall back to `STREAMING_PARALLELISM`.
238    #[parameter(default = ConfigParallelism::Default, flags = "SESSION_INIT")]
239    streaming_parallelism_for_materialized_view: ConfigParallelism,
240
241    /// Enable delta join for streaming queries. Defaults to false.
242    #[parameter(default = false, alias = "rw_streaming_enable_delta_join")]
243    streaming_enable_delta_join: bool,
244
245    /// Enable bushy join for streaming queries. Defaults to true.
246    #[parameter(default = true, alias = "rw_streaming_enable_bushy_join")]
247    streaming_enable_bushy_join: bool,
248
249    /// Force filtering to be done inside the join whenever there's a choice between optimizations.
250    /// Defaults to false.
251    #[parameter(default = false, alias = "rw_streaming_force_filter_inside_join")]
252    streaming_force_filter_inside_join: bool,
253
254    /// Deprecated. Arrangement backfill is always used as the fallback backfill type for new
255    /// streaming jobs, and this setting is ignored.
256    #[parameter(
257        default = true,
258        deprecated = "The session variable STREAMING_USE_ARRANGEMENT_BACKFILL has been deprecated and is ignored. Arrangement backfill is always used as the fallback backfill type for new streaming jobs."
259    )]
260    streaming_use_arrangement_backfill: bool,
261
262    #[parameter(default = true)]
263    streaming_use_snapshot_backfill: bool,
264
265    /// Enable serverless backfill for streaming queries. Defaults to false.
266    #[parameter(default = false)]
267    enable_serverless_backfill: bool,
268
269    /// Allow `jsonb` in stream key
270    #[parameter(default = false, alias = "rw_streaming_allow_jsonb_in_stream_key")]
271    streaming_allow_jsonb_in_stream_key: bool,
272
273    /// Unsafe: allow impure expressions on non-append-only streams without materialization.
274    ///
275    /// This may lead to inconsistent results or panics due to re-evaluation on updates/retracts.
276    #[parameter(default = false)]
277    streaming_unsafe_allow_unmaterialized_impure_expr: bool,
278
279    /// Unsafe: allow an upsert sink to use downstream primary-key columns that are not part of
280    /// the upstream stream key.
281    ///
282    /// This may leave stale rows in the downstream system if a downstream primary-key column
283    /// changes without the upsert stream providing its old value.
284    #[parameter(default = false)]
285    streaming_unsafe_allow_upsert_sink_pk_mismatch: bool,
286
287    /// Separate consecutive `StreamHashJoin` by no-shuffle `StreamExchange`
288    #[parameter(default = false)]
289    streaming_separate_consecutive_join: bool,
290
291    /// Separate `StreamSink` by no-shuffle `StreamExchange`
292    #[parameter(default = false)]
293    streaming_separate_sink: bool,
294
295    /// Determine which encoding will be used to encode join rows in operator cache.
296    ///
297    /// This overrides the corresponding entry from the `[streaming.developer]` section in the config file,
298    /// taking effect for new streaming jobs created in the current session.
299    #[parameter(default = None)]
300    streaming_join_encoding: OptionConfig<JoinEncodingType>,
301
302    /// Enable join ordering for streaming and batch queries. Defaults to true.
303    #[parameter(default = true, alias = "rw_enable_join_ordering")]
304    enable_join_ordering: bool,
305
306    /// Enable two phase agg optimization. Defaults to true.
307    /// Setting this to true will always set `FORCE_TWO_PHASE_AGG` to false.
308    #[parameter(default = true, flags = "SETTER", alias = "rw_enable_two_phase_agg")]
309    enable_two_phase_agg: bool,
310
311    /// Force two phase agg optimization whenever there's a choice between
312    /// optimizations. Defaults to false.
313    /// Setting this to true will always set `ENABLE_TWO_PHASE_AGG` to false.
314    #[parameter(default = false, flags = "SETTER", alias = "rw_force_two_phase_agg")]
315    force_two_phase_agg: bool,
316
317    /// Enable sharing of common sub-plans.
318    /// This means that DAG structured query plans can be constructed,
319    #[parameter(default = true, alias = "rw_enable_share_plan")]
320    /// rather than only tree structured query plans.
321    enable_share_plan: bool,
322
323    /// Enable split distinct agg
324    #[parameter(default = false, alias = "rw_force_split_distinct_agg")]
325    force_split_distinct_agg: bool,
326
327    /// See <https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-INTERVALSTYLE>
328    #[parameter(default = "", rename = "intervalstyle")]
329    interval_style: String,
330
331    /// If `BATCH_PARALLELISM` is non-zero, batch queries will use this parallelism.
332    #[parameter(default = ConfigNonZeroU64::default())]
333    batch_parallelism: ConfigNonZeroU64,
334
335    /// The version of PostgreSQL that Risingwave claims to be.
336    #[parameter(default = PG_VERSION)]
337    server_version: String,
338
339    /// The version of PostgreSQL that Risingwave claims to be.
340    #[parameter(default = SERVER_VERSION_NUM)]
341    server_version_num: i32,
342
343    /// see <https://www.postgresql.org/docs/15/runtime-config-client.html#GUC-CLIENT-MIN-MESSAGES>
344    #[parameter(default = "notice")]
345    client_min_messages: String,
346
347    /// see <https://www.postgresql.org/docs/15/runtime-config-client.html#GUC-CLIENT-ENCODING>
348    #[parameter(default = SERVER_ENCODING, check_hook = check_client_encoding)]
349    client_encoding: String,
350
351    /// Enable decoupling sink and internal streaming graph or not
352    #[parameter(default = SinkDecouple::default())]
353    sink_decouple: SinkDecouple,
354
355    /// See <https://www.postgresql.org/docs/current/runtime-config-compatible.html#RUNTIME-CONFIG-COMPATIBLE-VERSION>
356    /// Unused in RisingWave, support for compatibility.
357    #[parameter(default = false)]
358    synchronize_seqscans: bool,
359
360    /// Abort query statement that takes more than the specified amount of time in sec. If
361    /// `log_min_error_statement` is set to ERROR or lower, the statement that timed out will also be
362    /// logged. If this value is specified without units, it is taken as milliseconds. A value of
363    /// zero (the default) disables the timeout.
364    #[parameter(default = StatementTimeout::default())]
365    statement_timeout: StatementTimeout,
366
367    /// Terminate any session that has been idle (that is, waiting for a client query) within an open transaction for longer than the specified amount of time in milliseconds.
368    #[parameter(default = 60000u32)]
369    idle_in_transaction_session_timeout: u32,
370
371    /// See <https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-LOCK-TIMEOUT>
372    /// Unused in RisingWave, support for compatibility.
373    #[parameter(default = 0)]
374    lock_timeout: i32,
375
376    /// For limiting the startup time of a shareable CDC streaming source when the source is being created. Unit: seconds.
377    #[parameter(default = 60)]
378    cdc_source_wait_streaming_start_timeout: i32,
379
380    /// see <https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-ROW-SECURITY>.
381    /// Unused in RisingWave, support for compatibility.
382    #[parameter(default = true)]
383    row_security: bool,
384
385    /// see <https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-STANDARD-CONFORMING-STRINGS>
386    #[parameter(default = STANDARD_CONFORMING_STRINGS)]
387    standard_conforming_strings: String,
388
389    /// Set streaming rate limit (rows per second) for each parallelism for mv / source / sink backfilling
390    /// If set to -1, disable rate limit.
391    /// If set to 0, this pauses the snapshot read / source read.
392    #[parameter(default = DISABLE_BACKFILL_RATE_LIMIT)]
393    backfill_rate_limit: i32,
394
395    /// Set streaming rate limit (rows per second) for each parallelism for mv / source backfilling, source reads.
396    /// If set to -1, disable rate limit.
397    /// If set to 0, this pauses the snapshot read / source read.
398    #[parameter(default = DISABLE_SOURCE_RATE_LIMIT)]
399    source_rate_limit: i32,
400
401    /// Set streaming rate limit (rows per second) for each parallelism for table DML.
402    /// If set to -1, disable rate limit.
403    /// If set to 0, this pauses the DML.
404    #[parameter(default = DISABLE_DML_RATE_LIMIT)]
405    dml_rate_limit: i32,
406
407    /// Set sink rate limit (rows per second) for each parallelism for external sink.
408    /// If set to -1, disable rate limit.
409    /// If set to 0, this pauses the sink.
410    #[parameter(default = DISABLE_SINK_RATE_LIMIT)]
411    sink_rate_limit: i32,
412
413    /// Cache policy for partition cache in streaming over window.
414    /// Can be `full`, `recent`, `recent_first_n` or `recent_last_n`.
415    ///
416    /// This overrides the corresponding entry from the `[streaming.developer]` section in the config file,
417    /// taking effect for new streaming jobs created in the current session.
418    #[parameter(default = None, alias = "rw_streaming_over_window_cache_policy")]
419    streaming_over_window_cache_policy: OptionConfig<OverWindowCachePolicy>,
420
421    /// Cache refill policy for streaming cache refill feature.
422    /// Can be `enabled`, `disabled`, `streaming`, `serving` or `both`.
423    ///
424    /// This overrides the corresponding entry from the `[streaming.developer]` section in the config file,
425    /// taking effect for new streaming jobs created in the current session.
426    #[parameter(default = None)]
427    streaming_cache_refill_policy: OptionConfig<CacheRefillPolicy>,
428
429    /// Override the asynchronous projection chunk window for new streaming jobs in this session.
430    /// Unset inherits the compute-node config (default 1); 0 means unlimited.
431    #[parameter(default = None, check_hook = check_projection_concurrency)]
432    streaming_project_expr_concurrency: OptionConfig<usize>,
433
434    /// Override the asynchronous projection visible-row budget for new streaming jobs in this
435    /// session. Unset inherits the compute-node config (default 0); 0 means unlimited.
436    #[parameter(default = None, check_hook = check_projection_concurrency)]
437    streaming_project_expr_inflight_request_concurrency: OptionConfig<usize>,
438
439    /// Run DDL statements in background
440    #[parameter(default = false)]
441    background_ddl: bool,
442
443    /// Enable shared source. Currently only for Kafka.
444    ///
445    /// When enabled, `CREATE SOURCE` will create a source streaming job, and `CREATE MATERIALIZED VIEWS` from the source
446    /// will forward the data from the same source streaming job, and also backfill prior data from the external source.
447    #[parameter(default = true)]
448    streaming_use_shared_source: bool,
449
450    /// Enable in-memory cache for `AsOf` join executor.
451    ///
452    /// When enabled (default), `AsOf` join uses the cache-based implementation.
453    ///
454    /// When disabled, `AsOf` join uses a no-cache implementation that directly queries
455    /// the state table on-demand, reducing unnecessary data fetches for cache.
456    #[parameter(default = true)]
457    streaming_asof_join_use_cache: bool,
458
459    /// Shows the server-side character set encoding. At present, this parameter can be shown but not set, because the encoding is determined at database creation time.
460    #[parameter(default = SERVER_ENCODING)]
461    server_encoding: String,
462
463    #[parameter(default = "hex", check_hook = check_bytea_output)]
464    bytea_output: String,
465
466    /// Bypass checks on cluster limits
467    ///
468    /// When enabled, `CREATE MATERIALIZED VIEW` will not fail if the cluster limit is hit.
469    #[parameter(default = BYPASS_CLUSTER_LIMITS)]
470    bypass_cluster_limits: bool,
471
472    /// The maximum number of parallelism a streaming query can use. Defaults to 256.
473    ///
474    /// Compared to `STREAMING_PARALLELISM`, which configures the initial parallelism, this configures
475    /// the maximum parallelism a streaming query can use in the future, if the cluster size changes or
476    /// users manually change the parallelism with `ALTER .. SET PARALLELISM`.
477    ///
478    /// It's not always a good idea to set this to a very large number, as it may cause performance
479    /// degradation when performing range scans on the table or the materialized view.
480    // a.k.a. vnode count
481    #[parameter(default = VirtualNode::COUNT_FOR_COMPAT, check_hook = check_streaming_max_parallelism)]
482    streaming_max_parallelism: usize,
483
484    /// Used to provide the connection information for the iceberg engine.
485    /// Format: `iceberg_engine_connection` = `schema_name.connection_name`.
486    #[parameter(default = "", check_hook = check_iceberg_engine_connection)]
487    iceberg_engine_connection: String,
488
489    /// Whether the streaming join should be unaligned or not.
490    #[parameter(default = false)]
491    streaming_enable_unaligned_join: bool,
492
493    /// The timeout for reading from the buffer of the sync log store on barrier.
494    /// Every epoch we will attempt to read the full buffer of the sync log store.
495    /// If we hit the timeout, we will stop reading and continue.
496    ///
497    /// This overrides the corresponding entry from the `[streaming.developer]` section in the config file,
498    /// taking effect for new streaming jobs created in the current session.
499    #[parameter(default = None)]
500    streaming_sync_log_store_pause_duration_ms: OptionConfig<usize>,
501
502    /// The max buffer size for sync logstore, before we start flushing.
503    ///
504    /// This overrides the corresponding entry from the `[streaming.developer]` section in the config file,
505    /// taking effect for new streaming jobs created in the current session.
506    #[parameter(default = None)]
507    streaming_sync_log_store_buffer_size: OptionConfig<usize>,
508
509    /// Whether to disable purifying the definition of the table or source upon retrieval.
510    /// Only set this if encountering issues with functionalities like `SHOW` or `ALTER TABLE/SOURCE`.
511    /// This config may be removed in the future.
512    #[parameter(default = false, flags = "NO_ALTER_SYS")]
513    disable_purify_definition: bool,
514
515    /// The `ef_search` used in querying hnsw vector index
516    #[parameter(default = 40_usize)] // default value borrowed from pg_vector
517    batch_hnsw_ef_search: usize,
518
519    /// Enable index selection for queries
520    #[parameter(default = true)]
521    enable_index_selection: bool,
522
523    /// Enable mv selection for queries
524    #[parameter(default = false)]
525    enable_mv_selection: bool,
526
527    /// Whether to enable locality backfill. When enabled, `locality_backfill_mode` controls
528    /// whether it is selected automatically or always used.
529    #[parameter(default = true)]
530    enable_locality_backfill: bool,
531
532    /// How to apply locality backfill when it is enabled. `auto` uses the estimated backfill size,
533    /// while `always` skips the size check. Missing values from older versions mean `always` to
534    /// preserve the previous boolean behavior.
535    #[serde(default = "default_legacy_locality_backfill_mode")]
536    #[parameter(default = LocalityBackfillMode::Auto)]
537    locality_backfill_mode: LocalityBackfillMode,
538
539    /// Auto-enable locality backfill when estimated scan backfill data reaches this size in bytes.
540    /// Defaults to 10 `GiB` (10737418240 bytes).
541    #[serde(default = "default_auto_locality_backfill_min_size")]
542    #[parameter(default = AUTO_LOCALITY_BACKFILL_MIN_SIZE)]
543    auto_locality_backfill_min_size: u64,
544
545    /// Enable the sort buffer of locality providers for streaming queries created in this session.
546    /// When enabled, locality providers buffer and re-order amplified intermediate results (e.g.,
547    /// caused by join amplification) within an epoch to provide better locality for downstream
548    /// operators, with bounded memory usage. Only takes effect on streaming jobs planned with
549    /// locality providers (see `enable_locality_backfill`). Defaults to true.
550    #[parameter(default = true)]
551    enable_locality_sort_buffer: bool,
552
553    /// Duration in seconds before notifying the user that a long-running DDL operation (e.g., DROP TABLE, CANCEL JOBS)
554    /// is still running. Set to 0 to disable notifications. Defaults to 30 seconds.
555    #[parameter(default = 30u32)]
556    slow_ddl_notification_secs: u32,
557
558    /// Unsafe: Enable storage retention for non-append-only tables.
559    /// Enabling this can lead to streaming inconsistency and node panic
560    /// if there is any row INSERT/UPDATE/DELETE operation corresponding to the ttled primary key.
561    #[parameter(default = false)]
562    unsafe_enable_storage_retention_for_non_append_only_tables: bool,
563
564    /// Enable DataFusion Engine
565    /// When enabled, queries involving Iceberg tables will be executed using the DataFusion engine.
566    #[parameter(default = true)]
567    enable_datafusion_engine: bool,
568
569    /// Prefer hash join over sort merge join in DataFusion engine
570    /// When enabled, the DataFusion engine will prioritize hash joins for query execution plans,
571    /// potentially improving performance for certain workloads, but may cause OOM for large datasets.
572    #[parameter(default = true)]
573    datafusion_prefer_hash_join: bool,
574
575    /// Emit chunks in upsert format for `UPDATE` and `DELETE` DMLs.
576    /// May lead to undefined behavior if the table is created with `ON CONFLICT DO NOTHING`.
577    ///
578    /// When enabled:
579    /// - `UPDATE` will only emit `Insert` records for new rows, instead of `Update` records.
580    /// - `DELETE` will only include key columns and pad the rest with NULL, instead of emitting complete rows.
581    #[parameter(default = false)]
582    upsert_dml: bool,
583}
584
585fn check_iceberg_engine_connection(val: &str) -> Result<(), String> {
586    if val.is_empty() {
587        return Ok(());
588    }
589
590    let parts: Vec<&str> = val.split('.').collect();
591    if parts.len() != 2 {
592        return Err("Invalid iceberg engine connection format, Should be set to this format: schema_name.connection_name.".to_owned());
593    }
594
595    Ok(())
596}
597
598fn check_timezone(val: &str) -> Result<(), String> {
599    // Check if the provided string is a valid timezone.
600    Tz::from_str_insensitive(val).map_err(|_e| "Not a valid timezone")?;
601    Ok(())
602}
603
604fn check_client_encoding(val: &str) -> Result<(), String> {
605    // https://github.com/postgres/postgres/blob/REL_15_3/src/common/encnames.c#L525
606    let clean = val.replace(|c: char| !c.is_ascii_alphanumeric(), "");
607    if !clean.eq_ignore_ascii_case("UTF8") {
608        Err("Only support 'UTF8' for CLIENT_ENCODING".to_owned())
609    } else {
610        Ok(())
611    }
612}
613
614fn check_bytea_output(val: &str) -> Result<(), String> {
615    if val == "hex" {
616        Ok(())
617    } else {
618        Err("Only support 'hex' for BYTEA_OUTPUT".to_owned())
619    }
620}
621
622/// Check if the provided value is a valid max parallelism.
623fn check_streaming_max_parallelism(val: &usize) -> Result<(), String> {
624    match val {
625        // TODO(var-vnode): this is to prevent confusion with singletons, after we distinguish
626        // them better, we may allow 1 as the max parallelism (though not much point).
627        0 | 1 => Err("STREAMING_MAX_PARALLELISM must be greater than 1".to_owned()),
628        2..=VirtualNode::MAX_COUNT => Ok(()),
629        _ => Err(format!(
630            "STREAMING_MAX_PARALLELISM must be less than or equal to {}",
631            VirtualNode::MAX_COUNT
632        )),
633    }
634}
635
636fn check_streaming_parallelism_for_backfill(val: &ConfigBackfillParallelism) -> Result<(), String> {
637    match val {
638        ConfigBackfillParallelism::Default | ConfigBackfillParallelism::Fixed(_) => Ok(()),
639        ConfigBackfillParallelism::Adaptive
640        | ConfigBackfillParallelism::Bounded(_)
641        | ConfigBackfillParallelism::Ratio(_) => Err(
642            "Only `default` or fixed backfill parallelism is supported here; adaptive backfill strategy is deferred to a later change.".to_owned(),
643        ),
644    }
645}
646
647fn check_projection_concurrency(val: &OptionConfig<usize>) -> Result<(), String> {
648    // Job overrides are stored as TOML, whose integers are signed 64-bit values.
649    if val.as_ref().is_some_and(|v| i64::try_from(*v).is_err()) {
650        return Err(format!(
651            "must not exceed {} for TOML job overrides",
652            i64::MAX
653        ));
654    }
655    Ok(())
656}
657
658impl SessionConfig {
659    pub fn set_force_two_phase_agg(
660        &mut self,
661        val: bool,
662        reporter: &mut impl ConfigReporter,
663    ) -> SessionConfigResult<bool> {
664        let set_val = self.set_force_two_phase_agg_inner(val, reporter)?;
665        if self.force_two_phase_agg {
666            self.set_enable_two_phase_agg(true, reporter)
667        } else {
668            Ok(set_val)
669        }
670    }
671
672    pub fn set_enable_two_phase_agg(
673        &mut self,
674        val: bool,
675        reporter: &mut impl ConfigReporter,
676    ) -> SessionConfigResult<bool> {
677        let set_val = self.set_enable_two_phase_agg_inner(val, reporter)?;
678        if !self.force_two_phase_agg {
679            self.set_force_two_phase_agg(false, reporter)
680        } else {
681            Ok(set_val)
682        }
683    }
684}
685
686pub struct VariableInfo {
687    pub name: String,
688    pub setting: String,
689    pub description: String,
690}
691
692/// Report status or notice to caller.
693pub trait ConfigReporter {
694    fn report_status(&mut self, key: &str, new_val: String);
695}
696
697// Report nothing.
698impl ConfigReporter for () {
699    fn report_status(&mut self, _key: &str, _new_val: String) {}
700}
701
702def_anyhow_newtype! {
703    pub SessionConfigToOverrideError,
704    toml::ser::Error => "failed to serialize initial streaming configuration override",
705    ConfigMergeError => transparent,
706}
707
708impl SessionConfig {
709    /// Generate an initial override for the streaming config from the session config.
710    pub fn to_initial_streaming_config_override(
711        &self,
712    ) -> Result<String, SessionConfigToOverrideError> {
713        let mut table = toml::Table::new();
714
715        // TODO: make this more type safe.
716        // We `unwrap` here to assert the hard-coded keys are correct.
717        if let Some(v) = self.streaming_join_encoding.as_ref() {
718            table
719                .upsert("streaming.developer.join_encoding_type", v)
720                .unwrap();
721        }
722        if let Some(v) = self.streaming_sync_log_store_pause_duration_ms.as_ref() {
723            table
724                .upsert("streaming.developer.sync_log_store_pause_duration_ms", v)
725                .unwrap();
726        }
727        if let Some(v) = self.streaming_sync_log_store_buffer_size.as_ref() {
728            table
729                .upsert("streaming.developer.sync_log_store_buffer_size", v)
730                .unwrap();
731        }
732        if let Some(v) = self.streaming_over_window_cache_policy.as_ref() {
733            table
734                .upsert("streaming.developer.over_window_cache_policy", v)
735                .unwrap();
736        }
737        if let Some(v) = self.streaming_cache_refill_policy.as_ref() {
738            table
739                .upsert("streaming.developer.cache_refill_policy", v)
740                .unwrap();
741        }
742        for (key, value) in [
743            (
744                "streaming.developer.project_expr_concurrency",
745                self.streaming_project_expr_concurrency.as_ref(),
746            ),
747            (
748                "streaming.developer.project_expr_inflight_request_concurrency",
749                self.streaming_project_expr_inflight_request_concurrency
750                    .as_ref(),
751            ),
752        ] {
753            if let Some(value) = value {
754                table.upsert(key, value).with_context(|| {
755                    format!(
756                        "failed to build initial streaming configuration override: {key}={value}"
757                    )
758                })?;
759            }
760        }
761
762        let res = toml::to_string(&table)?;
763
764        // Validate all fields are valid by trying to merge it to the default config.
765        if !res.is_empty() {
766            let merged =
767                merge_streaming_config_section(&StreamingConfig::default(), res.as_str())?.unwrap();
768
769            let unrecognized_keys = merged.unrecognized_keys().collect_vec();
770            if !unrecognized_keys.is_empty() {
771                bail!("unrecognized configs: {:?}", unrecognized_keys);
772            }
773        }
774
775        Ok(res)
776    }
777}
778
779#[cfg(test)]
780mod test {
781    use expect_test::expect;
782
783    use super::*;
784
785    #[derive(SessionConfig)]
786    struct TestConfig {
787        #[parameter(default = 1, flags = "NO_ALTER_SYS", alias = "test_param_alias" | "alias_param_test")]
788        test_param: i32,
789        #[parameter(default = false, deprecated = "deprecated test notice")]
790        deprecated_test_param: bool,
791    }
792
793    #[test]
794    fn test_batch_read_latest_committed() {
795        let mut config = SessionConfig::default();
796        assert!(!config.batch_read_latest_committed());
797        assert_eq!(config.get("batch_read_latest_committed").unwrap(), "false");
798        config
799            .set("batch_read_latest_committed", "true".to_owned(), &mut ())
800            .unwrap();
801        assert!(config.batch_read_latest_committed());
802        assert_eq!(config.get("batch_read_latest_committed").unwrap(), "true");
803        config
804            .reset("batch_read_latest_committed", &mut ())
805            .unwrap();
806        assert!(!config.batch_read_latest_committed());
807    }
808
809    #[test]
810    fn test_session_config_alias() {
811        let mut config = TestConfig::default();
812        config.set("test_param", "2".to_owned(), &mut ()).unwrap();
813        assert_eq!(config.get("test_param_alias").unwrap(), "2");
814        config
815            .set("alias_param_test", "3".to_owned(), &mut ())
816            .unwrap();
817        assert_eq!(config.get("test_param_alias").unwrap(), "3");
818        assert!(TestConfig::check_no_alter_sys("test_param").unwrap());
819        assert_eq!(
820            TestConfig::deprecated_notice("deprecated_test_param").unwrap(),
821            Some("deprecated test notice")
822        );
823        assert_eq!(TestConfig::deprecated_notice("test_param").unwrap(), None);
824    }
825
826    #[test]
827    fn test_initial_streaming_config_override() {
828        let mut config = SessionConfig::default();
829        config
830            .set_streaming_join_encoding(Some(JoinEncodingType::Cpu).into(), &mut ())
831            .unwrap();
832        config
833            .set_streaming_over_window_cache_policy(
834                Some(OverWindowCachePolicy::RecentFirstN).into(),
835                &mut (),
836            )
837            .unwrap();
838        config
839            .set_streaming_cache_refill_policy(Some(CacheRefillPolicy::Both).into(), &mut ())
840            .unwrap();
841
842        // Check the converted config override string.
843        let override_str = config.to_initial_streaming_config_override().unwrap();
844        expect![[r#"
845            [streaming.developer]
846            cache_refill_policy = "both"
847            join_encoding_type = "cpu_optimized"
848            over_window_cache_policy = "recent_first_n"
849        "#]]
850        .assert_eq(&override_str);
851
852        // Try merging it to the default streaming config.
853        let merged = merge_streaming_config_section(&StreamingConfig::default(), &override_str)
854            .unwrap()
855            .unwrap();
856        assert_eq!(merged.developer.join_encoding_type, JoinEncodingType::Cpu);
857        assert_eq!(
858            merged.developer.over_window_cache_policy,
859            OverWindowCachePolicy::RecentFirstN
860        );
861        assert_eq!(
862            merged.developer.cache_refill_policy,
863            CacheRefillPolicy::Both
864        );
865    }
866
867    #[test]
868    fn test_initial_projection_config_override() {
869        let mut config = SessionConfig::default();
870        assert_eq!(config.to_initial_streaming_config_override().unwrap(), "");
871        config
872            .set_streaming_project_expr_concurrency(Some(0).into(), &mut ())
873            .unwrap();
874        config
875            .set_streaming_project_expr_inflight_request_concurrency(Some(13).into(), &mut ())
876            .unwrap();
877        let merged = merge_streaming_config_section(
878            &StreamingConfig::default(),
879            &config.to_initial_streaming_config_override().unwrap(),
880        )
881        .unwrap()
882        .unwrap();
883        assert_eq!(merged.developer.project_expr_concurrency, 0);
884        assert_eq!(
885            merged.developer.project_expr_inflight_request_concurrency,
886            13
887        );
888        config
889            .set_streaming_project_expr_concurrency(None.into(), &mut ())
890            .unwrap();
891        config
892            .set_streaming_project_expr_inflight_request_concurrency(None.into(), &mut ())
893            .unwrap();
894        assert_eq!(config.to_initial_streaming_config_override().unwrap(), "");
895    }
896
897    #[test]
898    fn test_projection_config_bounds() {
899        let max = usize::try_from(i64::MAX).unwrap_or(usize::MAX);
900        for (name, key) in [
901            (
902                "streaming_project_expr_concurrency",
903                "project_expr_concurrency",
904            ),
905            (
906                "streaming_project_expr_inflight_request_concurrency",
907                "project_expr_inflight_request_concurrency",
908            ),
909        ] {
910            let mut config = SessionConfig::default();
911            for value in [0, 1, max] {
912                config.set(name, value.to_string(), &mut ()).unwrap();
913                let override_str = config.to_initial_streaming_config_override().unwrap();
914                let table: toml::Table = override_str.parse().unwrap();
915                assert_eq!(
916                    table["streaming"]["developer"][key].as_integer(),
917                    Some(i64::try_from(value).unwrap())
918                );
919            }
920            for value in [
921                "-1",
922                "9223372036854775808",
923                "18446744073709551615",
924                "18446744073709551616",
925            ] {
926                let err = config.set(name, value.to_owned(), &mut ()).unwrap_err();
927                assert!(
928                    matches!(err, SessionConfigError::InvalidValue { entry, .. } if entry == name)
929                );
930                assert_eq!(config.get(name).unwrap(), max.to_string());
931                assert!(config.to_initial_streaming_config_override().is_ok());
932            }
933            config.set(name, String::new(), &mut ()).unwrap();
934            assert_eq!(config.to_initial_streaming_config_override().unwrap(), "");
935        }
936    }
937
938    #[cfg(target_pointer_width = "64")]
939    #[test]
940    fn test_projection_config_override_serialization_error() {
941        // Deserialization can bypass SET validation, e.g. for persisted session defaults.
942        for (name, key) in [
943            (
944                "streaming_project_expr_concurrency",
945                "streaming.developer.project_expr_concurrency",
946            ),
947            (
948                "streaming_project_expr_inflight_request_concurrency",
949                "streaming.developer.project_expr_inflight_request_concurrency",
950            ),
951        ] {
952            let mut value = serde_json::to_value(SessionConfig::default()).unwrap();
953            value[name] = "9223372036854775808".into();
954            let config: SessionConfig = serde_json::from_value(value).unwrap();
955            let err = config.to_initial_streaming_config_override().unwrap_err();
956            assert_eq!(
957                err.to_string(),
958                format!(
959                    "failed to build initial streaming configuration override: {key}=9223372036854775808"
960                )
961            );
962            assert!(
963                err.0
964                    .downcast_ref::<crate::config::mutate::ConfigMutateError>()
965                    .is_some()
966            );
967        }
968    }
969
970    #[test]
971    fn test_streaming_parallelism_defaults() {
972        let config = SessionConfig::default();
973
974        assert_eq!(config.streaming_parallelism(), ConfigParallelism::Default);
975        assert_eq!(
976            config.streaming_parallelism_for_table(),
977            ConfigParallelism::Default
978        );
979        assert_eq!(
980            config.streaming_parallelism_for_source(),
981            ConfigParallelism::Default
982        );
983        assert_eq!(
984            config.streaming_parallelism_for_sink(),
985            ConfigParallelism::Default
986        );
987        assert_eq!(
988            config.streaming_parallelism_for_index(),
989            ConfigParallelism::Default
990        );
991        assert_eq!(
992            config.streaming_parallelism_for_materialized_view(),
993            ConfigParallelism::Default
994        );
995        assert!(!config.streaming_unsafe_allow_upsert_sink_pk_mismatch());
996    }
997
998    #[test]
999    fn test_streaming_parallelism_default_round_trip() {
1000        let mut config = SessionConfig::default();
1001
1002        assert_eq!(config.get("streaming_parallelism").unwrap(), "default");
1003        assert_eq!(
1004            config.get("streaming_parallelism_for_table").unwrap(),
1005            "default"
1006        );
1007        assert_eq!(
1008            config.get("streaming_parallelism_for_source").unwrap(),
1009            "default"
1010        );
1011
1012        config
1013            .set("streaming_parallelism", "default".to_owned(), &mut ())
1014            .unwrap();
1015        assert_eq!(config.get("streaming_parallelism").unwrap(), "default");
1016
1017        config
1018            .set("streaming_parallelism", "bounded(16)".to_owned(), &mut ())
1019            .unwrap();
1020        config
1021            .set(
1022                "streaming_parallelism_for_table",
1023                "bounded(8)".to_owned(),
1024                &mut (),
1025            )
1026            .unwrap();
1027        config
1028            .set(
1029                "streaming_parallelism_for_source",
1030                "bounded(8)".to_owned(),
1031                &mut (),
1032            )
1033            .unwrap();
1034
1035        assert_eq!(
1036            config.reset("streaming_parallelism", &mut ()).unwrap(),
1037            "default"
1038        );
1039        assert_eq!(
1040            config
1041                .reset("streaming_parallelism_for_table", &mut ())
1042                .unwrap(),
1043            "default"
1044        );
1045        assert_eq!(
1046            config
1047                .reset("streaming_parallelism_for_source", &mut ())
1048                .unwrap(),
1049            "default"
1050        );
1051    }
1052    #[test]
1053    fn test_streaming_parallelism_for_backfill_accepts_default_and_fixed() {
1054        let mut config = SessionConfig::default();
1055
1056        config
1057            .set(
1058                "streaming_parallelism_for_backfill",
1059                "default".to_owned(),
1060                &mut (),
1061            )
1062            .unwrap();
1063        assert_eq!(
1064            config.get("streaming_parallelism_for_backfill").unwrap(),
1065            "default"
1066        );
1067
1068        config
1069            .set(
1070                "streaming_parallelism_for_backfill",
1071                "2".to_owned(),
1072                &mut (),
1073            )
1074            .unwrap();
1075        assert_eq!(config.streaming_parallelism_for_backfill().to_string(), "2");
1076    }
1077
1078    #[test]
1079    fn test_streaming_parallelism_for_backfill_rejects_adaptive_modes() {
1080        let mut config = SessionConfig::default();
1081        let expected = "Only `default` or fixed backfill parallelism is supported here; adaptive backfill strategy is deferred to a later change.";
1082
1083        for value in ["adaptive", "bounded(2)", "ratio(0.5)"] {
1084            let err = config
1085                .set(
1086                    "streaming_parallelism_for_backfill",
1087                    value.to_owned(),
1088                    &mut (),
1089                )
1090                .unwrap_err();
1091
1092            match err {
1093                SessionConfigError::InvalidValue {
1094                    entry,
1095                    value: actual_value,
1096                    source,
1097                } => {
1098                    assert_eq!(entry, "streaming_parallelism_for_backfill");
1099                    assert_eq!(actual_value, value);
1100                    assert_eq!(source.to_string(), expected);
1101                }
1102                other => panic!("unexpected error: {other:?}"),
1103            }
1104        }
1105    }
1106}