Skip to main content

mz_sql/session/vars/
definitions.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::borrow::Cow;
11use std::num::NonZeroU32;
12use std::str::FromStr;
13use std::sync::Arc;
14use std::sync::LazyLock;
15use std::time::Duration;
16
17use chrono::{DateTime, Utc};
18use derivative::Derivative;
19use mz_adapter_types::timestamp_oracle::{
20    DEFAULT_PG_TIMESTAMP_ORACLE_CONNPOOL_MAX_SIZE, DEFAULT_PG_TIMESTAMP_ORACLE_CONNPOOL_MAX_WAIT,
21    DEFAULT_PG_TIMESTAMP_ORACLE_CONNPOOL_TTL, DEFAULT_PG_TIMESTAMP_ORACLE_CONNPOOL_TTL_STAGGER,
22};
23use mz_dyncfg::ParameterScope;
24use mz_ore::cast::{self, CastFrom};
25use mz_repr::adt::numeric::Numeric;
26use mz_repr::adt::timestamp::CheckedTimestamp;
27use mz_repr::bytes::ByteSize;
28use mz_repr::optimize::OptimizerFeatures;
29use mz_sql_parser::ast::Ident;
30use mz_sql_parser::ident;
31use mz_storage_types::parameters::REPLICA_STATUS_HISTORY_RETENTION_WINDOW_DEFAULT;
32use mz_storage_types::parameters::{
33    DEFAULT_PG_SOURCE_CONNECT_TIMEOUT, DEFAULT_PG_SOURCE_TCP_CONFIGURE_SERVER,
34    DEFAULT_PG_SOURCE_TCP_KEEPALIVES_IDLE, DEFAULT_PG_SOURCE_TCP_KEEPALIVES_INTERVAL,
35    DEFAULT_PG_SOURCE_TCP_KEEPALIVES_RETRIES, DEFAULT_PG_SOURCE_TCP_USER_TIMEOUT,
36    DEFAULT_PG_SOURCE_WAL_SENDER_TIMEOUT, STORAGE_MANAGED_COLLECTIONS_BATCH_DURATION_DEFAULT,
37};
38use mz_tracing::{CloneableEnvFilter, SerializableDirective};
39use uncased::UncasedStr;
40
41use crate::session::user::{SUPPORT_USER, SYSTEM_USER, User};
42use crate::session::vars::constraints::{
43    BYTESIZE_AT_LEAST_1MB, DomainConstraint, NON_ZERO_DURATION, NUMERIC_BOUNDED_0_1_INCLUSIVE,
44    NUMERIC_NON_NEGATIVE, U32_AT_LEAST_1, ValueConstraint,
45};
46use crate::session::vars::errors::VarError;
47use crate::session::vars::polyfill::{LazyValueFn, lazy_value, value};
48use crate::session::vars::value::{
49    ClientEncoding, ClientSeverity, DEFAULT_DATE_STYLE, Failpoints, IntervalStyle, IsolationLevel,
50    TimeZone, Value,
51};
52use crate::session::vars::{FeatureFlag, Var, VarInput, VarParseError};
53use crate::{DEFAULT_SCHEMA, WEBHOOK_CONCURRENCY_LIMIT};
54
55/// Definition of a variable.
56#[derive(Clone, Derivative)]
57#[derivative(Debug)]
58pub struct VarDefinition {
59    /// Name of the variable, case-insensitive matching.
60    pub name: &'static UncasedStr,
61    /// Description of the variable.
62    pub description: &'static str,
63    /// Is the variable visible to users, when false only visible to system users.
64    pub user_visible: bool,
65
66    /// Default compiled in value for this variable.
67    pub value: VarDefaultValue,
68    /// Constraint that must be upheld for this variable to be valid.
69    pub constraint: Option<ValueConstraint>,
70    /// When set, prevents getting or setting the variable unless the specified
71    /// feature flag is enabled.
72    pub require_feature_flag: Option<&'static FeatureFlag>,
73    /// The scope at which this variable's value may be overridden by the
74    /// LaunchDarkly sync loop.
75    pub scope: ParameterScope,
76
77    /// Method to parse [`VarInput`] into a type that implements [`Value`].
78    ///
79    /// The reason `parse` exists as a function pointer is because we want to achieve two things:
80    ///   1. `VarDefinition` has no generic parameters.
81    ///   2. `Value::parse` returns an instance of `Self`.
82    /// `VarDefinition` holds a `dyn Value`, but `Value::parse` is not object safe because it
83    /// returns `Self`, so we can't call that method. We could change `Value::parse` to return a
84    /// `Box<dyn Value>` making it object safe, but that creates a footgun where it's possible for
85    /// `Value::parse` to return a type that isn't `Self`, e.g. `<String as Value>::parse` could
86    /// return a `usize`!
87    ///
88    /// So to prevent making `VarDefinition` generic over some type `V: Value`, but also defining
89    /// `Value::parse` as returning `Self`, we store a static function pointer to the `parse`
90    /// implementation of our default value.
91    #[derivative(Debug = "ignore")]
92    parse: fn(VarInput) -> Result<Box<dyn Value>, VarParseError>,
93    /// Returns a human readable name for the type of this variable. We store this as a static
94    /// function pointer for the same reason as `parse`.
95    #[derivative(Debug = "ignore")]
96    type_name: fn() -> Cow<'static, str>,
97}
98static_assertions::assert_impl_all!(VarDefinition: Send, Sync);
99
100impl VarDefinition {
101    /// Create a new [`VarDefinition`] in a const context with a value known at compile time.
102    pub const fn new<V: Value>(
103        name: &'static str,
104        value: &'static V,
105        description: &'static str,
106        user_visible: bool,
107    ) -> Self {
108        VarDefinition {
109            name: UncasedStr::new(name),
110            description,
111            value: VarDefaultValue::Static(value),
112            user_visible,
113            parse: V::parse_dyn_value,
114            type_name: V::type_name,
115            constraint: None,
116            require_feature_flag: None,
117            scope: ParameterScope::DEFAULT,
118        }
119    }
120
121    /// Create a new [`VarDefinition`] in a const context with a lazily evaluated value.
122    pub const fn new_lazy<V: Value, L: LazyValueFn<V>>(
123        name: &'static str,
124        _value: L,
125        description: &'static str,
126        user_visible: bool,
127    ) -> Self {
128        VarDefinition {
129            name: UncasedStr::new(name),
130            description,
131            value: VarDefaultValue::Lazy(L::LAZY_VALUE_FN),
132            user_visible,
133            parse: V::parse_dyn_value,
134            type_name: V::type_name,
135            constraint: None,
136            require_feature_flag: None,
137            scope: ParameterScope::DEFAULT,
138        }
139    }
140
141    /// Create a new [`VarDefinition`] with a value known at runtime.
142    pub fn new_runtime<V: Value>(
143        name: &'static str,
144        value: V,
145        description: &'static str,
146        user_visible: bool,
147    ) -> Self {
148        VarDefinition {
149            name: UncasedStr::new(name),
150            description,
151            value: VarDefaultValue::Runtime(Arc::new(value)),
152            user_visible,
153            parse: V::parse_dyn_value,
154            type_name: V::type_name,
155            constraint: None,
156            require_feature_flag: None,
157            scope: ParameterScope::DEFAULT,
158        }
159    }
160
161    /// TODO(parkmycar): Refactor this method onto a `VarDefinitionBuilder` that would allow us to
162    /// constrain `V` here to be the same `V` used in [`VarDefinition::new`].
163    pub const fn with_constraint<V: Value, D: DomainConstraint<Value = V>>(
164        mut self,
165        constraint: &'static D,
166    ) -> Self {
167        self.constraint = Some(ValueConstraint::Domain(constraint));
168        self
169    }
170
171    pub const fn fixed(mut self) -> Self {
172        self.constraint = Some(ValueConstraint::Fixed);
173        self
174    }
175
176    pub const fn read_only(mut self) -> Self {
177        self.constraint = Some(ValueConstraint::ReadOnly);
178        self
179    }
180
181    pub const fn with_feature_flag(mut self, feature_flag: &'static FeatureFlag) -> Self {
182        self.require_feature_flag = Some(feature_flag);
183        self
184    }
185
186    /// Declares the [`ParameterScope`] of this variable, overriding the
187    /// [default](ParameterScope::DEFAULT). See [`ParameterScope`] for the
188    /// semantics of each scope class.
189    pub const fn scoped(mut self, scope: ParameterScope) -> Self {
190        self.scope = scope;
191        self
192    }
193
194    pub fn parse(&self, input: VarInput) -> Result<Box<dyn Value>, VarError> {
195        (self.parse)(input).map_err(|err| err.into_var_error(self))
196    }
197
198    pub fn default_value(&self) -> &'_ dyn Value {
199        self.value.value()
200    }
201
202    /// Returns every property of this definition.
203    pub fn parts(&self) -> VarDefinitionParts<'_> {
204        // Destructured without `..`, so a new field fails to compile here
205        // until it is either exposed or deliberately skipped.
206        let VarDefinition {
207            name,
208            description,
209            user_visible,
210            value: _,
211            constraint,
212            require_feature_flag,
213            scope,
214            // Exposed as `VarDefinition::parse`.
215            parse: _,
216            type_name,
217        } = self;
218        VarDefinitionParts {
219            name,
220            description,
221            user_visible: *user_visible,
222            default_value: self.default_value(),
223            constraint: constraint.as_ref(),
224            require_feature_flag: *require_feature_flag,
225            scope: *scope,
226            type_name: type_name(),
227        }
228    }
229}
230
231/// The properties of a [`VarDefinition`], see [`VarDefinition::parts`].
232#[derive(Debug)]
233pub struct VarDefinitionParts<'a> {
234    pub name: &'static UncasedStr,
235    pub description: &'static str,
236    pub user_visible: bool,
237    pub default_value: &'a dyn Value,
238    pub constraint: Option<&'a ValueConstraint>,
239    pub require_feature_flag: Option<&'static FeatureFlag>,
240    pub scope: ParameterScope,
241    pub type_name: Cow<'static, str>,
242}
243
244impl Var for VarDefinition {
245    fn name(&self) -> &'static str {
246        self.name.as_str()
247    }
248
249    fn value(&self) -> String {
250        self.default_value().format()
251    }
252
253    fn description(&self) -> &'static str {
254        self.description
255    }
256
257    fn type_name(&self) -> Cow<'static, str> {
258        (self.type_name)()
259    }
260
261    fn scope(&self) -> ParameterScope {
262        self.scope
263    }
264
265    fn visible(&self, user: &User, system_vars: &super::SystemVars) -> Result<(), VarError> {
266        if !self.user_visible && user != &*SYSTEM_USER && user != &*SUPPORT_USER {
267            Err(VarError::UnknownParameter(self.name().to_string()))
268        } else if self.is_unsafe() && !system_vars.allow_unsafe() {
269            Err(VarError::RequiresUnsafeMode(self.name()))
270        } else {
271            if let Some(flag) = self.require_feature_flag {
272                flag.require(system_vars)?;
273            }
274
275            Ok(())
276        }
277    }
278}
279
280/// The kinds of compiled in default values that can be used with [`VarDefinition`].
281#[derive(Clone, Debug)]
282pub enum VarDefaultValue {
283    /// Static that can be evaluated at compile time.
284    Static(&'static dyn Value),
285    /// Lazy value that is defined at compile time, but created at runtime.
286    Lazy(fn() -> &'static dyn Value),
287    /// Value created at runtime. Note: This is generally an escape hatch.
288    Runtime(Arc<dyn Value>),
289}
290
291impl VarDefaultValue {
292    pub fn value(&self) -> &'_ dyn Value {
293        match self {
294            VarDefaultValue::Static(s) => *s,
295            VarDefaultValue::Lazy(l) => (l)(),
296            VarDefaultValue::Runtime(r) => r.as_ref(),
297        }
298    }
299}
300
301// We pretend to be Postgres v9.5.0, which is also what CockroachDB pretends to
302// be. Too new and some clients will emit a "server too new" warning. Too old
303// and some clients will fall back to legacy code paths. v9.5.0 empirically
304// seems to be a good compromise.
305
306/// The major version of PostgreSQL that Materialize claims to be.
307pub const SERVER_MAJOR_VERSION: u8 = 9;
308
309/// The minor version of PostgreSQL that Materialize claims to be.
310pub const SERVER_MINOR_VERSION: u8 = 5;
311
312/// The patch version of PostgreSQL that Materialize claims to be.
313pub const SERVER_PATCH_VERSION: u8 = 0;
314
315/// The name of the default database that Materialize uses.
316pub const DEFAULT_DATABASE_NAME: &str = "materialize";
317
318pub static APPLICATION_NAME: VarDefinition = VarDefinition::new(
319    "application_name",
320    value!(String; String::new()),
321    "Sets the application name to be reported in statistics and logs (PostgreSQL).",
322    true,
323);
324
325pub static CLIENT_ENCODING: VarDefinition = VarDefinition::new(
326    "client_encoding",
327    value!(ClientEncoding; ClientEncoding::Utf8),
328    "Sets the client's character set encoding (PostgreSQL).",
329    true,
330);
331
332pub static CLIENT_MIN_MESSAGES: VarDefinition = VarDefinition::new(
333    "client_min_messages",
334    value!(ClientSeverity; ClientSeverity::Notice),
335    "Sets the message levels that are sent to the client (PostgreSQL).",
336    true,
337);
338
339pub static CLUSTER: VarDefinition = VarDefinition::new_lazy(
340    "cluster",
341    lazy_value!(String; || "quickstart".to_string()),
342    "Sets the current cluster (Materialize).",
343    true,
344);
345
346pub static CLUSTER_REPLICA: VarDefinition = VarDefinition::new(
347    "cluster_replica",
348    value!(Option<String>; None),
349    "Sets a target cluster replica for SELECT queries (Materialize).",
350    true,
351);
352
353pub static CURRENT_OBJECT_MISSING_WARNINGS: VarDefinition = VarDefinition::new(
354    "current_object_missing_warnings",
355    value!(bool; true),
356    "Whether to emit warnings when the current database, schema, or cluster is missing (Materialize).",
357    true,
358);
359
360pub static DATABASE: VarDefinition = VarDefinition::new_lazy(
361    "database",
362    lazy_value!(String; || DEFAULT_DATABASE_NAME.to_string()),
363    "Sets the current database (CockroachDB).",
364    true,
365);
366
367pub static DATE_STYLE: VarDefinition = VarDefinition::new(
368    // DateStyle has nonstandard capitalization for historical reasons.
369    "DateStyle",
370    &DEFAULT_DATE_STYLE,
371    "Sets the display format for date and time values (PostgreSQL).",
372    true,
373);
374
375pub static DEFAULT_CLUSTER_REPLICATION_FACTOR: VarDefinition = VarDefinition::new(
376    "default_cluster_replication_factor",
377    value!(u32; 1),
378    "Default cluster replication factor (Materialize).",
379    true,
380);
381
382pub static EXTRA_FLOAT_DIGITS: VarDefinition = VarDefinition::new(
383    "extra_float_digits",
384    value!(i32; 1),
385    "Adjusts the number of digits displayed for floating-point values (PostgreSQL).",
386    true,
387);
388
389// The `unsafe_` prefix limits this variable to unsafe mode: a failpoint applies
390// to the whole process, so any session could, for example, crash environmentd
391// with a `panic` action.
392pub static UNSAFE_FAILPOINTS: VarDefinition = VarDefinition::new(
393    "unsafe_failpoints",
394    value!(Failpoints; Failpoints),
395    "Allows failpoints to be dynamically activated.",
396    true,
397);
398
399pub static INTEGER_DATETIMES: VarDefinition = VarDefinition::new(
400    "integer_datetimes",
401    value!(bool; true),
402    "Reports whether the server uses 64-bit-integer dates and times (PostgreSQL).",
403    true,
404)
405.fixed();
406
407pub static INTERVAL_STYLE: VarDefinition = VarDefinition::new(
408    // IntervalStyle has nonstandard capitalization for historical reasons.
409    "IntervalStyle",
410    value!(IntervalStyle; IntervalStyle::Postgres),
411    "Sets the display format for interval values (PostgreSQL).",
412    true,
413);
414
415pub const MZ_VERSION_NAME: &UncasedStr = UncasedStr::new("mz_version");
416pub const IS_SUPERUSER_NAME: &UncasedStr = UncasedStr::new("is_superuser");
417
418// Schema can be used an alias for a search path with a single element.
419pub const SCHEMA_ALIAS: &UncasedStr = UncasedStr::new("schema");
420pub static SEARCH_PATH: VarDefinition = VarDefinition::new_lazy(
421    "search_path",
422    lazy_value!(Vec<Ident>; || vec![ident!(DEFAULT_SCHEMA)]),
423    "Sets the schema search order for names that are not schema-qualified (PostgreSQL).",
424    true,
425);
426
427pub static STATEMENT_TIMEOUT: VarDefinition = VarDefinition::new(
428    "statement_timeout",
429    value!(Duration; Duration::from_secs(60)),
430    "Sets the maximum allowed duration of INSERT...SELECT, UPDATE, and DELETE operations. \
431    If this value is specified without units, it is taken as milliseconds.",
432    true,
433);
434
435pub static IDLE_IN_TRANSACTION_SESSION_TIMEOUT: VarDefinition = VarDefinition::new(
436    "idle_in_transaction_session_timeout",
437    value!(Duration; Duration::from_secs(60 * 2)),
438    "Sets the maximum allowed duration that a session can sit idle in a transaction before \
439    being terminated. If this value is specified without units, it is taken as milliseconds. \
440    A value of zero disables the timeout (PostgreSQL).",
441    true,
442);
443
444pub static SERVER_VERSION: VarDefinition = VarDefinition::new_lazy(
445    "server_version",
446    lazy_value!(String; || {
447        format!("{SERVER_MAJOR_VERSION}.{SERVER_MINOR_VERSION}.{SERVER_PATCH_VERSION}")
448    }),
449    "Shows the PostgreSQL compatible server version (PostgreSQL).",
450    true,
451)
452.read_only();
453
454pub static SERVER_VERSION_NUM: VarDefinition = VarDefinition::new(
455    "server_version_num",
456    value!(i32; (cast::u8_to_i32(SERVER_MAJOR_VERSION) * 10_000)
457        + (cast::u8_to_i32(SERVER_MINOR_VERSION) * 100)
458        + cast::u8_to_i32(SERVER_PATCH_VERSION)),
459    "Shows the PostgreSQL compatible server version as an integer (PostgreSQL).",
460    true,
461)
462.read_only();
463
464pub static SQL_SAFE_UPDATES: VarDefinition = VarDefinition::new(
465    "sql_safe_updates",
466    value!(bool; false),
467    "Prohibits SQL statements that may be overly destructive (CockroachDB).",
468    true,
469);
470
471pub static STANDARD_CONFORMING_STRINGS: VarDefinition = VarDefinition::new(
472    "standard_conforming_strings",
473    value!(bool; true),
474    "Causes '...' strings to treat backslashes literally (PostgreSQL).",
475    true,
476)
477.fixed();
478
479pub static TIMEZONE: VarDefinition = VarDefinition::new(
480    // TimeZone has nonstandard capitalization for historical reasons.
481    "TimeZone",
482    value!(TimeZone; TimeZone::UTC),
483    "Sets the time zone for displaying and interpreting time stamps (PostgreSQL).",
484    true,
485);
486
487pub const TRANSACTION_ISOLATION_VAR_NAME: &str = "transaction_isolation";
488pub static TRANSACTION_ISOLATION: VarDefinition = VarDefinition::new(
489    TRANSACTION_ISOLATION_VAR_NAME,
490    value!(IsolationLevel; IsolationLevel::StrictSerializable),
491    "Sets the current transaction's isolation level (PostgreSQL).",
492    true,
493);
494
495pub static MAX_KAFKA_CONNECTIONS: VarDefinition = VarDefinition::new(
496    "max_kafka_connections",
497    value!(u32; 1000),
498    "The maximum number of Kafka connections in the region, across all schemas (Materialize).",
499    true,
500);
501
502pub static MAX_POSTGRES_CONNECTIONS: VarDefinition = VarDefinition::new(
503    "max_postgres_connections",
504    value!(u32; 1000),
505    "The maximum number of PostgreSQL connections in the region, across all schemas (Materialize).",
506    true,
507);
508
509pub static MAX_MYSQL_CONNECTIONS: VarDefinition = VarDefinition::new(
510    "max_mysql_connections",
511    value!(u32; 1000),
512    "The maximum number of MySQL connections in the region, across all schemas (Materialize).",
513    true,
514);
515
516pub static MAX_SQL_SERVER_CONNECTIONS: VarDefinition = VarDefinition::new(
517    "max_sql_server_connections",
518    value!(u32; 1000),
519    "The maximum number of SQL Server connections in the region, across all schemas (Materialize).",
520    true,
521);
522
523pub static MAX_AWS_PRIVATELINK_CONNECTIONS: VarDefinition = VarDefinition::new(
524    "max_aws_privatelink_connections",
525    value!(u32; 0),
526    "The maximum number of AWS PrivateLink connections in the region, across all schemas (Materialize).",
527    true,
528);
529
530pub static MAX_TABLES: VarDefinition = VarDefinition::new(
531    "max_tables",
532    value!(u32; 200),
533    "The maximum number of tables in the region, across all schemas (Materialize).",
534    true,
535);
536
537pub static MAX_SOURCES: VarDefinition = VarDefinition::new(
538    "max_sources",
539    value!(u32; 200),
540    "The maximum number of sources in the region, across all schemas (Materialize).",
541    true,
542);
543
544pub static MAX_SINKS: VarDefinition = VarDefinition::new(
545    "max_sinks",
546    value!(u32; 1000),
547    "The maximum number of sinks in the region, across all schemas (Materialize).",
548    true,
549);
550
551pub static MAX_MATERIALIZED_VIEWS: VarDefinition = VarDefinition::new(
552    "max_materialized_views",
553    value!(u32; 500),
554    "The maximum number of materialized views in the region, across all schemas (Materialize).",
555    true,
556);
557
558pub static MAX_CLUSTERS: VarDefinition = VarDefinition::new(
559    "max_clusters",
560    value!(u32; 25),
561    "The maximum number of clusters in the region (Materialize).",
562    true,
563);
564
565pub static MAX_REPLICAS_PER_CLUSTER: VarDefinition = VarDefinition::new(
566    "max_replicas_per_cluster",
567    value!(u32; 5),
568    "The maximum number of replicas of a single cluster (Materialize).",
569    true,
570);
571
572pub static MAX_CREDIT_CONSUMPTION_RATE: VarDefinition = VarDefinition::new_lazy(
573    "max_credit_consumption_rate",
574    lazy_value!(Numeric; || 1024.into()),
575    "The maximum rate of credit consumption in a region. Credits are consumed based on the size of cluster replicas in use (Materialize).",
576    true,
577)
578.with_constraint(&NUMERIC_NON_NEGATIVE);
579
580pub static MAX_DATABASES: VarDefinition = VarDefinition::new(
581    "max_databases",
582    value!(u32; 1000),
583    "The maximum number of databases in the region (Materialize).",
584    true,
585);
586
587pub static MAX_SCHEMAS_PER_DATABASE: VarDefinition = VarDefinition::new(
588    "max_schemas_per_database",
589    value!(u32; 1000),
590    "The maximum number of schemas in a database (Materialize).",
591    true,
592);
593
594pub static MAX_OBJECTS_PER_SCHEMA: VarDefinition = VarDefinition::new(
595    "max_objects_per_schema",
596    value!(u32; 1000),
597    "The maximum number of objects in a schema (Materialize).",
598    true,
599);
600
601pub static MAX_SECRETS: VarDefinition = VarDefinition::new(
602    "max_secrets",
603    value!(u32; 100),
604    "The maximum number of secrets in the region, across all schemas (Materialize).",
605    true,
606);
607
608pub static MAX_ROLES: VarDefinition = VarDefinition::new(
609    "max_roles",
610    value!(u32; 1000),
611    "The maximum number of roles in the region (Materialize).",
612    true,
613);
614
615pub static MAX_NETWORK_POLICIES: VarDefinition = VarDefinition::new(
616    "max_network_policies",
617    value!(u32; 25),
618    "The maximum number of network policies in the region.",
619    true,
620);
621
622pub static MAX_QUERY_POLICIES: VarDefinition = VarDefinition::new(
623    "max_query_policies",
624    value!(u32; 25),
625    "The maximum number of query policies in the region.",
626    true,
627);
628
629pub static MAX_RULES_PER_NETWORK_POLICY: VarDefinition = VarDefinition::new(
630    "max_rules_per_network_policy",
631    value!(u32; 25),
632    "The maximum number of rules per network policies.",
633    true,
634);
635
636// Cloud environmentd is configured with 4 GiB of RAM, so 1 GiB is a good heuristic for a single
637// query.
638//
639// We constrain this parameter to a minimum of 1MB, to avoid accidental usage of values that will
640// interfere with queries executed by the system itself.
641//
642// TODO(jkosh44) Eventually we want to be able to return arbitrary sized results.
643pub static MAX_RESULT_SIZE: VarDefinition = VarDefinition::new(
644    "max_result_size",
645    value!(ByteSize; ByteSize::gb(1)),
646    "The maximum size in bytes for an internal query result (Materialize).",
647    true,
648)
649.with_constraint(&BYTESIZE_AT_LEAST_1MB);
650
651pub static MAX_QUERY_RESULT_SIZE: VarDefinition = VarDefinition::new(
652    "max_query_result_size",
653    value!(ByteSize; ByteSize::gb(1)),
654    "The maximum size in bytes for a single query's result (Materialize).",
655    true,
656);
657
658pub static MAX_COPY_FROM_ROW_SIZE: VarDefinition = VarDefinition::new(
659    "max_copy_from_row_size",
660    value!(ByteSize; ByteSize::mb(128)),
661    "The maximum size in bytes for a single COPY FROM STDIN row (Materialize).",
662    true,
663);
664
665pub static MAX_IDENTIFIER_LENGTH: VarDefinition = VarDefinition::new(
666    "max_identifier_length",
667    value!(usize; mz_sql_lexer::lexer::MAX_IDENTIFIER_LENGTH),
668    "The maximum length of object identifiers in bytes (PostgreSQL).",
669    true,
670);
671
672pub static WELCOME_MESSAGE: VarDefinition = VarDefinition::new(
673    "welcome_message",
674    value!(bool; true),
675    "Whether to send a notice with a welcome message after a successful connection (Materialize).",
676    true,
677);
678
679/// The logical compaction window for builtin tables and sources that have the
680/// `retained_metrics_relation` flag set.
681///
682/// The existence of this variable is a bit of a hack until we have a fully
683/// general solution for controlling retention windows.
684pub static METRICS_RETENTION: VarDefinition = VarDefinition::new(
685    "metrics_retention",
686    // 30 days
687    value!(Duration; Duration::from_secs(30 * 24 * 60 * 60)),
688    "The time to retain cluster utilization metrics (Materialize).",
689    false,
690);
691
692/// Curated metric sinks to keep from running, as a comma-separated list of names from `CURATED`
693/// in `mz_adapter::coord::metric_sink`. An entry naming no definition is tolerated, so a rollback
694/// that drops a definition needs no lockstep edit here.
695///
696/// Denying tears the sink down on replicas already running it; undenying puts it back. It
697/// subtracts from `enable_metric_sink`: with that flag off nothing installs regardless.
698pub static DISABLED_METRIC_SINKS: VarDefinition = VarDefinition::new(
699    "disabled_metric_sinks",
700    value!(Vec<Ident>; Vec::new()),
701    "Curated metric sinks to tear down and keep from installing, comma-separated (Materialize).",
702    false,
703);
704
705pub static ALLOWED_CLUSTER_REPLICA_SIZES: VarDefinition = VarDefinition::new(
706    "allowed_cluster_replica_sizes",
707    value!(Vec<Ident>; Vec::new()),
708    "The allowed sizes when creating a new cluster replica (Materialize).",
709    true,
710);
711
712/// Sizes the OCC write semaphore at boot. Zero permits would block every
713/// read-then-write until its `statement_timeout`, so the value must be at
714/// least 1.
715pub static MAX_CONCURRENT_OCC_WRITES: VarDefinition = VarDefinition::new(
716    "max_concurrent_occ_writes",
717    value!(u32; 4),
718    "Maximum number of concurrent read-then-write (DELETE/UPDATE) operations using OCC. Read at startup; changes require an environmentd restart (Materialize).",
719    false,
720)
721.with_constraint(&U32_AT_LEAST_1);
722
723pub static MAX_OCC_RETRIES: VarDefinition = VarDefinition::new(
724    "max_occ_retries",
725    value!(u32; 1000),
726    "Maximum number of OCC retry attempts per read-then-write operation before giving up (Materialize).",
727    false,
728);
729
730pub static PERSIST_FAST_PATH_LIMIT: VarDefinition = VarDefinition::new(
731    "persist_fast_path_limit",
732    value!(usize; 25),
733    "An exclusive upper bound on the number of results we may return from a Persist fast-path peek; \
734    queries that may return more results will follow the normal / slow path. \
735    Setting this to 0 disables the feature.",
736    false,
737);
738
739/// Controls `mz_adapter::coord::timestamp_oracle::postgres_oracle::DynamicConfig::pg_connection_pool_max_size`.
740pub static PG_TIMESTAMP_ORACLE_CONNECTION_POOL_MAX_SIZE: VarDefinition = VarDefinition::new(
741    "pg_timestamp_oracle_connection_pool_max_size",
742    value!(usize; DEFAULT_PG_TIMESTAMP_ORACLE_CONNPOOL_MAX_SIZE),
743    "Maximum size of the Postgres/CRDB connection pool, used by the Postgres/CRDB timestamp oracle.",
744    false,
745);
746
747/// Controls `mz_adapter::coord::timestamp_oracle::postgres_oracle::DynamicConfig::pg_connection_pool_max_wait`.
748pub static PG_TIMESTAMP_ORACLE_CONNECTION_POOL_MAX_WAIT: VarDefinition = VarDefinition::new(
749    "pg_timestamp_oracle_connection_pool_max_wait",
750    value!(Option<Duration>; Some(DEFAULT_PG_TIMESTAMP_ORACLE_CONNPOOL_MAX_WAIT)),
751    "The maximum time to wait when attempting to obtain a connection from the Postgres/CRDB connection pool, used by the Postgres/CRDB timestamp oracle.",
752    false,
753);
754
755/// Controls `mz_adapter::coord::timestamp_oracle::postgres_oracle::DynamicConfig::pg_connection_pool_ttl`.
756pub static PG_TIMESTAMP_ORACLE_CONNECTION_POOL_TTL: VarDefinition = VarDefinition::new(
757    "pg_timestamp_oracle_connection_pool_ttl",
758    value!(Duration; DEFAULT_PG_TIMESTAMP_ORACLE_CONNPOOL_TTL),
759    "The minimum TTL of a Consensus connection to Postgres/CRDB before it is proactively terminated",
760    false,
761);
762
763/// Controls `mz_adapter::coord::timestamp_oracle::postgres_oracle::DynamicConfig::pg_connection_pool_ttl_stagger`.
764pub static PG_TIMESTAMP_ORACLE_CONNECTION_POOL_TTL_STAGGER: VarDefinition = VarDefinition::new(
765    "pg_timestamp_oracle_connection_pool_ttl_stagger",
766    value!(Duration; DEFAULT_PG_TIMESTAMP_ORACLE_CONNPOOL_TTL_STAGGER),
767    "The minimum time between TTLing Consensus connections to Postgres/CRDB.",
768    false,
769);
770
771pub static UNSAFE_NEW_TRANSACTION_WALL_TIME: VarDefinition = VarDefinition::new(
772    "unsafe_new_transaction_wall_time",
773    value!(Option<CheckedTimestamp<DateTime<Utc>>>; None),
774    "Sets the wall time for all new explicit or implicit transactions to control the value of `now()`. \
775    If not set, uses the system's clock.",
776    // This needs to be true because `user_visible: false` things are only modifiable by the mz_system
777    // and mz_support users, and we want sqllogictest to have access with its user. Because the name
778    // starts with "unsafe" it still won't be visible or changeable by users unless unsafe mode is
779    // enabled.
780    true,
781);
782
783pub static SCRAM_ITERATIONS: VarDefinition = VarDefinition::new(
784    "scram_iterations",
785    // / The default iteration count as suggested by
786    // / <https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html>
787    value!(NonZeroU32; NonZeroU32::new(600_000).unwrap()),
788    "Iterations to use when hashing passwords. Higher iterations are more secure, but take longer to validated. \
789    Please consider the security risks before reducing this below the default value.",
790    true,
791);
792
793/// Tuning for RocksDB used by `UPSERT` sources that takes effect on restart.
794pub mod upsert_rocksdb {
795    use super::*;
796    use mz_rocksdb_types::config::{CompactionStyle, CompressionType};
797
798    pub static UPSERT_ROCKSDB_COMPACTION_STYLE: VarDefinition = VarDefinition::new(
799        "upsert_rocksdb_compaction_style",
800        value!(CompactionStyle; mz_rocksdb_types::defaults::DEFAULT_COMPACTION_STYLE),
801        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
802        sources. Described in the `mz_rocksdb_types::config` module. \
803        Only takes effect on source restart (Materialize).",
804        false,
805    );
806
807    pub static UPSERT_ROCKSDB_OPTIMIZE_COMPACTION_MEMTABLE_BUDGET: VarDefinition =
808        VarDefinition::new(
809            "upsert_rocksdb_optimize_compaction_memtable_budget",
810            value!(usize; mz_rocksdb_types::defaults::DEFAULT_OPTIMIZE_COMPACTION_MEMTABLE_BUDGET),
811            "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
812        sources. Described in the `mz_rocksdb_types::config` module. \
813        Only takes effect on source restart (Materialize).",
814            false,
815        );
816
817    pub static UPSERT_ROCKSDB_LEVEL_COMPACTION_DYNAMIC_LEVEL_BYTES: VarDefinition =
818        VarDefinition::new(
819            "upsert_rocksdb_level_compaction_dynamic_level_bytes",
820            value!(bool; mz_rocksdb_types::defaults::DEFAULT_LEVEL_COMPACTION_DYNAMIC_LEVEL_BYTES),
821            "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
822        sources. Described in the `mz_rocksdb_types::config` module. \
823        Only takes effect on source restart (Materialize).",
824            false,
825        );
826
827    pub static UPSERT_ROCKSDB_UNIVERSAL_COMPACTION_RATIO: VarDefinition = VarDefinition::new(
828        "upsert_rocksdb_universal_compaction_ratio",
829        value!(i32; mz_rocksdb_types::defaults::DEFAULT_UNIVERSAL_COMPACTION_RATIO),
830        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
831        sources. Described in the `mz_rocksdb_types::config` module. \
832        Only takes effect on source restart (Materialize).",
833        false,
834    );
835
836    pub static UPSERT_ROCKSDB_PARALLELISM: VarDefinition = VarDefinition::new(
837        "upsert_rocksdb_parallelism",
838        value!(Option<i32>; mz_rocksdb_types::defaults::DEFAULT_PARALLELISM),
839        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
840        sources. Described in the `mz_rocksdb_types::config` module. \
841        Only takes effect on source restart (Materialize).",
842        false,
843    );
844
845    pub static UPSERT_ROCKSDB_COMPRESSION_TYPE: VarDefinition = VarDefinition::new(
846        "upsert_rocksdb_compression_type",
847        value!(CompressionType; mz_rocksdb_types::defaults::DEFAULT_COMPRESSION_TYPE),
848        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
849        sources. Described in the `mz_rocksdb_types::config` module. \
850        Only takes effect on source restart (Materialize).",
851        false,
852    );
853
854    pub static UPSERT_ROCKSDB_BOTTOMMOST_COMPRESSION_TYPE: VarDefinition = VarDefinition::new(
855        "upsert_rocksdb_bottommost_compression_type",
856        value!(CompressionType; mz_rocksdb_types::defaults::DEFAULT_BOTTOMMOST_COMPRESSION_TYPE),
857        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
858        sources. Described in the `mz_rocksdb_types::config` module. \
859        Only takes effect on source restart (Materialize).",
860        false,
861    );
862
863    pub static UPSERT_ROCKSDB_BATCH_SIZE: VarDefinition = VarDefinition::new(
864        "upsert_rocksdb_batch_size",
865        value!(usize; mz_rocksdb_types::defaults::DEFAULT_BATCH_SIZE),
866        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
867        sources. Described in the `mz_rocksdb_types::config` module. \
868        Can be changed dynamically (Materialize).",
869        false,
870    );
871
872    pub static UPSERT_ROCKSDB_RETRY_DURATION: VarDefinition = VarDefinition::new(
873        "upsert_rocksdb_retry_duration",
874        value!(Duration; mz_rocksdb_types::defaults::DEFAULT_RETRY_DURATION),
875        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
876        sources. Described in the `mz_rocksdb_types::config` module. \
877        Only takes effect on source restart (Materialize).",
878        false,
879    );
880
881    pub static UPSERT_ROCKSDB_STATS_LOG_INTERVAL_SECONDS: VarDefinition = VarDefinition::new(
882        "upsert_rocksdb_stats_log_interval_seconds",
883        value!(u32; mz_rocksdb_types::defaults::DEFAULT_STATS_LOG_INTERVAL_S),
884        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
885        sources. Described in the `mz_rocksdb_types::config` module. \
886        Only takes effect on source restart (Materialize).",
887        false,
888    );
889
890    pub static UPSERT_ROCKSDB_STATS_PERSIST_INTERVAL_SECONDS: VarDefinition = VarDefinition::new(
891        "upsert_rocksdb_stats_persist_interval_seconds",
892        value!(u32; mz_rocksdb_types::defaults::DEFAULT_STATS_PERSIST_INTERVAL_S),
893        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
894        sources. Described in the `mz_rocksdb_types::config` module. \
895        Only takes effect on source restart (Materialize).",
896        false,
897    );
898
899    pub static UPSERT_ROCKSDB_POINT_LOOKUP_BLOCK_CACHE_SIZE_MB: VarDefinition = VarDefinition::new(
900        "upsert_rocksdb_point_lookup_block_cache_size_mb",
901        value!(Option<u32>; None),
902        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
903        sources. Described in the `mz_rocksdb_types::config` module. \
904        Only takes effect on source restart (Materialize).",
905        false,
906    );
907
908    /// The number of times by which allocated buffers will be shrinked in upsert rocksdb.
909    /// If value is 0, then no shrinking will occur.
910    pub static UPSERT_ROCKSDB_SHRINK_ALLOCATED_BUFFERS_BY_RATIO: VarDefinition = VarDefinition::new(
911        "upsert_rocksdb_shrink_allocated_buffers_by_ratio",
912        value!(usize; mz_rocksdb_types::defaults::DEFAULT_SHRINK_BUFFERS_BY_RATIO),
913        "The number of times by which allocated buffers will be shrinked in upsert rocksdb.",
914        false,
915    );
916
917    /// Only used if `upsert_rocksdb_write_buffer_manager_memory_bytes` is also set
918    /// and write buffer manager is enabled
919    pub static UPSERT_ROCKSDB_WRITE_BUFFER_MANAGER_CLUSTER_MEMORY_FRACTION: VarDefinition =
920        VarDefinition::new(
921            "upsert_rocksdb_write_buffer_manager_cluster_memory_fraction",
922            value!(Option<Numeric>; None),
923            "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
924        sources. Described in the `mz_rocksdb_types::config` module. \
925        Only takes effect on source restart (Materialize).",
926            false,
927        );
928
929    /// `upsert_rocksdb_write_buffer_manager_memory_bytes` needs to be set for write buffer manager to be
930    /// used.
931    pub static UPSERT_ROCKSDB_WRITE_BUFFER_MANAGER_MEMORY_BYTES: VarDefinition = VarDefinition::new(
932        "upsert_rocksdb_write_buffer_manager_memory_bytes",
933        value!(Option<usize>; None),
934        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
935        sources. Described in the `mz_rocksdb_types::config` module. \
936        Only takes effect on source restart (Materialize).",
937        false,
938    );
939
940    pub static UPSERT_ROCKSDB_WRITE_BUFFER_MANAGER_ALLOW_STALL: VarDefinition = VarDefinition::new(
941        "upsert_rocksdb_write_buffer_manager_allow_stall",
942        value!(bool; false),
943        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
944        sources. Described in the `mz_rocksdb_types::config` module. \
945        Only takes effect on source restart (Materialize).",
946        false,
947    );
948}
949
950pub static LOGGING_FILTER: VarDefinition = VarDefinition::new_lazy(
951    "log_filter",
952    lazy_value!(CloneableEnvFilter; || CloneableEnvFilter::from_str("info").expect("valid EnvFilter")),
953    "Sets the filter to apply to stderr logging.",
954    false,
955);
956
957pub static OPENTELEMETRY_FILTER: VarDefinition = VarDefinition::new_lazy(
958    "opentelemetry_filter",
959    lazy_value!(CloneableEnvFilter; || CloneableEnvFilter::from_str("info").expect("valid EnvFilter")),
960    "Sets the filter to apply to OpenTelemetry-backed distributed tracing.",
961    false,
962);
963
964pub static LOGGING_FILTER_DEFAULTS: VarDefinition = VarDefinition::new_lazy(
965    "log_filter_defaults",
966    lazy_value!(Vec<SerializableDirective>; || {
967        mz_ore::tracing::LOGGING_DEFAULTS
968            .iter()
969            .map(|d| d.clone().into())
970            .collect()
971    }),
972    "Sets additional default directives to apply to stderr logging. \
973        These apply to all variations of `log_filter`. Directives other than \
974        `module=off` are likely incorrect.",
975    false,
976);
977
978pub static OPENTELEMETRY_FILTER_DEFAULTS: VarDefinition = VarDefinition::new_lazy(
979    "opentelemetry_filter_defaults",
980    lazy_value!(Vec<SerializableDirective>; || {
981        mz_ore::tracing::OPENTELEMETRY_DEFAULTS
982            .iter()
983            .map(|d| d.clone().into())
984            .collect()
985    }),
986    "Sets additional default directives to apply to OpenTelemetry-backed \
987        distributed tracing. \
988        These apply to all variations of `opentelemetry_filter`. Directives other than \
989        `module=off` are likely incorrect.",
990    false,
991);
992
993pub static SENTRY_FILTERS: VarDefinition = VarDefinition::new_lazy(
994    "sentry_filters",
995    lazy_value!(Vec<SerializableDirective>; || {
996        mz_ore::tracing::SENTRY_DEFAULTS
997            .iter()
998            .map(|d| d.clone().into())
999            .collect()
1000    }),
1001    "Sets additional default directives to apply to sentry logging. \
1002        These apply on top of a default `info` directive. Directives other than \
1003        `module=off` are likely incorrect.",
1004    false,
1005);
1006
1007pub static WEBHOOKS_SECRETS_CACHING_TTL_SECS: VarDefinition = VarDefinition::new_lazy(
1008    "webhooks_secrets_caching_ttl_secs",
1009    lazy_value!(usize; || {
1010        usize::cast_from(mz_secrets::cache::DEFAULT_TTL_SECS)
1011    }),
1012    "Sets the time-to-live for values in the Webhooks secrets cache.",
1013    false,
1014);
1015
1016pub static COORD_SLOW_MESSAGE_WARN_THRESHOLD: VarDefinition = VarDefinition::new(
1017    "coord_slow_message_warn_threshold",
1018    value!(Duration; Duration::from_secs(30)),
1019    "Sets the threshold at which we will error! for a coordinator message being slow.",
1020    false,
1021);
1022
1023/// Controls the connect_timeout setting when connecting to PG via `mz_postgres_util`.
1024pub static PG_SOURCE_CONNECT_TIMEOUT: VarDefinition = VarDefinition::new(
1025    "pg_source_connect_timeout",
1026    value!(Duration; DEFAULT_PG_SOURCE_CONNECT_TIMEOUT),
1027    "Sets the timeout applied to socket-level connection attempts for PG \
1028    replication connections (Materialize).",
1029    false,
1030);
1031
1032/// Sets the maximum number of TCP keepalive probes that will be sent before dropping a connection
1033/// when connecting to PG via `mz_postgres_util`.
1034pub static PG_SOURCE_TCP_KEEPALIVES_RETRIES: VarDefinition = VarDefinition::new(
1035    "pg_source_tcp_keepalives_retries",
1036    value!(u32; DEFAULT_PG_SOURCE_TCP_KEEPALIVES_RETRIES),
1037    "Sets the maximum number of TCP keepalive probes that will be sent before dropping \
1038    a connection when connecting to PG via `mz_postgres_util` (Materialize).",
1039    false,
1040);
1041
1042/// Sets the amount of idle time before a keepalive packet is sent on the connection when connecting
1043/// to PG via `mz_postgres_util`.
1044pub static PG_SOURCE_TCP_KEEPALIVES_IDLE: VarDefinition = VarDefinition::new(
1045    "pg_source_tcp_keepalives_idle",
1046    value!(Duration; DEFAULT_PG_SOURCE_TCP_KEEPALIVES_IDLE),
1047    "Sets the amount of idle time before a keepalive packet is sent on the connection \
1048        when connecting to PG via `mz_postgres_util` (Materialize).",
1049    false,
1050);
1051
1052/// Sets the time interval between TCP keepalive probes when connecting to PG via `mz_postgres_util`.
1053pub static PG_SOURCE_TCP_KEEPALIVES_INTERVAL: VarDefinition = VarDefinition::new(
1054    "pg_source_tcp_keepalives_interval",
1055    value!(Duration; DEFAULT_PG_SOURCE_TCP_KEEPALIVES_INTERVAL),
1056    "Sets the time interval between TCP keepalive probes when connecting to PG via \
1057        replication (Materialize).",
1058    false,
1059);
1060
1061/// Sets the TCP user timeout when connecting to PG via `mz_postgres_util`.
1062pub static PG_SOURCE_TCP_USER_TIMEOUT: VarDefinition = VarDefinition::new(
1063    "pg_source_tcp_user_timeout",
1064    value!(Duration; DEFAULT_PG_SOURCE_TCP_USER_TIMEOUT),
1065    "Sets the TCP user timeout when connecting to PG via `mz_postgres_util` (Materialize).",
1066    false,
1067);
1068
1069/// Sets whether to apply the TCP configuration parameters on the server when
1070/// connecting to PG via `mz_postgres_util`.
1071pub static PG_SOURCE_TCP_CONFIGURE_SERVER: VarDefinition = VarDefinition::new(
1072    "pg_source_tcp_configure_server",
1073    value!(bool; DEFAULT_PG_SOURCE_TCP_CONFIGURE_SERVER),
1074    "Sets whether to apply the TCP configuration parameters on the server when connecting to PG via `mz_postgres_util` (Materialize).",
1075    false,
1076);
1077
1078/// Sets the `statement_timeout` value to use during the snapshotting phase of
1079/// PG sources.
1080pub static PG_SOURCE_SNAPSHOT_STATEMENT_TIMEOUT: VarDefinition = VarDefinition::new(
1081    "pg_source_snapshot_statement_timeout",
1082    value!(Duration; mz_postgres_util::DEFAULT_SNAPSHOT_STATEMENT_TIMEOUT),
1083    "Sets the `statement_timeout` value to use during the snapshotting phase of PG sources (Materialize)",
1084    false,
1085);
1086
1087/// Sets the `wal_sender_timeout` value to use during the replication phase of
1088/// PG sources.
1089pub static PG_SOURCE_WAL_SENDER_TIMEOUT: VarDefinition = VarDefinition::new(
1090    "pg_source_wal_sender_timeout",
1091    value!(Option<Duration>; DEFAULT_PG_SOURCE_WAL_SENDER_TIMEOUT),
1092    "Sets the `wal_sender_timeout` value to use during the replication phase of PG sources (Materialize)",
1093    false,
1094);
1095
1096/// Please see `PgSourceSnapshotConfig`.
1097pub static PG_SOURCE_SNAPSHOT_COLLECT_STRICT_COUNT: VarDefinition = VarDefinition::new(
1098    "pg_source_snapshot_collect_strict_count",
1099    value!(bool; mz_storage_types::parameters::PgSourceSnapshotConfig::new().collect_strict_count),
1100    "Please see <https://dev.materialize.com/api/rust-private\
1101        /mz_storage_types/parameters\
1102        /struct.PgSourceSnapshotConfig.html#structfield.collect_strict_count>",
1103    false,
1104);
1105
1106/// Sets the time between TCP keepalive probes when connecting to MySQL via `mz_mysql_util`.
1107pub static MYSQL_SOURCE_TCP_KEEPALIVE: VarDefinition = VarDefinition::new(
1108    "mysql_source_tcp_keepalive",
1109    value!(Duration; mz_mysql_util::DEFAULT_TCP_KEEPALIVE),
1110    "Sets the time between TCP keepalive probes when connecting to MySQL",
1111    false,
1112);
1113
1114/// Sets the `max_execution_time` value to use during the snapshotting phase of
1115/// MySQL sources.
1116pub static MYSQL_SOURCE_SNAPSHOT_MAX_EXECUTION_TIME: VarDefinition = VarDefinition::new(
1117    "mysql_source_snapshot_max_execution_time",
1118    value!(Duration; mz_mysql_util::DEFAULT_SNAPSHOT_MAX_EXECUTION_TIME),
1119    "Sets the `max_execution_time` value to use during the snapshotting phase of MySQL sources (Materialize)",
1120    false,
1121);
1122
1123/// Sets the `lock_wait_timeout` value to use during the snapshotting phase of
1124/// MySQL sources.
1125pub static MYSQL_SOURCE_SNAPSHOT_LOCK_WAIT_TIMEOUT: VarDefinition = VarDefinition::new(
1126    "mysql_source_snapshot_lock_wait_timeout",
1127    value!(Duration; mz_mysql_util::DEFAULT_SNAPSHOT_LOCK_WAIT_TIMEOUT),
1128    "Sets the `lock_wait_timeout` value to use during the snapshotting phase of MySQL sources (Materialize)",
1129    false,
1130);
1131
1132/// Sets the `wait_timeout` session value on connections used during the
1133/// snapshotting phase of MySQL sources.
1134pub static MYSQL_SOURCE_SNAPSHOT_WAIT_TIMEOUT: VarDefinition = VarDefinition::new(
1135    "mysql_source_snapshot_wait_timeout",
1136    value!(Duration; mz_mysql_util::DEFAULT_SNAPSHOT_WAIT_TIMEOUT),
1137    "Sets the `wait_timeout` value to use on connections during the snapshotting phase of MySQL sources (Materialize)",
1138    false,
1139);
1140
1141/// Sets the timeout for establishing an authenticated connection to MySQL
1142pub static MYSQL_SOURCE_CONNECT_TIMEOUT: VarDefinition = VarDefinition::new(
1143    "mysql_source_connect_timeout",
1144    value!(Duration; mz_mysql_util::DEFAULT_CONNECT_TIMEOUT),
1145    "Sets the timeout for establishing an authenticated connection to MySQL",
1146    false,
1147);
1148
1149/// Controls the check interval for connections to SSH bastions via `mz_ssh_util`.
1150pub static SSH_CHECK_INTERVAL: VarDefinition = VarDefinition::new(
1151    "ssh_check_interval",
1152    value!(Duration; mz_ssh_util::tunnel::DEFAULT_CHECK_INTERVAL),
1153    "Controls the check interval for connections to SSH bastions via `mz_ssh_util`.",
1154    false,
1155)
1156.with_constraint(&NON_ZERO_DURATION);
1157
1158/// Controls the connect timeout for connections to SSH bastions via `mz_ssh_util`.
1159pub static SSH_CONNECT_TIMEOUT: VarDefinition = VarDefinition::new(
1160    "ssh_connect_timeout",
1161    value!(Duration; mz_ssh_util::tunnel::DEFAULT_CONNECT_TIMEOUT),
1162    "Controls the connect timeout for connections to SSH bastions via `mz_ssh_util`.",
1163    false,
1164);
1165
1166/// Controls the keepalive idle interval for connections to SSH bastions via `mz_ssh_util`.
1167pub static SSH_KEEPALIVES_IDLE: VarDefinition = VarDefinition::new(
1168    "ssh_keepalives_idle",
1169    value!(Duration; mz_ssh_util::tunnel::DEFAULT_KEEPALIVES_IDLE),
1170    "Controls the keepalive idle interval for connections to SSH bastions via `mz_ssh_util`.",
1171    false,
1172);
1173
1174/// Enables `socket.keepalive.enable` for rdkafka client connections. Defaults to true.
1175pub static KAFKA_SOCKET_KEEPALIVE: VarDefinition = VarDefinition::new(
1176    "kafka_socket_keepalive",
1177    value!(bool; mz_kafka_util::client::DEFAULT_KEEPALIVE),
1178    "Enables `socket.keepalive.enable` for rdkafka client connections. Defaults to true.",
1179    false,
1180);
1181
1182/// Controls `socket.timeout.ms` for rdkafka client connections. Defaults to the rdkafka default
1183/// (60000ms). Cannot be greater than 300000ms, more than 100ms greater than
1184/// `kafka_transaction_timeout`, or less than 10ms.
1185pub static KAFKA_SOCKET_TIMEOUT: VarDefinition = VarDefinition::new(
1186    "kafka_socket_timeout",
1187    value!(Option<Duration>; None),
1188    "Controls `socket.timeout.ms` for rdkafka \
1189        client connections. Defaults to the rdkafka default (60000ms) or \
1190        the set transaction timeout + 100ms, whichever one is smaller. \
1191        Cannot be greater than 300000ms, more than 100ms greater than \
1192        `kafka_transaction_timeout`, or less than 10ms.",
1193    false,
1194);
1195
1196/// Controls `transaction.timeout.ms` for rdkafka client connections. Defaults to the rdkafka default
1197/// (60000ms). Cannot be greater than `i32::MAX` or less than 1000ms.
1198pub static KAFKA_TRANSACTION_TIMEOUT: VarDefinition = VarDefinition::new(
1199    "kafka_transaction_timeout",
1200    value!(Duration; mz_kafka_util::client::DEFAULT_TRANSACTION_TIMEOUT),
1201    "Controls `transaction.timeout.ms` for rdkafka \
1202        client connections. Defaults to the 10min. \
1203        Cannot be greater than `i32::MAX` or less than 1000ms.",
1204    false,
1205);
1206
1207/// Controls `socket.connection.setup.timeout.ms` for rdkafka client connections. Defaults to the rdkafka default
1208/// (30000ms). Cannot be greater than `i32::MAX` or less than 1000ms
1209pub static KAFKA_SOCKET_CONNECTION_SETUP_TIMEOUT: VarDefinition = VarDefinition::new(
1210    "kafka_socket_connection_setup_timeout",
1211    value!(Duration; mz_kafka_util::client::DEFAULT_SOCKET_CONNECTION_SETUP_TIMEOUT),
1212    "Controls `socket.connection.setup.timeout.ms` for rdkafka \
1213        client connections. Defaults to the rdkafka default (30000ms). \
1214        Cannot be greater than `i32::MAX` or less than 1000ms",
1215    false,
1216);
1217
1218/// Controls the timeout when fetching kafka metadata. Defaults to 10s.
1219pub static KAFKA_FETCH_METADATA_TIMEOUT: VarDefinition = VarDefinition::new(
1220    "kafka_fetch_metadata_timeout",
1221    value!(Duration; mz_kafka_util::client::DEFAULT_FETCH_METADATA_TIMEOUT),
1222    "Controls the timeout when fetching kafka metadata. \
1223        Defaults to 10s.",
1224    false,
1225);
1226
1227/// Controls the timeout when fetching kafka progress records. Defaults to 60s.
1228pub static KAFKA_PROGRESS_RECORD_FETCH_TIMEOUT: VarDefinition = VarDefinition::new(
1229    "kafka_progress_record_fetch_timeout",
1230    value!(Option<Duration>; None),
1231    "Controls the timeout when fetching kafka progress records. \
1232        Defaults to 60s or the transaction timeout, whichever one is larger.",
1233    false,
1234);
1235
1236/// The maximum number of in-flight bytes emitted by persist_sources feeding _storage
1237/// dataflows_.
1238/// Currently defaults to 256MiB = 268435456 bytes
1239/// Note: Backpressure will only be turned on if disk is enabled based on
1240/// `storage_dataflow_max_inflight_bytes_disk_only` flag
1241pub static STORAGE_DATAFLOW_MAX_INFLIGHT_BYTES: VarDefinition = VarDefinition::new(
1242    "storage_dataflow_max_inflight_bytes",
1243    value!(Option<usize>; Some(256 * 1024 * 1024)),
1244    "The maximum number of in-flight bytes emitted by persist_sources feeding \
1245        storage dataflows. Defaults to backpressure enabled (Materialize).",
1246    false,
1247);
1248
1249/// Configuration ratio to shrink unusef buffers in upsert by.
1250/// For eg: is 2 is set, then the buffers will be reduced by 2 i.e. halved.
1251/// Default is 0, which means shrinking is disabled.
1252pub static STORAGE_SHRINK_UPSERT_UNUSED_BUFFERS_BY_RATIO: VarDefinition = VarDefinition::new(
1253    "storage_shrink_upsert_unused_buffers_by_ratio",
1254    value!(usize; 0),
1255    "Configuration ratio to shrink unusef buffers in upsert by",
1256    false,
1257);
1258
1259/// The fraction of the cluster replica size to be used as the maximum number of
1260/// in-flight bytes emitted by persist_sources feeding storage dataflows.
1261/// If not configured, the storage_dataflow_max_inflight_bytes value will be used.
1262/// For this value to be used storage_dataflow_max_inflight_bytes needs to be set.
1263pub static STORAGE_DATAFLOW_MAX_INFLIGHT_BYTES_TO_CLUSTER_SIZE_FRACTION: VarDefinition =
1264    VarDefinition::new_lazy(
1265        "storage_dataflow_max_inflight_bytes_to_cluster_size_fraction",
1266        lazy_value!(Option<Numeric>; || Some(0.01.into())),
1267        "The fraction of the cluster replica size to be used as the maximum number of \
1268            in-flight bytes emitted by persist_sources feeding storage dataflows. \
1269            If not configured, the storage_dataflow_max_inflight_bytes value will be used.",
1270        false,
1271    );
1272
1273pub static STORAGE_DATAFLOW_MAX_INFLIGHT_BYTES_DISK_ONLY: VarDefinition = VarDefinition::new(
1274    "storage_dataflow_max_inflight_bytes_disk_only",
1275    value!(bool; true),
1276    "Whether or not `storage_dataflow_max_inflight_bytes` applies only to \
1277        upsert dataflows using disks. Defaults to true (Materialize).",
1278    false,
1279);
1280
1281/// The interval to submit statistics to `mz_source_statistics_per_worker` and `mz_sink_statistics_per_worker`.
1282pub static STORAGE_STATISTICS_INTERVAL: VarDefinition = VarDefinition::new(
1283    "storage_statistics_interval",
1284    value!(Duration; mz_storage_types::parameters::STATISTICS_INTERVAL_DEFAULT),
1285    "The interval to submit statistics to `mz_source_statistics_per_worker` \
1286        and `mz_sink_statistics` (Materialize).",
1287    false,
1288)
1289.with_constraint(&NON_ZERO_DURATION);
1290
1291/// The interval to collect statistics for `mz_source_statistics_per_worker` and `mz_sink_statistics_per_worker` in
1292/// clusterd. Controls the accuracy of metrics.
1293pub static STORAGE_STATISTICS_COLLECTION_INTERVAL: VarDefinition = VarDefinition::new(
1294    "storage_statistics_collection_interval",
1295    value!(Duration; mz_storage_types::parameters::STATISTICS_COLLECTION_INTERVAL_DEFAULT),
1296    "The interval to collect statistics for `mz_source_statistics_per_worker` \
1297        and `mz_sink_statistics_per_worker` in clusterd. Controls the accuracy of metrics \
1298        (Materialize).",
1299    false,
1300);
1301
1302pub static STORAGE_RECORD_SOURCE_SINK_NAMESPACED_ERRORS: VarDefinition = VarDefinition::new(
1303    "storage_record_source_sink_namespaced_errors",
1304    value!(bool; true),
1305    "Whether or not to record namespaced errors in the status history tables",
1306    false,
1307);
1308
1309/// Boolean flag indicating whether to enable syncing from
1310/// LaunchDarkly. Can be turned off as an emergency measure to still
1311/// be able to alter parameters while LD is broken.
1312pub static ENABLE_LAUNCHDARKLY: VarDefinition = VarDefinition::new(
1313    "enable_launchdarkly",
1314    value!(bool; true),
1315    "Boolean flag indicating whether flag synchronization from LaunchDarkly should be enabled (Materialize).",
1316    false,
1317);
1318
1319/// Feature flag indicating whether real time recency is enabled. Not that
1320/// unlike other feature flags, this is made available at the session level, so
1321/// is additionally gated by a feature flag.
1322pub static REAL_TIME_RECENCY: VarDefinition = VarDefinition::new(
1323    "real_time_recency",
1324    value!(bool; false),
1325    "Feature flag indicating whether real time recency is enabled (Materialize).",
1326    true,
1327)
1328.with_feature_flag(&ALLOW_REAL_TIME_RECENCY);
1329
1330pub static REAL_TIME_RECENCY_TIMEOUT: VarDefinition = VarDefinition::new(
1331    "real_time_recency_timeout",
1332    value!(Duration; Duration::from_secs(10)),
1333    "Sets the maximum allowed duration of SELECTs that actively use real-time \
1334    recency, i.e. reach out to an external system to determine their most recencly exposed \
1335    data (Materialize).",
1336    true,
1337)
1338.with_feature_flag(&ALLOW_REAL_TIME_RECENCY);
1339
1340pub static EMIT_PLAN_INSIGHTS_NOTICE: VarDefinition = VarDefinition::new(
1341    "emit_plan_insights_notice",
1342    value!(bool; false),
1343    "Boolean flag indicating whether to send a NOTICE with JSON-formatted plan insights before executing a SELECT statement (Materialize).",
1344    true,
1345);
1346
1347pub static EMIT_EXECUTION_TIME_NOTICE: VarDefinition = VarDefinition::new(
1348    "emit_execution_time_notice",
1349    value!(bool; false),
1350    "Boolean flag indicating whether to send a NOTICE with the server-side execution time of statements (Materialize).",
1351    true,
1352);
1353
1354pub static EMIT_TIMESTAMP_NOTICE: VarDefinition = VarDefinition::new(
1355    "emit_timestamp_notice",
1356    value!(bool; false),
1357    "Boolean flag indicating whether to send a NOTICE with timestamp explanations of queries (Materialize).",
1358    true,
1359);
1360
1361pub static EMIT_TRACE_ID_NOTICE: VarDefinition = VarDefinition::new(
1362    "emit_trace_id_notice",
1363    value!(bool; false),
1364    "Boolean flag indicating whether to send a NOTICE specifying the trace id when available (Materialize).",
1365    true,
1366);
1367
1368pub static UNSAFE_MOCK_AUDIT_EVENT_TIMESTAMP: VarDefinition = VarDefinition::new(
1369    "unsafe_mock_audit_event_timestamp",
1370    value!(Option<mz_repr::Timestamp>; None),
1371    "Mocked timestamp to use for audit events for testing purposes",
1372    false,
1373);
1374
1375pub static ENABLE_RBAC_CHECKS: VarDefinition = VarDefinition::new(
1376    "enable_rbac_checks",
1377    value!(bool; true),
1378    "User facing global boolean flag indicating whether to apply RBAC checks before \
1379        executing statements (Materialize).",
1380    true,
1381);
1382
1383pub static ENABLE_SESSION_RBAC_CHECKS: VarDefinition = VarDefinition::new(
1384    "enable_session_rbac_checks",
1385    // TODO(jkosh44) Once RBAC is enabled in all environments, change this to `true`.
1386    value!(bool; false),
1387    "User facing session boolean flag indicating whether to apply RBAC checks before \
1388        executing statements (Materialize).",
1389    true,
1390);
1391
1392pub static RESTRICT_TO_USER_OBJECTS: VarDefinition = VarDefinition::new(
1393    "restrict_to_user_objects",
1394    value!(bool; false),
1395    "When enabled, queries are restricted from accessing system catalog objects. \
1396        Useful for MCP tool queries that should only access user-created data products.",
1397    true,
1398);
1399
1400pub static EMIT_INTROSPECTION_QUERY_NOTICE: VarDefinition = VarDefinition::new(
1401    "emit_introspection_query_notice",
1402    value!(bool; true),
1403    "Whether to print a notice when querying per-replica introspection sources.",
1404    true,
1405);
1406
1407// TODO(mgree) change this to a SelectOption
1408pub static ENABLE_SESSION_CARDINALITY_ESTIMATES: VarDefinition = VarDefinition::new(
1409    "enable_session_cardinality_estimates",
1410    value!(bool; false),
1411    "Feature flag indicating whether to use cardinality estimates when optimizing queries; \
1412        does not affect EXPLAIN WITH(cardinality) (Materialize).",
1413    true,
1414)
1415.with_feature_flag(&ENABLE_CARDINALITY_ESTIMATES);
1416
1417pub static OPTIMIZER_STATS_TIMEOUT: VarDefinition = VarDefinition::new(
1418    "optimizer_stats_timeout",
1419    value!(Duration; Duration::from_millis(250)),
1420    "Sets the timeout applied to the optimizer's statistics collection from storage; \
1421        applied to non-oneshot, i.e., long-lasting queries, like CREATE MATERIALIZED VIEW (Materialize).",
1422    false,
1423);
1424
1425pub static OPTIMIZER_ONESHOT_STATS_TIMEOUT: VarDefinition = VarDefinition::new(
1426    "optimizer_oneshot_stats_timeout",
1427    value!(Duration; Duration::from_millis(10)),
1428    "Sets the timeout applied to the optimizer's statistics collection from storage; \
1429        applied to oneshot queries, like SELECT (Materialize).",
1430    false,
1431);
1432
1433pub static PRIVATELINK_STATUS_UPDATE_QUOTA_PER_MINUTE: VarDefinition = VarDefinition::new(
1434    "privatelink_status_update_quota_per_minute",
1435    value!(u32; 20),
1436    "Sets the per-minute quota for privatelink vpc status updates to be written to \
1437        the storage-collection-backed system table. This value implies the total and burst quota per-minute.",
1438    false,
1439);
1440
1441pub static STATEMENT_LOGGING_SAMPLE_RATE: VarDefinition = VarDefinition::new_lazy(
1442    "statement_logging_sample_rate",
1443    lazy_value!(Numeric; || 0.1.into()),
1444    "User-facing session variable indicating how many statement executions should be \
1445        logged, subject to constraint by the system variable `statement_logging_max_sample_rate` (Materialize).",
1446    true,
1447).with_constraint(&NUMERIC_BOUNDED_0_1_INCLUSIVE);
1448
1449pub static ENABLE_DEFAULT_CONNECTION_VALIDATION: VarDefinition = VarDefinition::new(
1450    "enable_default_connection_validation",
1451    value!(bool; true),
1452    "LD facing global boolean flag that allows turning default connection validation off for everyone (Materialize).",
1453    false,
1454);
1455
1456pub static STATEMENT_LOGGING_MAX_DATA_CREDIT: VarDefinition = VarDefinition::new(
1457    "statement_logging_max_data_credit",
1458    value!(Option<usize>; Some(50 * 1024 * 1024)),
1459    // The idea is that during periods of low logging, tokens can accumulate up to this value,
1460    // and then be depleted during periods of high logging.
1461    "The maximum number of bytes that can be logged for statement logging in short burts, or NULL if unlimited (Materialize).",
1462    false,
1463);
1464
1465pub static STATEMENT_LOGGING_TARGET_DATA_RATE: VarDefinition = VarDefinition::new(
1466    "statement_logging_target_data_rate",
1467    value!(Option<usize>; Some(2071)),
1468    "The maximum sustained data rate of statement logging, in bytes per second, or NULL if unlimited (Materialize).",
1469    false,
1470);
1471
1472pub static STATEMENT_LOGGING_MAX_SAMPLE_RATE: VarDefinition = VarDefinition::new_lazy(
1473    "statement_logging_max_sample_rate",
1474    lazy_value!(Numeric; || 0.99.into()),
1475    "The maximum rate at which statements may be logged. If this value is less than \
1476        that of `statement_logging_sample_rate`, the latter is ignored (Materialize).",
1477    true,
1478)
1479.with_constraint(&NUMERIC_BOUNDED_0_1_INCLUSIVE);
1480
1481pub static STATEMENT_LOGGING_DEFAULT_SAMPLE_RATE: VarDefinition = VarDefinition::new_lazy(
1482    "statement_logging_default_sample_rate",
1483    lazy_value!(Numeric; || 0.99.into()),
1484    "The default value of `statement_logging_sample_rate` for new sessions (Materialize).",
1485    true,
1486)
1487.with_constraint(&NUMERIC_BOUNDED_0_1_INCLUSIVE);
1488
1489pub static ENABLE_INTERNAL_STATEMENT_LOGGING: VarDefinition = VarDefinition::new(
1490    "enable_internal_statement_logging",
1491    value!(bool; false),
1492    "Whether to log statements from the `mz_system` user.",
1493    false,
1494);
1495
1496/// When on, the SQL frontends log incoming statements and other frontend
1497/// messages at info level as soon as they arrive, before processing them
1498/// (except that SQL text is parsed, for redaction). Messages consumed by
1499/// pgwire's COPY subprotocol or its post-error drain loop are not logged.
1500///
1501/// This is an emergency diagnostic for statements that crash the process
1502/// before they reach the statement log (or before its contents are written
1503/// out to persist). It adds a lot of log volume, so use it only in emergencies,
1504/// i.e. to debug active incidents.
1505///
1506/// SQL text is logged with its literals redacted, which is the same redaction
1507/// the statement log applies, see `redact_sql_for_logging`.
1508pub static ENABLE_STATEMENT_ARRIVAL_LOGGING: VarDefinition = VarDefinition::new(
1509    "enable_statement_arrival_logging",
1510    value!(bool; false),
1511    "Whether to log incoming statements and other frontend messages at info \
1512    level as they arrive at the SQL frontends, before processing. SQL text is \
1513    logged with its literals redacted, as in the statement log. Use it only in \
1514    emergencies, i.e. debugging active incidents.",
1515    false,
1516);
1517
1518/// Off is the escape hatch for clients that pipeline statements Materialize
1519/// cannot run in one transaction, for example a read or a DDL after a write.
1520/// Those fail while this is on, rather than silently committing the writes
1521/// staged before them.
1522pub static ENABLE_EXTENDED_PROTOCOL_IMPLICIT_TRANSACTION: VarDefinition = VarDefinition::new(
1523    "enable_extended_protocol_implicit_transaction",
1524    value!(bool; true),
1525    "Whether an implicit write transaction started by the extended query \
1526    protocol spans the whole pipeline up to the client's Sync, so that the \
1527    pipeline commits or rolls back atomically as in PostgreSQL (Materialize).",
1528    false,
1529);
1530
1531pub static AUTO_ROUTE_CATALOG_QUERIES: VarDefinition = VarDefinition::new(
1532    "auto_route_catalog_queries",
1533    value!(bool; true),
1534    "Whether to force queries that depend only on system tables, to run on the mz_catalog_server cluster (Materialize).",
1535    true,
1536);
1537
1538pub static MAX_CONNECTIONS: VarDefinition = VarDefinition::new(
1539    "max_connections",
1540    value!(u32; 5000),
1541    "The maximum number of concurrent connections (PostgreSQL).",
1542    true,
1543);
1544
1545pub static SUPERUSER_RESERVED_CONNECTIONS: VarDefinition = VarDefinition::new(
1546    "superuser_reserved_connections",
1547    value!(u32; 3),
1548    "The number of connections that are reserved for superusers (PostgreSQL).",
1549    true,
1550);
1551
1552/// Controls [`mz_storage_types::parameters::StorageParameters::keep_n_source_status_history_entries`].
1553pub static KEEP_N_SOURCE_STATUS_HISTORY_ENTRIES: VarDefinition = VarDefinition::new(
1554    "keep_n_source_status_history_entries",
1555    value!(usize; 5),
1556    "On reboot, truncate all but the last n entries per ID in the source_status_history collection (Materialize).",
1557    false,
1558);
1559
1560/// Controls [`mz_storage_types::parameters::StorageParameters::keep_n_sink_status_history_entries`].
1561pub static KEEP_N_SINK_STATUS_HISTORY_ENTRIES: VarDefinition = VarDefinition::new(
1562    "keep_n_sink_status_history_entries",
1563    value!(usize; 5),
1564    "On reboot, truncate all but the last n entries per ID in the sink_status_history collection (Materialize).",
1565    false,
1566);
1567
1568/// Controls [`mz_storage_types::parameters::StorageParameters::keep_n_privatelink_status_history_entries`].
1569pub static KEEP_N_PRIVATELINK_STATUS_HISTORY_ENTRIES: VarDefinition = VarDefinition::new(
1570    "keep_n_privatelink_status_history_entries",
1571    value!(usize; 5),
1572    "On reboot, truncate all but the last n entries per ID in the mz_aws_privatelink_connection_status_history \
1573        collection (Materialize).",
1574    false,
1575);
1576
1577/// Controls [`mz_storage_types::parameters::StorageParameters::replica_status_history_retention_window`].
1578pub static REPLICA_STATUS_HISTORY_RETENTION_WINDOW: VarDefinition = VarDefinition::new(
1579    "replica_status_history_retention_window",
1580    value!(Duration; REPLICA_STATUS_HISTORY_RETENTION_WINDOW_DEFAULT),
1581    "On reboot, truncate up all entries past the retention window in the mz_cluster_replica_status_history \
1582        collection (Materialize).",
1583    false,
1584);
1585
1586pub static ENABLE_STORAGE_SHARD_FINALIZATION: VarDefinition = VarDefinition::new(
1587    "enable_storage_shard_finalization",
1588    value!(bool; true),
1589    "Whether to allow the storage client to finalize shards (Materialize).",
1590    false,
1591);
1592
1593pub static DEFAULT_TIMESTAMP_INTERVAL: VarDefinition = VarDefinition::new(
1594    "default_timestamp_interval",
1595    value!(Duration; Duration::from_millis(1000)),
1596    "The interval at which timestamps are assigned to data from sources and tables.",
1597    false,
1598)
1599.with_constraint(&NON_ZERO_DURATION);
1600
1601pub static MIN_TIMESTAMP_INTERVAL: VarDefinition = VarDefinition::new(
1602    "min_timestamp_interval",
1603    value!(Duration; Duration::from_millis(1000)),
1604    "Minimum timestamp interval",
1605    false,
1606);
1607
1608pub static MAX_TIMESTAMP_INTERVAL: VarDefinition = VarDefinition::new(
1609    "max_timestamp_interval",
1610    value!(Duration; Duration::from_millis(1000)),
1611    "Maximum timestamp interval",
1612    false,
1613);
1614
1615pub static WEBHOOK_CONCURRENT_REQUEST_LIMIT: VarDefinition = VarDefinition::new(
1616    "webhook_concurrent_request_limit",
1617    value!(usize; WEBHOOK_CONCURRENCY_LIMIT),
1618    "Maximum number of concurrent requests for appending to a webhook source.",
1619    false,
1620);
1621
1622pub static USER_STORAGE_MANAGED_COLLECTIONS_BATCH_DURATION: VarDefinition = VarDefinition::new(
1623    "user_storage_managed_collections_batch_duration",
1624    value!(Duration; STORAGE_MANAGED_COLLECTIONS_BATCH_DURATION_DEFAULT),
1625    "Duration which we'll wait to collect a batch of events for a webhook source.",
1626    false,
1627);
1628
1629// This system var will need to point to the name of an existing network policy
1630// this will be enforced on alter_system_set
1631pub static NETWORK_POLICY: VarDefinition = VarDefinition::new_lazy(
1632    "network_policy",
1633    lazy_value!(String; || "default".to_string()),
1634    "Sets the fallback network policy applied to all users without an explicit policy.",
1635    true,
1636);
1637
1638pub static FORCE_SOURCE_TABLE_SYNTAX: VarDefinition = VarDefinition::new(
1639    "force_source_table_syntax",
1640    value!(bool; false),
1641    "Force use of new source model (CREATE TABLE .. FROM SOURCE) and migrate existing sources",
1642    true,
1643);
1644
1645pub static OPTIMIZER_E2E_LATENCY_WARNING_THRESHOLD: VarDefinition = VarDefinition::new(
1646    "optimizer_e2e_latency_warning_threshold",
1647    value!(Duration; Duration::from_millis(500)),
1648    "Sets the duration that a query can take to compile; queries that take longer \
1649        will trigger a warning. If this value is specified without units, it is taken as \
1650        milliseconds. A value of zero disables the timeout (Materialize).",
1651    true,
1652);
1653
1654/// Configuration for gRPC client connections.
1655pub mod grpc_client {
1656    use super::*;
1657
1658    pub static CONNECT_TIMEOUT: VarDefinition = VarDefinition::new(
1659        "grpc_client_connect_timeout",
1660        value!(Duration; Duration::from_secs(5)),
1661        "Timeout to apply to initial gRPC client connection establishment.",
1662        false,
1663    );
1664
1665    pub static HTTP2_KEEP_ALIVE_INTERVAL: VarDefinition = VarDefinition::new(
1666        "grpc_client_http2_keep_alive_interval",
1667        value!(Duration; Duration::from_secs(3)),
1668        "Idle time to wait before sending HTTP/2 PINGs to maintain established gRPC client connections.",
1669        false,
1670    );
1671
1672    pub static HTTP2_KEEP_ALIVE_TIMEOUT: VarDefinition = VarDefinition::new(
1673        "grpc_client_http2_keep_alive_timeout",
1674        value!(Duration; Duration::from_secs(60)),
1675        "Time to wait for HTTP/2 pong response before terminating a gRPC client connection.",
1676        false,
1677    );
1678}
1679
1680/// Configuration for how cluster replicas are scheduled.
1681pub mod cluster_scheduling {
1682    use super::*;
1683    use mz_orchestrator::scheduling_config::*;
1684
1685    pub static CLUSTER_MULTI_PROCESS_REPLICA_AZ_AFFINITY_WEIGHT: VarDefinition = VarDefinition::new(
1686        "cluster_multi_process_replica_az_affinity_weight",
1687        value!(Option<i32>; DEFAULT_POD_AZ_AFFINITY_WEIGHT),
1688        "Whether or not to add an availability zone affinity between instances of \
1689            multi-process replicas. Either an affinity weight or empty (off) (Materialize).",
1690        false,
1691    );
1692
1693    pub static CLUSTER_SOFTEN_REPLICATION_ANTI_AFFINITY: VarDefinition = VarDefinition::new(
1694        "cluster_soften_replication_anti_affinity",
1695        value!(bool; DEFAULT_SOFTEN_REPLICATION_ANTI_AFFINITY),
1696        "Whether or not to turn the node-scope anti affinity between replicas \
1697            in the same cluster into a preference (Materialize).",
1698        false,
1699    );
1700
1701    pub static CLUSTER_SOFTEN_REPLICATION_ANTI_AFFINITY_WEIGHT: VarDefinition = VarDefinition::new(
1702        "cluster_soften_replication_anti_affinity_weight",
1703        value!(i32; DEFAULT_SOFTEN_REPLICATION_ANTI_AFFINITY_WEIGHT),
1704        "The preference weight for `cluster_soften_replication_anti_affinity` (Materialize).",
1705        false,
1706    );
1707
1708    pub static CLUSTER_ENABLE_TOPOLOGY_SPREAD: VarDefinition = VarDefinition::new(
1709        "cluster_enable_topology_spread",
1710        value!(bool; DEFAULT_TOPOLOGY_SPREAD_ENABLED),
1711        "Whether or not to add topology spread constraints among replicas in the same cluster (Materialize).",
1712        false,
1713    );
1714
1715    pub static CLUSTER_TOPOLOGY_SPREAD_IGNORE_NON_SINGULAR_SCALE: VarDefinition =
1716        VarDefinition::new(
1717            "cluster_topology_spread_ignore_non_singular_scale",
1718            value!(bool; DEFAULT_TOPOLOGY_SPREAD_IGNORE_NON_SINGULAR_SCALE),
1719            "If true, ignore replicas with more than 1 process when adding topology spread constraints (Materialize).",
1720            false,
1721        );
1722
1723    pub static CLUSTER_TOPOLOGY_SPREAD_MAX_SKEW: VarDefinition = VarDefinition::new(
1724        "cluster_topology_spread_max_skew",
1725        value!(i32; DEFAULT_TOPOLOGY_SPREAD_MAX_SKEW),
1726        "The `maxSkew` for replica topology spread constraints (Materialize).",
1727        false,
1728    );
1729
1730    // `minDomains`, like maxSkew, is used to spread across a topology
1731    // key. Unlike max skew, minDomains will force node creation to ensure
1732    // distribution across a minimum number of keys.
1733    // https://kubernetes.io/docs/concepts/scheduling-eviction/topology-spread-constraints/#spread-constraint-definition
1734    pub static CLUSTER_TOPOLOGY_SPREAD_MIN_DOMAINS: VarDefinition = VarDefinition::new(
1735        "cluster_topology_spread_min_domains",
1736        value!(Option<i32>; None),
1737        "`minDomains` for replica topology spread constraints. \
1738            Should be set to the number of Availability Zones (Materialize).",
1739        false,
1740    );
1741
1742    pub static CLUSTER_TOPOLOGY_SPREAD_SOFT: VarDefinition = VarDefinition::new(
1743        "cluster_topology_spread_soft",
1744        value!(bool; DEFAULT_TOPOLOGY_SPREAD_SOFT),
1745        "If true, soften the topology spread constraints for replicas (Materialize).",
1746        false,
1747    );
1748
1749    pub static CLUSTER_SOFTEN_AZ_AFFINITY: VarDefinition = VarDefinition::new(
1750        "cluster_soften_az_affinity",
1751        value!(bool; DEFAULT_SOFTEN_AZ_AFFINITY),
1752        "Whether or not to turn the az-scope node affinity for replicas. \
1753            Note this could violate requests from the user (Materialize).",
1754        false,
1755    );
1756
1757    pub static CLUSTER_SOFTEN_AZ_AFFINITY_WEIGHT: VarDefinition = VarDefinition::new(
1758        "cluster_soften_az_affinity_weight",
1759        value!(i32; DEFAULT_SOFTEN_AZ_AFFINITY_WEIGHT),
1760        "The preference weight for `cluster_soften_az_affinity` (Materialize).",
1761        false,
1762    );
1763
1764    const DEFAULT_CLUSTER_ALTER_CHECK_READY_INTERVAL: Duration = Duration::from_secs(3);
1765
1766    pub static CLUSTER_ALTER_CHECK_READY_INTERVAL: VarDefinition = VarDefinition::new(
1767        "cluster_alter_check_ready_interval",
1768        value!(Duration; DEFAULT_CLUSTER_ALTER_CHECK_READY_INTERVAL),
1769        "How often to poll readiness checks for cluster alter",
1770        false,
1771    );
1772
1773    pub static CLUSTER_SECURITY_CONTEXT_ENABLED: VarDefinition = VarDefinition::new(
1774        "cluster_security_context_enabled",
1775        value!(bool; DEFAULT_SECURITY_CONTEXT_ENABLED),
1776        "Enables SecurityContext for clusterd instances, restricting capabilities to improve security.",
1777        false,
1778    );
1779
1780    const DEFAULT_CLUSTER_REFRESH_MV_COMPACTION_ESTIMATE: Duration = Duration::from_secs(1200);
1781
1782    pub static CLUSTER_REFRESH_MV_COMPACTION_ESTIMATE: VarDefinition = VarDefinition::new(
1783        "cluster_refresh_mv_compaction_estimate",
1784        value!(Duration; DEFAULT_CLUSTER_REFRESH_MV_COMPACTION_ESTIMATE),
1785        "How much time to wait for compaction after a REFRESH MV completes a refresh \
1786            before turning off the refresh cluster. This is needed because Persist does compaction \
1787            only after a write, but refresh MVs do writes only at their refresh times. \
1788            (In the long term, we'd like to remove this configuration and instead wait exactly \
1789            until compaction has settled. We'd need some new Persist API for this.)",
1790        false,
1791    );
1792}
1793
1794/// Macro to simplify creating feature flags, i.e. boolean flags that we use to toggle the
1795/// availability of features.
1796///
1797/// The arguments to `feature_flags!` are:
1798/// - `$name`, which will be the name of the feature flag, in snake_case
1799/// - `$feature_desc`, a human-readable description of the feature
1800/// - `$value`, which if not provided, defaults to `false`
1801///
1802/// Note that not all `VarDefinition<bool>` are feature flags. Feature flags are for variables that:
1803/// - Belong to `SystemVars`, _not_ `SessionVars`
1804/// - Default to false and must be explicitly enabled, or default to `true` and can be explicitly disabled.
1805///
1806/// WARNING / CONTRACT: Syntax-related feature flags must always *enable* behavior. In other words,
1807/// setting a feature flag must make the system more permissive. For example, let's suppose we'd like
1808/// to gate deprecated upsert syntax behind a feature flag. In this case, do not add a feature flag
1809/// like `disable_deprecated_upsert_syntax`, as `disable_deprecated_upsert_syntax = on` would
1810/// _prevent_ the system from parsing the deprecated upsert syntax. Instead, use a feature flag
1811/// like `enable_deprecated_upsert_syntax`.
1812///
1813/// The hazard this protects against is related to reboots after feature flags have been disabled.
1814/// Say someone creates a Kinesis source while `enable_kinesis_sources = on`. Materialize will
1815/// commit this source to the system catalog. Then, suppose we discover a catastrophic bug in
1816/// Kinesis sources and set `enable_kinesis_sources` to `off`. This prevents users from creating
1817/// new Kinesis sources, but leaves the existing Kinesis sources in place. This is because
1818/// disabling a feature flag doesn't remove access to catalog objects created while the feature
1819/// flag was live. On the next reboot, Materialize will proceed to load the Kinesis source from the
1820/// catalog, reparsing and replanning the `CREATE SOURCE` definition and rechecking the
1821/// `enable_kinesis_sources` feature flag along the way. Even though the feature flag has been
1822/// switched to `off`, we need to temporarily re-enable it during parsing and planning to be able
1823/// to boot successfully.
1824///
1825/// Ensuring that all syntax-related feature flags *enable* behavior means that setting all such
1826/// feature flags to `on` during catalog boot has the desired effect.
1827macro_rules! feature_flags {
1828    // Resolve an optional `scope:` field to a `ParameterScope`, using the
1829    // default scope when the field is omitted.
1830    (@scope_or_default) => {
1831        ParameterScope::DEFAULT
1832    };
1833    (@scope_or_default $scope:expr) => {
1834        $scope
1835    };
1836    // Match `$name, $feature_desc, $value`.
1837    (@inner
1838        // The feature flag name.
1839        name: $name:expr,
1840        // The feature flag description.
1841        desc: $desc:literal,
1842        // The feature flag default value.
1843        default: $value:expr,
1844        // The scope class of the feature flag.
1845        scope: $scope:expr,
1846    ) => {
1847        paste::paste!{
1848            // Note that the ServerVar is not directly exported; we expect these to be
1849            // accessible through their FeatureFlag variant.
1850            static [<$name:upper _VAR>]: VarDefinition = VarDefinition::new(
1851                stringify!($name),
1852                value!(bool; $value),
1853                concat!("Whether ", $desc, " is allowed (Materialize)."),
1854                false,
1855            )
1856            .scoped($scope);
1857
1858            pub static [<$name:upper >]: FeatureFlag = FeatureFlag {
1859                flag: &[<$name:upper _VAR>],
1860                feature_desc: $desc,
1861            };
1862        }
1863    };
1864    ($({
1865        // The feature flag name.
1866        name: $name:expr,
1867        // The feature flag description.
1868        desc: $desc:literal,
1869        // The feature flag default value.
1870        default: $value:expr,
1871        // Should the feature be turned on during catalog rehydration when
1872        // parsing a catalog item.
1873        enable_for_item_parsing: $enable_for_item_parsing:expr,
1874        // The optional scope class. Uses `ParameterScope::DEFAULT` when omitted.
1875        // Cluster-coherent optimizer flags declare `scope: ParameterScope::Cluster`.
1876        $(scope: $scope:expr,)?
1877    },)+) => {
1878        $(feature_flags! { @inner
1879            name: $name,
1880            desc: $desc,
1881            default: $value,
1882            scope: feature_flags!(@scope_or_default $($scope)?),
1883        })+
1884
1885        paste::paste!{
1886            pub static FEATURE_FLAGS: &'static [&'static VarDefinition] = &[
1887                $(  & [<$name:upper _VAR>] , )+
1888            ];
1889        }
1890
1891        paste::paste!{
1892            impl super::SystemVars {
1893                pub fn enable_all_feature_flags_by_default(&mut self) {
1894                    $(
1895                        self.set_default(stringify!($name), super::VarInput::Flat("on"))
1896                            .expect("setting default value must work");
1897                    )+
1898                }
1899
1900                pub fn enable_for_item_parsing(&mut self) {
1901                    $(
1902                        if $enable_for_item_parsing {
1903                            self.set(stringify!($name), super::VarInput::Flat("on"))
1904                                .expect("setting default value must work");
1905                        }
1906                    )+
1907                }
1908
1909                $(
1910                    pub fn [<$name:lower>](&self) -> bool {
1911                        *self.expect_value(&[<$name:upper _VAR>])
1912                    }
1913                )+
1914            }
1915        }
1916    }
1917}
1918
1919feature_flags!(
1920    // Gates for other feature flags
1921    {
1922        name: allow_real_time_recency,
1923        desc: "real time recency",
1924        default: false,
1925        enable_for_item_parsing: true,
1926    },
1927    // Actual feature flags
1928    {
1929        name: enable_binary_date_bin,
1930        desc: "the binary version of date_bin function",
1931        default: false,
1932        enable_for_item_parsing: true,
1933    },
1934    {
1935        name: enable_date_bin_hopping,
1936        desc: "the date_bin_hopping function",
1937        default: false,
1938        enable_for_item_parsing: true,
1939    },
1940    {
1941        name: enable_jq,
1942        desc: "the jq function",
1943        default: true,
1944        enable_for_item_parsing: true,
1945    },
1946    {
1947        name: enable_envelope_debezium_in_subscribe,
1948        desc: "`ENVELOPE DEBEZIUM (KEY (..))`",
1949        default: false,
1950        enable_for_item_parsing: true,
1951    },
1952    {
1953        name: enable_envelope_materialize,
1954        desc: "ENVELOPE MATERIALIZE",
1955        default: false,
1956        enable_for_item_parsing: true,
1957    },
1958    {
1959        name: enable_explain_pushdown,
1960        desc: "EXPLAIN FILTER PUSHDOWN",
1961        default: true,
1962        enable_for_item_parsing: true,
1963    },
1964    {
1965        name: enable_index_options,
1966        desc: "INDEX OPTIONS",
1967        default: false,
1968        enable_for_item_parsing: true,
1969    },
1970    {
1971        name: enable_list_length_max,
1972        desc: "the list_length_max function",
1973        default: false,
1974        enable_for_item_parsing: true,
1975    },
1976    {
1977        name: enable_list_n_layers,
1978        desc: "the list_n_layers function",
1979        default: false,
1980        enable_for_item_parsing: true,
1981    },
1982    {
1983        name: enable_list_remove,
1984        desc: "the list_remove function",
1985        default: false,
1986        enable_for_item_parsing: true,
1987    },
1988    {
1989
1990        name: enable_logical_compaction_window,
1991        desc: "RETAIN HISTORY",
1992        default: false,
1993        enable_for_item_parsing: true,
1994    },
1995    {
1996        name: enable_primary_key_not_enforced,
1997        desc: "PRIMARY KEY NOT ENFORCED",
1998        default: false,
1999        enable_for_item_parsing: true,
2000    },
2001    {
2002        name: enable_collection_partition_by,
2003        desc: "PARTITION BY",
2004        default: true,
2005        enable_for_item_parsing: true,
2006    },
2007    {
2008        name: enable_multi_worker_storage_persist_sink,
2009        desc: "multi-worker storage persist sink",
2010        default: true,
2011        enable_for_item_parsing: true,
2012    },
2013    {
2014        name: enable_persist_streaming_snapshot_and_fetch,
2015        desc: "use the new streaming consolidate for snapshot_and_fetch",
2016        default: false,
2017        enable_for_item_parsing: true,
2018    },
2019    {
2020        name: enable_persist_streaming_compaction,
2021        desc: "use the new streaming consolidate for compaction",
2022        default: false,
2023        enable_for_item_parsing: true,
2024    },
2025    {
2026        name: enable_raise_statement,
2027        desc: "RAISE statement",
2028        default: false,
2029        enable_for_item_parsing: true,
2030    },
2031    {
2032        name: enable_repeat_row,
2033        desc: "the repeat_row function",
2034        default: false,
2035        enable_for_item_parsing: true,
2036    },
2037    {
2038        name: enable_repeat_row_non_negative,
2039        desc: "the repeat_row_non_negative function",
2040        default: false,
2041        enable_for_item_parsing: true,
2042    },
2043    {
2044        name: enable_replica_targeted_materialized_views,
2045        desc: "replica-targeted materialized views",
2046        default: false,
2047        enable_for_item_parsing: true,
2048    },
2049    {
2050        name: unsafe_enable_incomplete_view_column_lists,
2051        desc: "declaring a view with fewer column names than columns",
2052        default: false,
2053        enable_for_item_parsing: true,
2054    },
2055    {
2056        name: unsafe_enable_table_check_constraint,
2057        desc: "CREATE TABLE with a check constraint",
2058        default: false,
2059        enable_for_item_parsing: true,
2060    },
2061    {
2062        name: unsafe_enable_table_foreign_key,
2063        desc: "CREATE TABLE with a foreign key",
2064        default: false,
2065        enable_for_item_parsing: true,
2066    },
2067    {
2068        name: unsafe_enable_table_keys,
2069        desc: "CREATE TABLE with a primary key or unique constraint",
2070        default: false,
2071        enable_for_item_parsing: true,
2072    },
2073    {
2074        name: unsafe_enable_unorchestrated_cluster_replicas,
2075        desc: "unorchestrated cluster replicas",
2076        default: false,
2077        enable_for_item_parsing: true,
2078    },
2079    {
2080        name: unsafe_enable_unstable_dependencies,
2081        desc: "depending on unstable objects",
2082        default: false,
2083        enable_for_item_parsing: true,
2084    },
2085    {
2086        name: unsafe_enable_unbounded_custom_type_resolution,
2087        desc: "resolving custom types without the depth and complexity limits that bound resolution work",
2088        default: false,
2089        enable_for_item_parsing: true,
2090    },
2091    {
2092        name: enable_within_timestamp_order_by_in_subscribe,
2093        desc: "`WITHIN TIMESTAMP ORDER BY ..`",
2094        default: false,
2095        enable_for_item_parsing: true,
2096    },
2097    {
2098        name: enable_cardinality_estimates,
2099        desc: "join planning with cardinality estimates",
2100        default: false,
2101        enable_for_item_parsing: false,
2102    },
2103    {
2104        name: enable_connection_validation_syntax,
2105        desc: "CREATE CONNECTION .. WITH (VALIDATE) and VALIDATE CONNECTION syntax",
2106        default: true,
2107        enable_for_item_parsing: true,
2108    },
2109    {
2110        name: enable_kafka_broker_matching_rules,
2111        desc: "MATCHING broker rules in BROKERS for Kafka PrivateLink connections",
2112        default: false,
2113        enable_for_item_parsing: true,
2114    },
2115    {
2116        name: enable_alter_set_cluster,
2117        desc: "ALTER ... SET CLUSTER syntax",
2118        default: false,
2119        enable_for_item_parsing: true,
2120    },
2121    {
2122        name: unsafe_enable_unsafe_functions,
2123        desc: "executing potentially dangerous functions",
2124        default: false,
2125        enable_for_item_parsing: true,
2126    },
2127    // NOTE: `false` is the safe setting, unlike most `enable_*` flags. Turning it on lets
2128    // `DROP INDEX` orphan the dataflows of indexes that other dataflows still read from.
2129    {
2130        name: enable_drop_in_use_index,
2131        desc: "dropping an index while other dataflows read from it, leaving them running on an orphaned arrangement",
2132        default: false,
2133        enable_for_item_parsing: false,
2134    },
2135    {
2136        name: enable_managed_cluster_availability_zones,
2137        desc: "MANAGED, AVAILABILITY ZONES syntax",
2138        default: false,
2139        enable_for_item_parsing: true,
2140    },
2141    {
2142        name: statement_logging_use_reproducible_rng,
2143        desc: "statement logging with reproducible RNG",
2144        default: false,
2145        enable_for_item_parsing: false,
2146    },
2147    {
2148        name: enable_notices_for_index_already_exists,
2149        desc: "emitting notices for IndexAlreadyExists (doesn't affect EXPLAIN)",
2150        default: true,
2151        enable_for_item_parsing: true,
2152    },
2153    {
2154        name: enable_notices_for_index_too_wide_for_literal_constraints,
2155        desc: "emitting notices for IndexTooWideForLiteralConstraints (doesn't affect EXPLAIN)",
2156        default: false,
2157        enable_for_item_parsing: true,
2158    },
2159    {
2160        name: enable_notices_for_index_empty_key,
2161        desc: "emitting notices for indexes with an empty key (doesn't affect EXPLAIN)",
2162        default: true,
2163        enable_for_item_parsing: true,
2164    },
2165    {
2166        name: enable_notices_for_equals_null,
2167        desc: "emitting notices for `= NULL` and `<> NULL` comparisons (doesn't affect EXPLAIN)",
2168        default: true,
2169        enable_for_item_parsing: true,
2170    },
2171    {
2172        name: enable_alter_swap,
2173        desc: "the ALTER SWAP feature for objects",
2174        default: true,
2175        enable_for_item_parsing: true,
2176    },
2177    {
2178        name: enable_new_outer_join_lowering,
2179        desc: "new outer join lowering",
2180        default: true,
2181        enable_for_item_parsing: false,
2182        scope: ParameterScope::Cluster,
2183    },
2184    {
2185        name: enable_fixed_correlated_cte_lowering,
2186        desc: "CTE-aware branch keys in HIR-to-MIR lowering, fixing references to \
2187               correlated CTEs from nested correlated scopes",
2188        default: true,
2189        enable_for_item_parsing: false,
2190    },
2191    {
2192        name: enable_time_at_time_zone,
2193        desc: "use of AT TIME ZONE or timezone() with time type",
2194        default: false,
2195        enable_for_item_parsing: true,
2196    },
2197    {
2198        name: enable_postgres_source_failover,
2199        desc: "the FAILOVER option for PostgreSQL sources",
2200        default: false,
2201        enable_for_item_parsing: true,
2202    },
2203    {
2204        name: enable_load_generator_counter,
2205        desc: "Create a LOAD GENERATOR COUNTER",
2206        default: false,
2207        enable_for_item_parsing: true,
2208    },
2209    {
2210        name: enable_load_generator_clock,
2211        desc: "Create a LOAD GENERATOR CLOCK",
2212        default: false,
2213        enable_for_item_parsing: true,
2214    },
2215    {
2216        name: enable_load_generator_datums,
2217        desc: "Create a LOAD GENERATOR DATUMS",
2218        default: false,
2219        enable_for_item_parsing: true,
2220    },
2221    {
2222        name: enable_load_generator_key_value,
2223        desc: "Create a LOAD GENERATOR KEY VALUE",
2224        default: false,
2225        enable_for_item_parsing: true,
2226    },
2227    {
2228        name: enable_expressions_in_limit_syntax,
2229        desc: "LIMIT <expr> syntax",
2230        default: true,
2231        enable_for_item_parsing: true,
2232    },
2233    {
2234        name: enable_try_cast,
2235        desc: "TRY_CAST(<expr> AS <type>) syntax",
2236        default: true,
2237        enable_for_item_parsing: true,
2238    },
2239    {
2240        name: enable_mz_notices,
2241        desc: "Populate the contents of `mz_internal.mz_notices`",
2242        default: true,
2243        enable_for_item_parsing: false,
2244    },
2245    {
2246        name: enable_eager_delta_joins,
2247        desc:
2248            "eager delta joins",
2249        default: false,
2250        enable_for_item_parsing: false,
2251        scope: ParameterScope::Cluster,
2252    },
2253    {
2254        name: enable_off_thread_optimization,
2255        desc: "use off-thread optimization in `CREATE` statements",
2256        default: true,
2257        enable_for_item_parsing: false,
2258    },
2259    {
2260        name: enable_refresh_every_mvs,
2261        desc: "REFRESH EVERY and REFRESH AT materialized views",
2262        default: false,
2263        enable_for_item_parsing: true,
2264    },
2265    {
2266        name: enable_cluster_schedule_refresh,
2267        desc: "`SCHEDULE = ON REFRESH` cluster option",
2268        default: false,
2269        enable_for_item_parsing: true,
2270    },
2271    {
2272        name: enable_auto_scaling_strategy,
2273        desc: "`AUTO SCALING STRATEGY` cluster option",
2274        default: true,
2275        enable_for_item_parsing: true,
2276    },
2277    {
2278        name: enable_reduce_mfp_fusion,
2279        desc: "fusion of MFPs in reductions",
2280        default: true,
2281        enable_for_item_parsing: false,
2282    },
2283    {
2284        name: enable_worker_core_affinity,
2285        desc: "set core affinity for replica worker threads",
2286        default: false,
2287        enable_for_item_parsing: false,
2288    },
2289    {
2290        name: enable_session_timelines,
2291        desc: "strong session serializable isolation levels",
2292        default: false,
2293        enable_for_item_parsing: false,
2294    },
2295    {
2296        name: enable_variadic_left_join_lowering,
2297        desc: "Enable joint HIR ⇒ MIR lowering of stacks of left joins",
2298        default: true,
2299        enable_for_item_parsing: false,
2300        scope: ParameterScope::Cluster,
2301    },
2302    {
2303        name: enable_redacted_test_option,
2304        desc: "Enable useless option to test value redaction",
2305        default: false,
2306        enable_for_item_parsing: true,
2307    },
2308    {
2309        name: enable_letrec_fixpoint_analysis,
2310        desc: "Enable Lattice-based fixpoint iteration on LetRec nodes in the Analysis framework",
2311        default: true, // This is just a failsafe switch for the deployment of materialize#25591.
2312        enable_for_item_parsing: false,
2313        scope: ParameterScope::Cluster,
2314    },
2315    {
2316        name: enable_kafka_sink_headers,
2317        desc: "Enable the HEADERS option for Kafka sinks",
2318        default: true,
2319        enable_for_item_parsing: true,
2320    },
2321    {
2322        name: enable_metric_sink,
2323        desc: "CREATE METRIC SINK",
2324        default: true,
2325        // Boot re-parses every item's `create_sql`, so turning this off would leave any
2326        // already-created metric sink unparseable and take the whole catalog down with it.
2327        enable_for_item_parsing: true,
2328    },
2329    {
2330        name: enable_unlimited_retain_history,
2331        desc: "Disable limits on RETAIN HISTORY (below 1s default, and 0 disables compaction).",
2332        default: false,
2333        enable_for_item_parsing: true,
2334    },
2335    {
2336        name: enable_envelope_upsert_inline_errors,
2337        desc: "The VALUE DECODING ERRORS = INLINE option on ENVELOPE UPSERT",
2338        default: true,
2339        enable_for_item_parsing: true,
2340    },
2341    {
2342        name: enable_alter_table_add_column,
2343        desc: "Enable ALTER TABLE ... ADD COLUMN ...",
2344        default: false,
2345        enable_for_item_parsing: false,
2346    },
2347    {
2348        name: enable_network_policies,
2349        desc: "ENABLE NETWORK POLICIES",
2350        default: true,
2351        enable_for_item_parsing: true,
2352    },
2353    {
2354        name: enable_query_policies,
2355        desc: "Enable creating and managing query policies and their attachments.",
2356        default: false,
2357        enable_for_item_parsing: true,
2358    },
2359    {
2360        name: enable_query_policy_enforcement,
2361        desc: "Enable checking attached query policies during query admission.",
2362        default: false,
2363        enable_for_item_parsing: false,
2364    },
2365    {
2366        name: enable_create_table_from_source,
2367        desc: "Whether to allow CREATE TABLE .. FROM SOURCE syntax.",
2368        default: true,
2369        enable_for_item_parsing: true,
2370    },
2371    {
2372        name: enable_exclude_constraints_option,
2373        desc: "Whether to allow the EXCLUDE CONSTRAINTS / EXCLUDE ALL CONSTRAINTS options \
2374               in CREATE TABLE .. FROM SOURCE.",
2375        default: true,
2376        enable_for_item_parsing: true,
2377    },
2378    {
2379        name: enable_join_prioritize_arranged,
2380        desc: "Whether join planning should prioritize already-arranged keys over keys with more fields.",
2381        default: false,
2382        enable_for_item_parsing: false,
2383        scope: ParameterScope::Cluster,
2384    },
2385    {
2386        name: enable_projection_pushdown_after_relation_cse,
2387        desc: "Run ProjectionPushdown one more time after the last RelationCSE.",
2388        default: true,
2389        enable_for_item_parsing: false,
2390        scope: ParameterScope::Cluster,
2391    },
2392    {
2393        name: enable_union_cancellation_after_relation_cse,
2394        desc: "Run UnionBranchCancellation one more time after the last RelationCSE.",
2395        default: true,
2396        enable_for_item_parsing: false,
2397        scope: ParameterScope::Cluster,
2398    },
2399    {
2400        name: enable_less_reduce_in_eqprop,
2401        desc: "Run MSE::reduce in EquivalencePropagation only if reduce_expr changed something.",
2402        default: true,
2403        enable_for_item_parsing: false,
2404    },
2405    {
2406        name: enable_dequadratic_eqprop_map,
2407        desc: "Skip the quadratic part of EquivalencePropagation's handling of Map.",
2408        default: true,
2409        enable_for_item_parsing: false,
2410    },
2411    {
2412        name: enable_eq_classes_withholding_errors,
2413        desc: "Use `EquivalenceClassesWithholdingErrors` instead of raw `EquivalenceClasses` during eq prop for joins.",
2414        default: true,
2415        enable_for_item_parsing: false,
2416    },
2417    {
2418        name: enable_fast_path_plan_insights,
2419        desc: "Enables those plan insight notices that help with getting fast path queries. Don't turn on before #9492 is fixed!",
2420        default: false,
2421        enable_for_item_parsing: false,
2422    },
2423    {
2424        name: enable_with_ordinality_legacy_fallback,
2425        desc: "When the new WITH ORDINALITY implementation can't be used with a table func, whether to fall back to the legacy implementation or error out.",
2426        default: false,
2427        enable_for_item_parsing: true,
2428    },
2429    {
2430        name: enable_frontend_transaction_completion, // changes take effect for new sessions
2431        desc: "Complete session-owned read-only transactions without a coordinator round trip.",
2432        default: true,
2433        enable_for_item_parsing: false,
2434    },
2435    {
2436        name: enable_replacement_materialized_views,
2437        desc: "Whether to enable replacement materialized views.",
2438        default: true,
2439        enable_for_item_parsing: true,
2440    },
2441    {
2442        name: enable_cast_elimination,
2443        desc: "Allow the optimizer to eliminate noop casts between values of equivalent representation types.",
2444        default: true,
2445        enable_for_item_parsing: false,
2446    },
2447    {
2448        // Just an escape hatch for the unlikely case that we have some user who is doing such
2449        // queries. Can be removed after one week in prod.
2450        // https://github.com/MaterializeInc/database-issues/issues/10004
2451        name: disallow_unmaterializable_functions_as_of,
2452        desc: "Prohibits calling unmaterializable functions (except `mz_now`) in AS OF queries.",
2453        default: true,
2454        enable_for_item_parsing: false,
2455    },
2456    {
2457        name: enable_case_literal_transform,
2458        desc: "Allow the optimizer to rewrite If-chains matching a single expression against literals into a CaseLiteral lookup.",
2459        default: false,
2460        enable_for_item_parsing: false,
2461    },
2462    {
2463        name: enable_simplify_quantified_comparisons,
2464        desc: "Allow the optimizer to simplify quantified comparisons in JOIN ON clauses into semi/anti-join EXISTS form during HIR-to-MIR lowering.",
2465        default: true,
2466        enable_for_item_parsing: false,
2467    },
2468    {
2469        name: enable_simplify_from_less_existence,
2470        desc: "Allow the optimizer to collapse EXISTS/NOT EXISTS over a FROM-less correlated subquery into a plain Filter during HIR-to-MIR lowering.",
2471        default: true,
2472        enable_for_item_parsing: false,
2473    },
2474    {
2475        name: enable_coalesce_case_transform,
2476        desc: "Allow the optimizer to push `COALESCE` into `CASE WHEN`.",
2477        default: true,
2478        enable_for_item_parsing: false,
2479    },
2480    // Disposition: added 2026-05-29, default on; remove after several weeks of observation.
2481    {
2482        name: enable_will_distinct_propagation,
2483        desc: "Allow the WillDistinct transform to propagate a pending distinct through Map, Filter, FlatMap, Threshold, Negate, non-negative Project, and TopK with limit 1 and offset 0.",
2484        default: true,
2485        enable_for_item_parsing: false,
2486    },
2487    {
2488        // An escape hatch: the `CASE` guard defeats the batched lowering that shares one
2489        // `unnest` across several `ANY`/`ALL` operands, so a query with multiple `ANY`/`ALL`
2490        // over a non-constant array plans into more arrangements than before. Turning the flag
2491        // off restores the old plans at the cost of the wrong answer for a NULL array.
2492        name: enable_any_all_null_array_semantics,
2493        desc: "PostgreSQL-compatible NULL semantics for `ANY`/`ALL` over a NULL array or list.",
2494        default: true,
2495        enable_for_item_parsing: false,
2496    },
2497);
2498
2499impl From<&super::SystemVars> for OptimizerFeatures {
2500    fn from(vars: &super::SystemVars) -> Self {
2501        Self {
2502            enable_eager_delta_joins: vars.enable_eager_delta_joins(),
2503            enable_new_outer_join_lowering: vars.enable_new_outer_join_lowering(),
2504            enable_reduce_mfp_fusion: vars.enable_reduce_mfp_fusion(),
2505            enable_variadic_left_join_lowering: vars.enable_variadic_left_join_lowering(),
2506            enable_letrec_fixpoint_analysis: vars.enable_letrec_fixpoint_analysis(),
2507            enable_cardinality_estimates: vars.enable_cardinality_estimates(),
2508            persist_fast_path_limit: vars.persist_fast_path_limit(),
2509            reoptimize_imported_views: false,
2510            enable_join_prioritize_arranged: vars.enable_join_prioritize_arranged(),
2511            enable_projection_pushdown_after_relation_cse: vars
2512                .enable_projection_pushdown_after_relation_cse(),
2513            enable_union_cancellation_after_relation_cse: vars
2514                .enable_union_cancellation_after_relation_cse(),
2515            enable_less_reduce_in_eqprop: vars.enable_less_reduce_in_eqprop(),
2516            enable_dequadratic_eqprop_map: vars.enable_dequadratic_eqprop_map(),
2517            enable_eq_classes_withholding_errors: vars.enable_eq_classes_withholding_errors(),
2518            enable_fast_path_plan_insights: vars.enable_fast_path_plan_insights(),
2519            enable_cast_elimination: vars.enable_cast_elimination(),
2520            enable_case_literal_transform: vars.enable_case_literal_transform(),
2521            enable_simplify_quantified_comparisons: vars.enable_simplify_quantified_comparisons(),
2522            enable_simplify_from_less_existence: vars.enable_simplify_from_less_existence(),
2523            enable_coalesce_case_transform: vars.enable_coalesce_case_transform(),
2524            enable_will_distinct_propagation: vars.enable_will_distinct_propagation(),
2525            enable_fixed_correlated_cte_lowering: vars.enable_fixed_correlated_cte_lowering(),
2526        }
2527    }
2528}
2529
2530#[cfg(test)]
2531mod tests {
2532    use super::*;
2533    use crate::session::vars::SystemVars;
2534
2535    /// Ensure that all vars used for optimizer features have `enable_for_item_parsing = false`.
2536    ///
2537    /// This is important to ensure that plan caching works as intended during item parsing. Cached
2538    /// plans include the optimizer features they were produced with, and if they don't match on
2539    /// lookup, that results in a cache miss.
2540    #[mz_ore::test]
2541    fn optimizer_features_no_enable_for_item_parsing() {
2542        // Construct a `SystemVars` where all optimizer features are `false`.
2543        //
2544        // We do this in a roundabout way, by first constructing all-false `OptimizerFeatures` and
2545        // then assigning them to their respective system vars, to ensure we don't forget to update
2546        // this test when new optimizer features are added.
2547        //
2548        // NOTE: if the new feature ships enabled, also turn it on in
2549        // `mz_transform_fuzz::fuzz_features`, which the cargo-fuzz optimizer targets plan with.
2550        // That helper falls back to `Default` (all-`false`) for anything it does not name, so a
2551        // flag missing from it silently fuzzes the disabled path. This exhaustive destructuring is
2552        // the tripwire for both.
2553        let false_features = OptimizerFeatures::default();
2554        let OptimizerFeatures {
2555            enable_eq_classes_withholding_errors,
2556            enable_eager_delta_joins,
2557            enable_letrec_fixpoint_analysis,
2558            enable_new_outer_join_lowering,
2559            enable_reduce_mfp_fusion,
2560            enable_variadic_left_join_lowering,
2561            enable_cardinality_estimates,
2562            persist_fast_path_limit,
2563            reoptimize_imported_views,
2564            enable_join_prioritize_arranged,
2565            enable_projection_pushdown_after_relation_cse,
2566            enable_union_cancellation_after_relation_cse,
2567            enable_less_reduce_in_eqprop,
2568            enable_dequadratic_eqprop_map,
2569            enable_fast_path_plan_insights,
2570            enable_cast_elimination,
2571            enable_case_literal_transform,
2572            enable_simplify_quantified_comparisons,
2573            enable_simplify_from_less_existence,
2574            enable_coalesce_case_transform,
2575            enable_will_distinct_propagation,
2576            enable_fixed_correlated_cte_lowering,
2577        } = false_features;
2578
2579        let mut vars = SystemVars::new();
2580
2581        macro_rules! set_var {
2582            ($var:ident) => {
2583                vars.set(stringify!($var), VarInput::Flat(&$var.to_string()))
2584                    .unwrap();
2585            };
2586        }
2587
2588        set_var!(enable_eq_classes_withholding_errors);
2589        set_var!(enable_eager_delta_joins);
2590        set_var!(enable_letrec_fixpoint_analysis);
2591        set_var!(enable_new_outer_join_lowering);
2592        set_var!(enable_reduce_mfp_fusion);
2593        set_var!(enable_variadic_left_join_lowering);
2594        set_var!(enable_cardinality_estimates);
2595        set_var!(persist_fast_path_limit);
2596        let _ = reoptimize_imported_views; // no corresponding var
2597        set_var!(enable_join_prioritize_arranged);
2598        set_var!(enable_projection_pushdown_after_relation_cse);
2599        set_var!(enable_union_cancellation_after_relation_cse);
2600        set_var!(enable_less_reduce_in_eqprop);
2601        set_var!(enable_dequadratic_eqprop_map);
2602        set_var!(enable_fast_path_plan_insights);
2603        set_var!(enable_cast_elimination);
2604        set_var!(enable_case_literal_transform);
2605        set_var!(enable_simplify_quantified_comparisons);
2606        set_var!(enable_simplify_from_less_existence);
2607        set_var!(enable_coalesce_case_transform);
2608        set_var!(enable_will_distinct_propagation);
2609        set_var!(enable_fixed_correlated_cte_lowering);
2610
2611        // Enable for item parsing, then ensure we still get the same optimizer features.
2612        vars.enable_for_item_parsing();
2613        let features_for_item_parsing = OptimizerFeatures::from(&vars);
2614        assert_eq!(features_for_item_parsing, false_features);
2615    }
2616}