1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

use std::borrow::Cow;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;

use chrono::{DateTime, Utc};
use derivative::Derivative;
use mz_adapter_types::timestamp_oracle::{
    DEFAULT_PG_TIMESTAMP_ORACLE_CONNPOOL_MAX_SIZE, DEFAULT_PG_TIMESTAMP_ORACLE_CONNPOOL_MAX_WAIT,
    DEFAULT_PG_TIMESTAMP_ORACLE_CONNPOOL_TTL, DEFAULT_PG_TIMESTAMP_ORACLE_CONNPOOL_TTL_STAGGER,
};
use mz_ore::cast::{self, CastFrom};
use mz_repr::adt::numeric::Numeric;
use mz_repr::adt::timestamp::CheckedTimestamp;
use mz_repr::bytes::ByteSize;
use mz_repr::optimize::OptimizerFeatures;
use mz_sql_parser::ast::Ident;
use mz_sql_parser::ident;
use mz_storage_types::controller::PersistTxnTablesImpl;
use mz_storage_types::parameters::STORAGE_MANAGED_COLLECTIONS_BATCH_DURATION_DEFAULT;
use mz_tracing::{CloneableEnvFilter, SerializableDirective};
use once_cell::sync::Lazy;
use uncased::UncasedStr;

use crate::session::user::{User, SUPPORT_USER, SYSTEM_USER};
use crate::session::vars::constraints::{
    DomainConstraint, ValueConstraint, NUMERIC_BOUNDED_0_1_INCLUSIVE, NUMERIC_NON_NEGATIVE,
};
use crate::session::vars::errors::VarError;
use crate::session::vars::polyfill::{lazy_value, value, LazyValueFn};
use crate::session::vars::value::{
    ClientEncoding, ClientSeverity, Failpoints, IntervalStyle, IsolationLevel, TimeZone, Value,
    DEFAULT_DATE_STYLE,
};
use crate::session::vars::{FeatureFlag, Var, VarInput, VarParseError};
use crate::{DEFAULT_SCHEMA, WEBHOOK_CONCURRENCY_LIMIT};

/// Definition of a variable.
#[derive(Clone, Derivative)]
#[derivative(Debug)]
pub struct VarDefinition {
    /// Name of the variable, case-insensitive matching.
    pub name: &'static UncasedStr,
    /// Description of the variable.
    pub description: &'static str,
    /// TODO(parkmcar): What does internal mean?
    pub internal: bool,

    /// Default compiled in value for this variable.
    pub value: VarDefaultValue,
    /// Constraint that must be upheld for this variable to be valid.
    pub constraint: Option<ValueConstraint>,
    /// Optionally hides this variable if it's related to a feature flag being enabled.
    pub feature_flag: Option<&'static FeatureFlag>,

    /// Method to parse [`VarInput`] into a type that implements [`Value`].
    ///
    /// The reason `parse` exists as a function pointer is because we want to achieve two things:
    ///   1. `VarDefinition` has no generic parameters.
    ///   2. `Value::parse` returns an instance of `Self`.
    /// `VarDefinition` holds a `dyn Value`, but `Value::parse` is not object safe because it
    /// returns `Self`, so we can't call that method. We could change `Value::parse` to return a
    /// `Box<dyn Value>` making it object safe, but that creates a footgun where it's possible for
    /// `Value::parse` to return a type that isn't `Self`, e.g. `<String as Value>::parse` could
    /// return a `usize`!
    ///
    /// So to prevent making `VarDefinition` generic over some type `V: Value`, but also defining
    /// `Value::parse` as returning `Self`, we store a static function pointer to the `parse`
    /// implementation of our default value.
    #[derivative(Debug = "ignore")]
    parse: fn(VarInput) -> Result<Box<dyn Value>, VarParseError>,
    /// Returns a human readable name for the type of this variable. We store this as a static
    /// function pointer for the same reason as `parse`.
    #[derivative(Debug = "ignore")]
    type_name: fn() -> Cow<'static, str>,
}
static_assertions::assert_impl_all!(VarDefinition: Send, Sync);

impl VarDefinition {
    pub const fn new<V: Value>(
        name: &'static str,
        value: &'static V,
        description: &'static str,
        internal: bool,
    ) -> Self {
        VarDefinition {
            name: UncasedStr::new(name),
            description,
            value: VarDefaultValue::Static(value),
            internal,
            parse: V::parse_dyn_value,
            type_name: V::type_name,
            constraint: None,
            feature_flag: None,
        }
    }

    pub const fn new_lazy<V: Value, L: LazyValueFn<V>>(
        name: &'static str,
        _value: L,
        description: &'static str,
        internal: bool,
    ) -> Self {
        VarDefinition {
            name: UncasedStr::new(name),
            description,
            value: VarDefaultValue::Lazy(L::LAZY_VALUE_FN),
            internal,
            parse: V::parse_dyn_value,
            type_name: V::type_name,
            constraint: None,
            feature_flag: None,
        }
    }

    pub fn new_runtime<V: Value>(
        name: &'static str,
        value: V,
        description: &'static str,
        internal: bool,
    ) -> Self {
        VarDefinition {
            name: UncasedStr::new(name),
            description,
            value: VarDefaultValue::Runtime(Arc::new(value)),
            internal,
            parse: V::parse_dyn_value,
            type_name: V::type_name,
            constraint: None,
            feature_flag: None,
        }
    }

    /// TODO(parkmycar): Refactor this method onto a `VarDefinitionBuilder` that would allow us to
    /// constrain `V` here to be the same `V` used in [`VarDefinition::new`].
    pub const fn with_constraint<V: Value, D: DomainConstraint<Value = V>>(
        mut self,
        constraint: &'static D,
    ) -> Self {
        self.constraint = Some(ValueConstraint::Domain(constraint));
        self
    }

    pub const fn fixed(mut self) -> Self {
        self.constraint = Some(ValueConstraint::Fixed);
        self
    }

    pub const fn read_only(mut self) -> Self {
        self.constraint = Some(ValueConstraint::ReadOnly);
        self
    }

    pub const fn with_feature_flag(mut self, feature_flag: &'static FeatureFlag) -> Self {
        self.feature_flag = Some(feature_flag);
        self
    }

    pub fn parse(&self, input: VarInput) -> Result<Box<dyn Value>, VarError> {
        (self.parse)(input).map_err(|err| err.into_var_error(self))
    }

    pub fn default_value(&self) -> &'_ dyn Value {
        self.value.value()
    }
}

impl Var for VarDefinition {
    fn name(&self) -> &'static str {
        self.name.as_str()
    }

    fn value(&self) -> String {
        self.default_value().format()
    }

    fn description(&self) -> &'static str {
        self.description
    }

    fn type_name(&self) -> Cow<'static, str> {
        (self.type_name)()
    }

    fn visible(
        &self,
        user: &User,
        system_vars: Option<&super::SystemVars>,
    ) -> Result<(), VarError> {
        if self.internal && user != &*SYSTEM_USER && user != &*SUPPORT_USER {
            Err(VarError::UnknownParameter(self.name().to_string()))
        } else if self.name().starts_with("unsafe")
            && match system_vars {
                None => true,
                Some(system_vars) => !system_vars.allow_unsafe(),
            }
        {
            Err(VarError::RequiresUnsafeMode(self.name()))
        } else {
            if let Some(flag) = self.feature_flag {
                flag.enabled(system_vars, None, None)?;
            }

            Ok(())
        }
    }
}

/// The kinds of compiled in default values that can be used with [`VarDefinition`].
#[derive(Clone, Debug)]
pub enum VarDefaultValue {
    /// Static that can be evaluated at compile time.
    Static(&'static dyn Value),
    /// Lazy value that is defined at compile time, but created at runtime.
    Lazy(fn() -> &'static dyn Value),
    /// Value created at runtime. Note: This is generally an escape hatch.
    Runtime(Arc<dyn Value>),
}

impl VarDefaultValue {
    pub fn value(&self) -> &'_ dyn Value {
        match self {
            VarDefaultValue::Static(s) => *s,
            VarDefaultValue::Lazy(l) => (l)(),
            VarDefaultValue::Runtime(r) => r.as_ref(),
        }
    }
}

// We pretend to be Postgres v9.5.0, which is also what CockroachDB pretends to
// be. Too new and some clients will emit a "server too new" warning. Too old
// and some clients will fall back to legacy code paths. v9.5.0 empirically
// seems to be a good compromise.

/// The major version of PostgreSQL that Materialize claims to be.
pub const SERVER_MAJOR_VERSION: u8 = 9;

/// The minor version of PostgreSQL that Materialize claims to be.
pub const SERVER_MINOR_VERSION: u8 = 5;

/// The patch version of PostgreSQL that Materialize claims to be.
pub const SERVER_PATCH_VERSION: u8 = 0;

/// The name of the default database that Materialize uses.
pub const DEFAULT_DATABASE_NAME: &str = "materialize";

pub static APPLICATION_NAME: VarDefinition = VarDefinition::new(
    "application_name",
    value!(String; String::new()),
    "Sets the application name to be reported in statistics and logs (PostgreSQL).",
    false,
);

pub static CLIENT_ENCODING: VarDefinition = VarDefinition::new(
    "client_encoding",
    value!(ClientEncoding; ClientEncoding::Utf8),
    "Sets the client's character set encoding (PostgreSQL).",
    false,
);

pub static CLIENT_MIN_MESSAGES: VarDefinition = VarDefinition::new(
    "client_min_messages",
    value!(ClientSeverity; ClientSeverity::Notice),
    "Sets the message levels that are sent to the client (PostgreSQL).",
    false,
);

pub static CLUSTER: VarDefinition = VarDefinition::new_lazy(
    "cluster",
    lazy_value!(String; || "quickstart".to_string()),
    "Sets the current cluster (Materialize).",
    false,
);

pub static CLUSTER_REPLICA: VarDefinition = VarDefinition::new(
    "cluster_replica",
    value!(Option<String>; None),
    "Sets a target cluster replica for SELECT queries (Materialize).",
    false,
);

pub static DATABASE: VarDefinition = VarDefinition::new_lazy(
    "database",
    lazy_value!(String; || DEFAULT_DATABASE_NAME.to_string()),
    "Sets the current database (CockroachDB).",
    false,
);

pub static DATE_STYLE: VarDefinition = VarDefinition::new(
    // DateStyle has nonstandard capitalization for historical reasons.
    "DateStyle",
    &DEFAULT_DATE_STYLE,
    "Sets the display format for date and time values (PostgreSQL).",
    false,
);

pub static EXTRA_FLOAT_DIGITS: VarDefinition = VarDefinition::new(
    "extra_float_digits",
    value!(i32; 3),
    "Adjusts the number of digits displayed for floating-point values (PostgreSQL).",
    false,
);

pub static FAILPOINTS: VarDefinition = VarDefinition::new(
    "failpoints",
    value!(Failpoints; Failpoints),
    "Allows failpoints to be dynamically activated.",
    false,
);

pub static INTEGER_DATETIMES: VarDefinition = VarDefinition::new(
    "integer_datetimes",
    value!(bool; true),
    "Reports whether the server uses 64-bit-integer dates and times (PostgreSQL).",
    false,
)
.fixed();

pub static INTERVAL_STYLE: VarDefinition = VarDefinition::new(
    // IntervalStyle has nonstandard capitalization for historical reasons.
    "IntervalStyle",
    value!(IntervalStyle; IntervalStyle::Postgres),
    "Sets the display format for interval values (PostgreSQL).",
    false,
);

pub const MZ_VERSION_NAME: &UncasedStr = UncasedStr::new("mz_version");
pub const IS_SUPERUSER_NAME: &UncasedStr = UncasedStr::new("is_superuser");

// Schema can be used an alias for a search path with a single element.
pub const SCHEMA_ALIAS: &UncasedStr = UncasedStr::new("schema");
pub static SEARCH_PATH: VarDefinition = VarDefinition::new_lazy(
    "search_path",
    lazy_value!(Vec<Ident>; || vec![ident!(DEFAULT_SCHEMA)]),
    "Sets the schema search order for names that are not schema-qualified (PostgreSQL).",
    false,
);

pub static STATEMENT_TIMEOUT: VarDefinition = VarDefinition::new(
    "statement_timeout",
    value!(Duration; Duration::from_secs(10)),
    "Sets the maximum allowed duration of INSERT...SELECT, UPDATE, and DELETE operations. \
    If this value is specified without units, it is taken as milliseconds.",
    false,
);

pub static IDLE_IN_TRANSACTION_SESSION_TIMEOUT: VarDefinition = VarDefinition::new(
    "idle_in_transaction_session_timeout",
    value!(Duration; Duration::from_secs(60 * 2)),
    "Sets the maximum allowed duration that a session can sit idle in a transaction before \
    being terminated. If this value is specified without units, it is taken as milliseconds. \
    A value of zero disables the timeout (PostgreSQL).",
    false,
);

pub static SERVER_VERSION: VarDefinition = VarDefinition::new_lazy(
    "server_version",
    lazy_value!(String; || {
        format!("{SERVER_MAJOR_VERSION}.{SERVER_MINOR_VERSION}.{SERVER_PATCH_VERSION}")
    }),
    "Shows the PostgreSQL compatible server version (PostgreSQL).",
    false,
)
.read_only();

pub static SERVER_VERSION_NUM: VarDefinition = VarDefinition::new(
    "server_version_num",
    value!(i32; (cast::u8_to_i32(SERVER_MAJOR_VERSION) * 10_000)
        + (cast::u8_to_i32(SERVER_MINOR_VERSION) * 100)
        + cast::u8_to_i32(SERVER_PATCH_VERSION)),
    "Shows the PostgreSQL compatible server version as an integer (PostgreSQL).",
    false,
)
.read_only();

pub static SQL_SAFE_UPDATES: VarDefinition = VarDefinition::new(
    "sql_safe_updates",
    value!(bool; false),
    "Prohibits SQL statements that may be overly destructive (CockroachDB).",
    false,
);

pub static STANDARD_CONFORMING_STRINGS: VarDefinition = VarDefinition::new(
    "standard_conforming_strings",
    value!(bool; true),
    "Causes '...' strings to treat backslashes literally (PostgreSQL).",
    false,
)
.fixed();

pub static TIMEZONE: VarDefinition = VarDefinition::new(
    // TimeZone has nonstandard capitalization for historical reasons.
    "TimeZone",
    value!(TimeZone; TimeZone::UTC),
    "Sets the time zone for displaying and interpreting time stamps (PostgreSQL).",
    false,
);

pub const TRANSACTION_ISOLATION_VAR_NAME: &str = "transaction_isolation";
pub static TRANSACTION_ISOLATION: VarDefinition = VarDefinition::new(
    TRANSACTION_ISOLATION_VAR_NAME,
    value!(IsolationLevel; IsolationLevel::StrictSerializable),
    "Sets the current transaction's isolation level (PostgreSQL).",
    false,
);

pub static MAX_KAFKA_CONNECTIONS: VarDefinition = VarDefinition::new(
    "max_kafka_connections",
    value!(u32; 1000),
    "The maximum number of Kafka connections in the region, across all schemas (Materialize).",
    false,
);

pub static MAX_POSTGRES_CONNECTIONS: VarDefinition = VarDefinition::new(
    "max_postgres_connections",
    value!(u32; 1000),
    "The maximum number of PostgreSQL connections in the region, across all schemas (Materialize).",
    false,
);

pub static MAX_AWS_PRIVATELINK_CONNECTIONS: VarDefinition = VarDefinition::new(
    "max_aws_privatelink_connections",
    value!(u32; 0),
     "The maximum number of AWS PrivateLink connections in the region, across all schemas (Materialize).",
    false
);

pub static MAX_TABLES: VarDefinition = VarDefinition::new(
    "max_tables",
    value!(u32; 25),
    "The maximum number of tables in the region, across all schemas (Materialize).",
    false,
);

pub static MAX_SOURCES: VarDefinition = VarDefinition::new(
    "max_sources",
    value!(u32; 25),
    "The maximum number of sources in the region, across all schemas (Materialize).",
    false,
);

pub static MAX_SINKS: VarDefinition = VarDefinition::new(
    "max_sinks",
    value!(u32; 25),
    "The maximum number of sinks in the region, across all schemas (Materialize).",
    false,
);

pub static MAX_MATERIALIZED_VIEWS: VarDefinition = VarDefinition::new(
    "max_materialized_views",
    value!(u32; 100),
    "The maximum number of materialized views in the region, across all schemas (Materialize).",
    false,
);

pub static MAX_CLUSTERS: VarDefinition = VarDefinition::new(
    "max_clusters",
    value!(u32; 10),
    "The maximum number of clusters in the region (Materialize).",
    false,
);

pub static MAX_REPLICAS_PER_CLUSTER: VarDefinition = VarDefinition::new(
    "max_replicas_per_cluster",
    value!(u32; 5),
    "The maximum number of replicas of a single cluster (Materialize).",
    false,
);

pub static MAX_CREDIT_CONSUMPTION_RATE: VarDefinition = VarDefinition::new_lazy(
    "max_credit_consumption_rate",
    lazy_value!(Numeric; || 1024.into()),
    "The maximum rate of credit consumption in a region. Credits are consumed based on the size of cluster replicas in use (Materialize).",
    false,
)
.with_constraint(&NUMERIC_NON_NEGATIVE);

pub static MAX_DATABASES: VarDefinition = VarDefinition::new(
    "max_databases",
    value!(u32; 1000),
    "The maximum number of databases in the region (Materialize).",
    false,
);

pub static MAX_SCHEMAS_PER_DATABASE: VarDefinition = VarDefinition::new(
    "max_schemas_per_database",
    value!(u32; 1000),
    "The maximum number of schemas in a database (Materialize).",
    false,
);

pub static MAX_OBJECTS_PER_SCHEMA: VarDefinition = VarDefinition::new(
    "max_objects_per_schema",
    value!(u32; 1000),
    "The maximum number of objects in a schema (Materialize).",
    false,
);

pub static MAX_SECRETS: VarDefinition = VarDefinition::new(
    "max_secrets",
    value!(u32; 100),
    "The maximum number of secrets in the region, across all schemas (Materialize).",
    false,
);

pub static MAX_ROLES: VarDefinition = VarDefinition::new(
    "max_roles",
    value!(u32; 1000),
    "The maximum number of roles in the region (Materialize).",
    false,
);

// Cloud environmentd is configured with 4 GiB of RAM, so 1 GiB is a good heuristic for a single
// query.
// TODO(jkosh44) Eventually we want to be able to return arbitrary sized results.
pub static MAX_RESULT_SIZE: VarDefinition = VarDefinition::new(
    "max_result_size",
    value!(ByteSize; ByteSize::gb(1)),
    "The maximum size in bytes for an internal query result (Materialize).",
    false,
);

pub static MAX_QUERY_RESULT_SIZE: VarDefinition = VarDefinition::new(
    "max_query_result_size",
    value!(ByteSize; ByteSize::gb(1)),
    "The maximum size in bytes for a single query's result (Materialize).",
    false,
);

pub static MAX_COPY_FROM_SIZE: VarDefinition = VarDefinition::new(
    "max_copy_from_size",
    // 1 GiB, this limit is noted in the docs, if you change it make sure to update our docs.
    value!(u32; 1_073_741_824),
    "The maximum size in bytes we buffer for COPY FROM statements (Materialize).",
    false,
);

pub static MAX_IDENTIFIER_LENGTH: VarDefinition = VarDefinition::new(
    "max_identifier_length",
    value!(usize; mz_sql_lexer::lexer::MAX_IDENTIFIER_LENGTH),
    "The maximum length of object identifiers in bytes (PostgreSQL).",
    false,
);

pub static WELCOME_MESSAGE: VarDefinition = VarDefinition::new(
    "welcome_message",
    value!(bool; true),
    "Whether to send a notice with a welcome message after a successful connection (Materialize).",
    false,
);

/// The logical compaction window for builtin tables and sources that have the
/// `retained_metrics_relation` flag set.
///
/// The existence of this variable is a bit of a hack until we have a fully
/// general solution for controlling retention windows.
pub static METRICS_RETENTION: VarDefinition = VarDefinition::new(
    "metrics_retention",
    // 30 days
    value!(Duration; Duration::from_secs(30 * 24 * 60 * 60)),
    "The time to retain cluster utilization metrics (Materialize).",
    true,
);

pub static ALLOWED_CLUSTER_REPLICA_SIZES: VarDefinition = VarDefinition::new(
    "allowed_cluster_replica_sizes",
    value!(Vec<Ident>; Vec::new()),
    "The allowed sizes when creating a new cluster replica (Materialize).",
    false,
);

pub static PERSIST_FAST_PATH_LIMIT: VarDefinition = VarDefinition::new(
    "persist_fast_path_limit",
    value!(usize; 0),
    "An exclusive upper bound on the number of results we may return from a Persist fast-path peek; \
    queries that may return more results will follow the normal / slow path. \
    Setting this to 0 disables the feature.",
    true,
);

pub static PERSIST_TXN_TABLES: VarDefinition = VarDefinition::new(
    "persist_txn_tables",
    value!(PersistTxnTablesImpl; PersistTxnTablesImpl::Eager),
    "\
    Whether to use the new persist-txn tables implementation or the legacy \
    one.

    Only takes effect on restart. Any changes will also cause clusterd \
    processes to restart.

    This value is also configurable via a Launch Darkly parameter of the \
    same name, but we keep the flag to make testing easier. If specified, \
    the flag takes precedence over the Launch Darkly param.",
    true,
);

/// Controls `mz_adapter::coord::timestamp_oracle::postgres_oracle::DynamicConfig::pg_connection_pool_max_size`.
pub static PG_TIMESTAMP_ORACLE_CONNECTION_POOL_MAX_SIZE: VarDefinition = VarDefinition::new(
    "pg_timestamp_oracle_connection_pool_max_size",
    value!(usize; DEFAULT_PG_TIMESTAMP_ORACLE_CONNPOOL_MAX_SIZE),
    "Maximum size of the Postgres/CRDB connection pool, used by the Postgres/CRDB timestamp oracle.",
    true,
);

/// Controls `mz_adapter::coord::timestamp_oracle::postgres_oracle::DynamicConfig::pg_connection_pool_max_wait`.
pub static PG_TIMESTAMP_ORACLE_CONNECTION_POOL_MAX_WAIT: VarDefinition = VarDefinition::new(
    "pg_timestamp_oracle_connection_pool_max_wait",
    value!(Option<Duration>; Some(DEFAULT_PG_TIMESTAMP_ORACLE_CONNPOOL_MAX_WAIT)),
    "The maximum time to wait when attempting to obtain a connection from the Postgres/CRDB connection pool, used by the Postgres/CRDB timestamp oracle.",
    true,
);

/// Controls `mz_adapter::coord::timestamp_oracle::postgres_oracle::DynamicConfig::pg_connection_pool_ttl`.
pub static PG_TIMESTAMP_ORACLE_CONNECTION_POOL_TTL: VarDefinition = VarDefinition::new(
    "pg_timestamp_oracle_connection_pool_ttl",
    value!(Duration; DEFAULT_PG_TIMESTAMP_ORACLE_CONNPOOL_TTL),
    "The minimum TTL of a Consensus connection to Postgres/CRDB before it is proactively terminated",
    true,
);

/// Controls `mz_adapter::coord::timestamp_oracle::postgres_oracle::DynamicConfig::pg_connection_pool_ttl_stagger`.
pub static PG_TIMESTAMP_ORACLE_CONNECTION_POOL_TTL_STAGGER: VarDefinition = VarDefinition::new(
    "pg_timestamp_oracle_connection_pool_ttl_stagger",
    value!(Duration; DEFAULT_PG_TIMESTAMP_ORACLE_CONNPOOL_TTL_STAGGER),
    "The minimum time between TTLing Consensus connections to Postgres/CRDB.",
    true,
);

/// The default for the `DISK` option when creating managed clusters and cluster replicas.
pub static DISK_CLUSTER_REPLICAS_DEFAULT: VarDefinition = VarDefinition::new(
    "disk_cluster_replicas_default",
    value!(bool; false),
    "Whether the disk option for managed clusters and cluster replicas should be enabled by default.",
    true,
);

pub static UNSAFE_NEW_TRANSACTION_WALL_TIME: VarDefinition = VarDefinition::new(
    "unsafe_new_transaction_wall_time",
    value!(Option<CheckedTimestamp<DateTime<Utc>>>; None),
    "Sets the wall time for all new explicit or implicit transactions to control the value of `now()`. \
    If not set, uses the system's clock.",
    // This needs to be false because `internal: true` things are only modifiable by the mz_system
    // and mz_support users, and we want sqllogictest to have access with its user. Because the name
    // starts with "unsafe" it still won't be visible or changeable by users unless unsafe mode is
    // enabled.
    false,
);

/// Tuning for RocksDB used by `UPSERT` sources that takes effect on restart.
pub mod upsert_rocksdb {
    use super::*;
    use mz_rocksdb_types::config::{CompactionStyle, CompressionType};

    pub static UPSERT_ROCKSDB_COMPACTION_STYLE: VarDefinition = VarDefinition::new(
        "upsert_rocksdb_compaction_style",
        value!(CompactionStyle; mz_rocksdb_types::defaults::DEFAULT_COMPACTION_STYLE),
        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
        sources. Described in the `mz_rocksdb_types::config` module. \
        Only takes effect on source restart (Materialize).",
        true,
    );

    pub static UPSERT_ROCKSDB_OPTIMIZE_COMPACTION_MEMTABLE_BUDGET: VarDefinition =
        VarDefinition::new(
            "upsert_rocksdb_optimize_compaction_memtable_budget",
            value!(usize; mz_rocksdb_types::defaults::DEFAULT_OPTIMIZE_COMPACTION_MEMTABLE_BUDGET),
            "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
        sources. Described in the `mz_rocksdb_types::config` module. \
        Only takes effect on source restart (Materialize).",
            true,
        );

    pub static UPSERT_ROCKSDB_LEVEL_COMPACTION_DYNAMIC_LEVEL_BYTES: VarDefinition =
        VarDefinition::new(
            "upsert_rocksdb_level_compaction_dynamic_level_bytes",
            value!(bool; mz_rocksdb_types::defaults::DEFAULT_LEVEL_COMPACTION_DYNAMIC_LEVEL_BYTES),
            "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
        sources. Described in the `mz_rocksdb_types::config` module. \
        Only takes effect on source restart (Materialize).",
            true,
        );

    pub static UPSERT_ROCKSDB_UNIVERSAL_COMPACTION_RATIO: VarDefinition = VarDefinition::new(
        "upsert_rocksdb_universal_compaction_ratio",
        value!(i32; mz_rocksdb_types::defaults::DEFAULT_UNIVERSAL_COMPACTION_RATIO),
        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
        sources. Described in the `mz_rocksdb_types::config` module. \
        Only takes effect on source restart (Materialize).",
        true,
    );

    pub static UPSERT_ROCKSDB_PARALLELISM: VarDefinition = VarDefinition::new(
        "upsert_rocksdb_parallelism",
        value!(Option<i32>; mz_rocksdb_types::defaults::DEFAULT_PARALLELISM),
        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
        sources. Described in the `mz_rocksdb_types::config` module. \
        Only takes effect on source restart (Materialize).",
        true,
    );

    pub static UPSERT_ROCKSDB_COMPRESSION_TYPE: VarDefinition = VarDefinition::new(
        "upsert_rocksdb_compression_type",
        value!(CompressionType; mz_rocksdb_types::defaults::DEFAULT_COMPRESSION_TYPE),
        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
        sources. Described in the `mz_rocksdb_types::config` module. \
        Only takes effect on source restart (Materialize).",
        true,
    );

    pub static UPSERT_ROCKSDB_BOTTOMMOST_COMPRESSION_TYPE: VarDefinition = VarDefinition::new(
        "upsert_rocksdb_bottommost_compression_type",
        value!(CompressionType; mz_rocksdb_types::defaults::DEFAULT_BOTTOMMOST_COMPRESSION_TYPE),
        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
        sources. Described in the `mz_rocksdb_types::config` module. \
        Only takes effect on source restart (Materialize).",
        true,
    );

    pub static UPSERT_ROCKSDB_BATCH_SIZE: VarDefinition = VarDefinition::new(
        "upsert_rocksdb_batch_size",
        value!(usize; mz_rocksdb_types::defaults::DEFAULT_BATCH_SIZE),
        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
        sources. Described in the `mz_rocksdb_types::config` module. \
        Can be changed dynamically (Materialize).",
        true,
    );

    pub static UPSERT_ROCKSDB_RETRY_DURATION: VarDefinition = VarDefinition::new(
        "upsert_rocksdb_retry_duration",
        value!(Duration; mz_rocksdb_types::defaults::DEFAULT_RETRY_DURATION),
        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
        sources. Described in the `mz_rocksdb_types::config` module. \
        Only takes effect on source restart (Materialize).",
        true,
    );

    /// Controls whether automatic spill to disk should be turned on when using `DISK`.
    pub static UPSERT_ROCKSDB_AUTO_SPILL_TO_DISK: VarDefinition = VarDefinition::new(
        "upsert_rocksdb_auto_spill_to_disk",
        value!(bool; false),
        "Controls whether automatic spill to disk should be turned on when using `DISK`",
        true,
    );

    /// The upsert in memory state size threshold after which it will spill to disk.
    /// The default is 85 MiB = 89128960 bytes
    pub static UPSERT_ROCKSDB_AUTO_SPILL_THRESHOLD_BYTES: VarDefinition = VarDefinition::new(
        "upsert_rocksdb_auto_spill_threshold_bytes",
        value!(usize; mz_rocksdb_types::defaults::DEFAULT_AUTO_SPILL_MEMORY_THRESHOLD),
        "The upsert in-memory state size threshold in bytes after which it will spill to disk",
        true,
    );

    pub static UPSERT_ROCKSDB_STATS_LOG_INTERVAL_SECONDS: VarDefinition = VarDefinition::new(
        "upsert_rocksdb_stats_log_interval_seconds",
        value!(u32; mz_rocksdb_types::defaults::DEFAULT_STATS_LOG_INTERVAL_S),
        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
        sources. Described in the `mz_rocksdb_types::config` module. \
        Only takes effect on source restart (Materialize).",
        true,
    );

    pub static UPSERT_ROCKSDB_STATS_PERSIST_INTERVAL_SECONDS: VarDefinition = VarDefinition::new(
        "upsert_rocksdb_stats_persist_interval_seconds",
        value!(u32; mz_rocksdb_types::defaults::DEFAULT_STATS_PERSIST_INTERVAL_S),
        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
        sources. Described in the `mz_rocksdb_types::config` module. \
        Only takes effect on source restart (Materialize).",
        true,
    );

    pub static UPSERT_ROCKSDB_POINT_LOOKUP_BLOCK_CACHE_SIZE_MB: VarDefinition = VarDefinition::new(
        "upsert_rocksdb_point_lookup_block_cache_size_mb",
        value!(Option<u32>; None),
        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
        sources. Described in the `mz_rocksdb_types::config` module. \
        Only takes effect on source restart (Materialize).",
        true,
    );

    /// The number of times by which allocated buffers will be shrinked in upsert rocksdb.
    /// If value is 0, then no shrinking will occur.
    pub static UPSERT_ROCKSDB_SHRINK_ALLOCATED_BUFFERS_BY_RATIO: VarDefinition = VarDefinition::new(
        "upsert_rocksdb_shrink_allocated_buffers_by_ratio",
        value!(usize; mz_rocksdb_types::defaults::DEFAULT_SHRINK_BUFFERS_BY_RATIO),
        "The number of times by which allocated buffers will be shrinked in upsert rocksdb.",
        true,
    );

    /// Only used if `upsert_rocksdb_write_buffer_manager_memory_bytes` is also set
    /// and write buffer manager is enabled
    pub static UPSERT_ROCKSDB_WRITE_BUFFER_MANAGER_CLUSTER_MEMORY_FRACTION: VarDefinition =
        VarDefinition::new(
            "upsert_rocksdb_write_buffer_manager_cluster_memory_fraction",
            value!(Option<Numeric>; None),
            "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
        sources. Described in the `mz_rocksdb_types::config` module. \
        Only takes effect on source restart (Materialize).",
            true,
        );

    /// `upsert_rocksdb_write_buffer_manager_memory_bytes` needs to be set for write buffer manager to be
    /// used.
    pub static UPSERT_ROCKSDB_WRITE_BUFFER_MANAGER_MEMORY_BYTES: VarDefinition = VarDefinition::new(
        "upsert_rocksdb_write_buffer_manager_memory_bytes",
        value!(Option<usize>; None),
        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
        sources. Described in the `mz_rocksdb_types::config` module. \
        Only takes effect on source restart (Materialize).",
        true,
    );

    pub static UPSERT_ROCKSDB_WRITE_BUFFER_MANAGER_ALLOW_STALL: VarDefinition = VarDefinition::new(
        "upsert_rocksdb_write_buffer_manager_allow_stall",
        value!(bool; false),
        "Tuning parameter for RocksDB as used in `UPSERT/DEBEZIUM` \
        sources. Described in the `mz_rocksdb_types::config` module. \
        Only takes effect on source restart (Materialize).",
        true,
    );
}

pub static LOGGING_FILTER: VarDefinition = VarDefinition::new_lazy(
    "log_filter",
    lazy_value!(CloneableEnvFilter; || CloneableEnvFilter::from_str("info").expect("valid EnvFilter")),
    "Sets the filter to apply to stderr logging.",
    true,
);

pub static OPENTELEMETRY_FILTER: VarDefinition = VarDefinition::new_lazy(
    "opentelemetry_filter",
    lazy_value!(CloneableEnvFilter; || CloneableEnvFilter::from_str("info").expect("valid EnvFilter")),
    "Sets the filter to apply to OpenTelemetry-backed distributed tracing.",
    true,
);

pub static LOGGING_FILTER_DEFAULTS: VarDefinition = VarDefinition::new_lazy(
    "log_filter_defaults",
    lazy_value!(Vec<SerializableDirective>; || {
        mz_ore::tracing::LOGGING_DEFAULTS
            .iter()
            .map(|d| d.clone().into())
            .collect()
    }),
    "Sets additional default directives to apply to stderr logging. \
        These apply to all variations of `log_filter`. Directives other than \
        `module=off` are likely incorrect.",
    true,
);

pub static OPENTELEMETRY_FILTER_DEFAULTS: VarDefinition = VarDefinition::new_lazy(
    "opentelemetry_filter_defaults",
    lazy_value!(Vec<SerializableDirective>; || {
        mz_ore::tracing::OPENTELEMETRY_DEFAULTS
            .iter()
            .map(|d| d.clone().into())
            .collect()
    }),
    "Sets additional default directives to apply to OpenTelemetry-backed \
        distributed tracing. \
        These apply to all variations of `opentelemetry_filter`. Directives other than \
        `module=off` are likely incorrect.",
    true,
);

pub static SENTRY_FILTERS: VarDefinition = VarDefinition::new_lazy(
    "sentry_filters",
    lazy_value!(Vec<SerializableDirective>; || {
        mz_ore::tracing::SENTRY_DEFAULTS
            .iter()
            .map(|d| d.clone().into())
            .collect()
    }),
    "Sets additional default directives to apply to sentry logging. \
        These apply on top of a default `info` directive. Directives other than \
        `module=off` are likely incorrect.",
    true,
);

pub static WEBHOOKS_SECRETS_CACHING_TTL_SECS: VarDefinition = VarDefinition::new_lazy(
    "webhooks_secrets_caching_ttl_secs",
    lazy_value!(usize; || {
        usize::cast_from(
            mz_secrets::cache::DEFAULT_TTL_SECS.load(std::sync::atomic::Ordering::Relaxed),
        )
    }),
    "Sets the time-to-live for values in the Webhooks secrets cache.",
    true,
);

pub static COORD_SLOW_MESSAGE_WARN_THRESHOLD: VarDefinition = VarDefinition::new(
    "coord_slow_message_warn_threshold",
    // Note(parkmycar): This value was chosen arbitrarily.
    value!(Duration; Duration::from_secs(5)),
    "Sets the threshold at which we will warn! for a coordinator message being slow.",
    true,
);

/// Controls the connect_timeout setting when connecting to PG via `mz_postgres_util`.
pub static PG_SOURCE_CONNECT_TIMEOUT: VarDefinition = VarDefinition::new(
    "pg_source_connect_timeout",
    value!(Duration; mz_postgres_util::DEFAULT_CONNECT_TIMEOUT),
    "Sets the timeout applied to socket-level connection attempts for PG \
    replication connections. (Materialize)",
    true,
);

/// Sets the maximum number of TCP keepalive probes that will be sent before dropping a connection
/// when connecting to PG via `mz_postgres_util`.
pub static PG_SOURCE_KEEPALIVES_RETRIES: VarDefinition = VarDefinition::new(
    "pg_source_keepalives_retries",
    value!(u32; mz_postgres_util::DEFAULT_KEEPALIVE_RETRIES),
    "Sets the maximum number of TCP keepalive probes that will be sent before dropping \
    a connection when connecting to PG via `mz_postgres_util`. (Materialize)",
    true,
);

/// Sets the amount of idle time before a keepalive packet is sent on the connection when connecting
/// to PG via `mz_postgres_util`.
pub static PG_SOURCE_KEEPALIVES_IDLE: VarDefinition = VarDefinition::new(
    "pg_source_keepalives_idle",
    value!(Duration; mz_postgres_util::DEFAULT_KEEPALIVE_IDLE),
    "Sets the amount of idle time before a keepalive packet is sent on the connection \
        when connecting to PG via `mz_postgres_util`. (Materialize)",
    true,
);

/// Sets the time interval between TCP keepalive probes when connecting to PG via `mz_postgres_util`.
pub static PG_SOURCE_KEEPALIVES_INTERVAL: VarDefinition = VarDefinition::new(
    "pg_source_keepalives_interval",
    value!(Duration; mz_postgres_util::DEFAULT_KEEPALIVE_INTERVAL),
    "Sets the time interval between TCP keepalive probes when connecting to PG via \
        replication. (Materialize)",
    true,
);

/// Sets the TCP user timeout when connecting to PG via `mz_postgres_util`.
pub static PG_SOURCE_TCP_USER_TIMEOUT: VarDefinition = VarDefinition::new(
    "pg_source_tcp_user_timeout",
    value!(Duration; mz_postgres_util::DEFAULT_TCP_USER_TIMEOUT),
    "Sets the TCP user timeout when connecting to PG via `mz_postgres_util`. (Materialize)",
    true,
);

/// Sets the `statement_timeout` value to use during the snapshotting phase of
/// PG sources.
pub static PG_SOURCE_SNAPSHOT_STATEMENT_TIMEOUT: VarDefinition = VarDefinition::new(
    "pg_source_snapshot_statement_timeout",
    value!(Duration; mz_postgres_util::DEFAULT_SNAPSHOT_STATEMENT_TIMEOUT),
    "Sets the `statement_timeout` value to use during the snapshotting phase of PG sources (Materialize)",
    true,
);

/// Sets the `wal_sender_timeout` value to use during the replication phase of
/// PG sources.
pub static PG_SOURCE_WAL_SENDER_TIMEOUT: VarDefinition = VarDefinition::new(
    "pg_source_wal_sender_timeout",
    value!(Duration; mz_postgres_util::DEFAULT_WAL_SENDER_TIMEOUT),
    "Sets the `wal_sender_timeout` value to use during the replication phase of PG sources (Materialize)",
    true,
);

/// Please see `PgSourceSnapshotConfig`.
pub static PG_SOURCE_SNAPSHOT_COLLECT_STRICT_COUNT: VarDefinition = VarDefinition::new(
    "pg_source_snapshot_collect_strict_count",
    value!(bool; mz_storage_types::parameters::PgSourceSnapshotConfig::new().collect_strict_count),
    "Please see <https://dev.materialize.com/api/rust-private\
        /mz_storage_types/parameters\
        /struct.PgSourceSnapshotConfig.html#structfield.collect_strict_count>",
    true,
);

/// Please see `PgSourceSnapshotConfig`.
pub static PG_SOURCE_SNAPSHOT_FALLBACK_TO_STRICT_COUNT: VarDefinition = VarDefinition::new(
    "pg_source_snapshot_fallback_to_strict_count",
    value!(bool; mz_storage_types::parameters::PgSourceSnapshotConfig::new().fallback_to_strict_count),
    "Please see <https://dev.materialize.com/api/rust-private\
        /mz_storage_types/parameters\
        /struct.PgSourceSnapshotConfig.html#structfield.fallback_to_strict_count>",
    true,
);

/// Please see `PgSourceSnapshotConfig`.
pub static PG_SOURCE_SNAPSHOT_WAIT_FOR_COUNT: VarDefinition = VarDefinition::new(
    "pg_source_snapshot_wait_for_count",
    value!(bool; mz_storage_types::parameters::PgSourceSnapshotConfig::new().wait_for_count),
    "Please see <https://dev.materialize.com/api/rust-private\
        /mz_storage_types/parameters\
        /struct.PgSourceSnapshotConfig.html#structfield.wait_for_count>",
    true,
);

/// Sets the time between TCP keepalive probes when connecting to MySQL via `mz_mysql_util`.
pub static MYSQL_SOURCE_TCP_KEEPALIVE: VarDefinition = VarDefinition::new(
    "mysql_source_tcp_keepalive",
    value!(Duration; mz_mysql_util::DEFAULT_TCP_KEEPALIVE),
    "Sets the time between TCP keepalive probes when connecting to MySQL",
    true,
);

/// Sets the `max_execution_time` value to use during the snapshotting phase of
/// MySQL sources.
pub static MYSQL_SOURCE_SNAPSHOT_MAX_EXECUTION_TIME: VarDefinition = VarDefinition::new(
    "mysql_source_snapshot_max_execution_time",
    value!(Duration; mz_mysql_util::DEFAULT_SNAPSHOT_MAX_EXECUTION_TIME),
    "Sets the `max_execution_time` value to use during the snapshotting phase of MySQL sources (Materialize)",
    true,
);

/// Sets the `lock_wait_timeout` value to use during the snapshotting phase of
/// MySQL sources.
pub static MYSQL_SOURCE_SNAPSHOT_LOCK_WAIT_TIMEOUT: VarDefinition = VarDefinition::new(
    "mysql_source_snapshot_lock_wait_timeout",
    value!(Duration; mz_mysql_util::DEFAULT_SNAPSHOT_LOCK_WAIT_TIMEOUT),
    "Sets the `lock_wait_timeout` value to use during the snapshotting phase of MySQL sources (Materialize)",
    true,
);

/// Controls the check interval for connections to SSH bastions via `mz_ssh_util`.
pub static SSH_CHECK_INTERVAL: VarDefinition = VarDefinition::new(
    "ssh_check_interval",
    value!(Duration; mz_ssh_util::tunnel::DEFAULT_CHECK_INTERVAL),
    "Controls the check interval for connections to SSH bastions via `mz_ssh_util`.",
    true,
);

/// Controls the connect timeout for connections to SSH bastions via `mz_ssh_util`.
pub static SSH_CONNECT_TIMEOUT: VarDefinition = VarDefinition::new(
    "ssh_connect_timeout",
    value!(Duration; mz_ssh_util::tunnel::DEFAULT_CONNECT_TIMEOUT),
    "Controls the connect timeout for connections to SSH bastions via `mz_ssh_util`.",
    true,
);

/// Controls the keepalive idle interval for connections to SSH bastions via `mz_ssh_util`.
pub static SSH_KEEPALIVES_IDLE: VarDefinition = VarDefinition::new(
    "ssh_keepalives_idle",
    value!(Duration; mz_ssh_util::tunnel::DEFAULT_KEEPALIVES_IDLE),
    "Controls the keepalive idle interval for connections to SSH bastions via `mz_ssh_util`.",
    true,
);

/// Enables `socket.keepalive.enable` for rdkafka client connections. Defaults to true.
pub static KAFKA_SOCKET_KEEPALIVE: VarDefinition = VarDefinition::new(
    "kafka_socket_keepalive",
    value!(bool; mz_kafka_util::client::DEFAULT_KEEPALIVE),
    "Enables `socket.keepalive.enable` for rdkafka client connections. Defaults to true.",
    true,
);

/// Controls `socket.timeout.ms` for rdkafka client connections. Defaults to the rdkafka default
/// (60000ms). Cannot be greater than 300000ms, more than 100ms greater than
/// `kafka_transaction_timeout`, or less than 10ms.
pub static KAFKA_SOCKET_TIMEOUT: VarDefinition = VarDefinition::new(
    "kafka_socket_timeout",
    value!(Duration; mz_kafka_util::client::DEFAULT_SOCKET_TIMEOUT),
    "Controls `socket.timeout.ms` for rdkafka \
        client connections. Defaults to the rdkafka default (60000ms). \
        Cannot be greater than 300000ms or more than 100ms greater than \
        Cannot be greater than 300000ms, more than 100ms greater than \
        `kafka_transaction_timeout`, or less than 10ms.",
    true,
);

/// Controls `transaction.timeout.ms` for rdkafka client connections. Defaults to the rdkafka default
/// (60000ms). Cannot be greater than `i32::MAX` or less than 1000ms.
pub static KAFKA_TRANSACTION_TIMEOUT: VarDefinition = VarDefinition::new(
    "kafka_transaction_timeout",
    value!(Duration; mz_kafka_util::client::DEFAULT_TRANSACTION_TIMEOUT),
    "Controls `transaction.timeout.ms` for rdkafka \
        client connections. Defaults to the rdkafka default (60000ms). \
        Cannot be greater than `i32::MAX` or less than 1000ms.",
    true,
);

/// Controls `socket.connection.setup.timeout.ms` for rdkafka client connections. Defaults to the rdkafka default
/// (30000ms). Cannot be greater than `i32::MAX` or less than 1000ms
pub static KAFKA_SOCKET_CONNECTION_SETUP_TIMEOUT: VarDefinition = VarDefinition::new(
    "kafka_socket_connection_setup_timeout",
    value!(Duration; mz_kafka_util::client::DEFAULT_SOCKET_CONNECTION_SETUP_TIMEOUT),
    "Controls `socket.connection.setup.timeout.ms` for rdkafka \
        client connections. Defaults to the rdkafka default (30000ms). \
        Cannot be greater than `i32::MAX` or less than 1000ms",
    true,
);

/// Controls the timeout when fetching kafka metadata. Defaults to 10s.
pub static KAFKA_FETCH_METADATA_TIMEOUT: VarDefinition = VarDefinition::new(
    "kafka_fetch_metadata_timeout",
    value!(Duration; mz_kafka_util::client::DEFAULT_FETCH_METADATA_TIMEOUT),
    "Controls the timeout when fetching kafka metadata. \
        Defaults to 10s.",
    true,
);

/// Controls the timeout when fetching kafka progress records. Defaults to 60s.
pub static KAFKA_PROGRESS_RECORD_FETCH_TIMEOUT: VarDefinition = VarDefinition::new(
    "kafka_progress_record_fetch_timeout",
    value!(Duration; mz_kafka_util::client::DEFAULT_PROGRESS_RECORD_FETCH_TIMEOUT),
    "Controls the timeout when fetching kafka progress records. \
        Defaults to 60s.",
    true,
);

/// The interval we will fetch metadata from, unless overridden by the source.
pub static KAFKA_DEFAULT_METADATA_FETCH_INTERVAL: VarDefinition = VarDefinition::new(
    "kafka_default_metadata_fetch_interval",
    value!(Duration; mz_kafka_util::client::DEFAULT_METADATA_FETCH_INTERVAL),
    "The interval we will fetch metadata from, unless overridden by the source. \
        Defaults to 60s.",
    true,
);

/// The maximum number of in-flight bytes emitted by persist_sources feeding _storage
/// dataflows_.
/// Currently defaults to 256MiB = 268435456 bytes
/// Note: Backpressure will only be turned on if disk is enabled based on
/// `storage_dataflow_max_inflight_bytes_disk_only` flag
pub static STORAGE_DATAFLOW_MAX_INFLIGHT_BYTES: VarDefinition = VarDefinition::new(
    "storage_dataflow_max_inflight_bytes",
    value!(Option<usize>; Some(256 * 1024 * 1024)),
    "The maximum number of in-flight bytes emitted by persist_sources feeding \
        storage dataflows. Defaults to backpressure enabled (Materialize).",
    true,
);

/// Configuration ratio to shrink unusef buffers in upsert by.
/// For eg: is 2 is set, then the buffers will be reduced by 2 i.e. halved.
/// Default is 0, which means shrinking is disabled.
pub static STORAGE_SHRINK_UPSERT_UNUSED_BUFFERS_BY_RATIO: VarDefinition = VarDefinition::new(
    "storage_shrink_upsert_unused_buffers_by_ratio",
    value!(usize; 0),
    "Configuration ratio to shrink unusef buffers in upsert by",
    true,
);

/// The fraction of the cluster replica size to be used as the maximum number of
/// in-flight bytes emitted by persist_sources feeding storage dataflows.
/// If not configured, the storage_dataflow_max_inflight_bytes value will be used.
/// For this value to be used storage_dataflow_max_inflight_bytes needs to be set.
pub static STORAGE_DATAFLOW_MAX_INFLIGHT_BYTES_TO_CLUSTER_SIZE_FRACTION: VarDefinition =
    VarDefinition::new_lazy(
        "storage_dataflow_max_inflight_bytes_to_cluster_size_fraction",
        lazy_value!(Option<Numeric>; || Some(0.0025.into())),
        "The fraction of the cluster replica size to be used as the maximum number of \
            in-flight bytes emitted by persist_sources feeding storage dataflows. \
            If not configured, the storage_dataflow_max_inflight_bytes value will be used.",
        true,
    );

pub static STORAGE_DATAFLOW_MAX_INFLIGHT_BYTES_DISK_ONLY: VarDefinition = VarDefinition::new(
    "storage_dataflow_max_inflight_bytes_disk_only",
    value!(bool; true),
    "Whether or not `storage_dataflow_max_inflight_bytes` applies only to \
        upsert dataflows using disks. Defaults to true (Materialize).",
    true,
);

/// The interval to submit statistics to `mz_source_statistics_per_worker` and `mz_sink_statistics_per_worker`.
pub static STORAGE_STATISTICS_INTERVAL: VarDefinition = VarDefinition::new(
    "storage_statistics_interval",
    value!(Duration; mz_storage_types::parameters::STATISTICS_INTERVAL_DEFAULT),
    "The interval to submit statistics to `mz_source_statistics_per_worker` \
        and `mz_sink_statistics` (Materialize).",
    true,
);

/// The interval to collect statistics for `mz_source_statistics_per_worker` and `mz_sink_statistics_per_worker` in
/// clusterd. Controls the accuracy of metrics.
pub static STORAGE_STATISTICS_COLLECTION_INTERVAL: VarDefinition = VarDefinition::new(
    "storage_statistics_collection_interval",
    value!(Duration; mz_storage_types::parameters::STATISTICS_COLLECTION_INTERVAL_DEFAULT),
    "The interval to collect statistics for `mz_source_statistics_per_worker` \
        and `mz_sink_statistics_per_worker` in clusterd. Controls the accuracy of metrics \
        (Materialize).",
    true,
);

pub static STORAGE_RECORD_SOURCE_SINK_NAMESPACED_ERRORS: VarDefinition = VarDefinition::new(
    "storage_record_source_sink_namespaced_errors",
    value!(bool; true),
    "Whether or not to record namespaced errors in the status history tables",
    true,
);

/// Boolean flag indicating whether to enable syncing from
/// LaunchDarkly. Can be turned off as an emergency measure to still
/// be able to alter parameters while LD is broken.
pub static ENABLE_LAUNCHDARKLY: VarDefinition = VarDefinition::new(
    "enable_launchdarkly",
    value!(bool; true),
    "Boolean flag indicating whether flag synchronization from LaunchDarkly should be enabled (Materialize).",
    true
);

/// Feature flag indicating whether real time recency is enabled. Not that
/// unlike other feature flags, this is made available at the session level, so
/// is additionally gated by a feature flag.
pub static REAL_TIME_RECENCY: VarDefinition = VarDefinition::new(
    "real_time_recency",
    value!(bool; false),
    "Feature flag indicating whether real time recency is enabled (Materialize).",
    false,
)
.with_feature_flag(&ALLOW_REAL_TIME_RECENCY);

pub static EMIT_PLAN_INSIGHTS_NOTICE: VarDefinition = VarDefinition::new(
    "emit_plan_insights_notice",
    value!(bool; false),
    "Boolean flag indicating whether to send a NOTICE with JSON-formatted plan insights before executing a SELECT statement (Materialize).",
    false,
);

pub static EMIT_TIMESTAMP_NOTICE: VarDefinition = VarDefinition::new(
    "emit_timestamp_notice",
    value!(bool; false),
    "Boolean flag indicating whether to send a NOTICE with timestamp explanations of queries (Materialize).",
    false,
);

pub static EMIT_TRACE_ID_NOTICE: VarDefinition = VarDefinition::new(
    "emit_trace_id_notice",
    value!(bool; false),
    "Boolean flag indicating whether to send a NOTICE specifying the trace id when available (Materialize).",
    false,
);

pub static UNSAFE_MOCK_AUDIT_EVENT_TIMESTAMP: VarDefinition = VarDefinition::new(
    "unsafe_mock_audit_event_timestamp",
    value!(Option<mz_repr::Timestamp>; None),
    "Mocked timestamp to use for audit events for testing purposes",
    true,
);

pub static ENABLE_RBAC_CHECKS: VarDefinition = VarDefinition::new(
    "enable_rbac_checks",
    value!(bool; true),
    "User facing global boolean flag indicating whether to apply RBAC checks before \
        executing statements (Materialize).",
    false,
);

pub static ENABLE_SESSION_RBAC_CHECKS: VarDefinition = VarDefinition::new(
    "enable_session_rbac_checks",
    // TODO(jkosh44) Once RBAC is complete, change this to `true`.
    value!(bool; false),
    "User facing session boolean flag indicating whether to apply RBAC checks before \
        executing statements (Materialize).",
    false,
);

pub static EMIT_INTROSPECTION_QUERY_NOTICE: VarDefinition = VarDefinition::new(
    "emit_introspection_query_notice",
    value!(bool; true),
    "Whether to print a notice when querying per-replica introspection sources.",
    false,
);

// TODO(mgree) change this to a SelectOption
pub static ENABLE_SESSION_CARDINALITY_ESTIMATES: VarDefinition = VarDefinition::new(
    "enable_session_cardinality_estimates",
    value!(bool; false),
    "Feature flag indicating whether to use cardinality estimates when optimizing queries; \
        does not affect EXPLAIN WITH(cardinality) (Materialize).",
    false,
)
.with_feature_flag(&ENABLE_CARDINALITY_ESTIMATES);

pub static OPTIMIZER_STATS_TIMEOUT: VarDefinition = VarDefinition::new(
    "optimizer_stats_timeout",
    value!(Duration; Duration::from_millis(250)),
    "Sets the timeout applied to the optimizer's statistics collection from storage; \
        applied to non-oneshot, i.e., long-lasting queries, like CREATE MATERIALIZED VIEW (Materialize).",
    true,
);

pub static OPTIMIZER_ONESHOT_STATS_TIMEOUT: VarDefinition = VarDefinition::new(
    "optimizer_oneshot_stats_timeout",
    value!(Duration; Duration::from_millis(20)),
    "Sets the timeout applied to the optimizer's statistics collection from storage; \
        applied to oneshot queries, like SELECT (Materialize).",
    true,
);

pub static PRIVATELINK_STATUS_UPDATE_QUOTA_PER_MINUTE: VarDefinition = VarDefinition::new(
    "privatelink_status_update_quota_per_minute",
    value!(u32; 20),
    "Sets the per-minute quota for privatelink vpc status updates to be written to \
        the storage-collection-backed system table. This value implies the total and burst quota per-minute.",
    true,
);

pub static STATEMENT_LOGGING_SAMPLE_RATE: VarDefinition = VarDefinition::new_lazy(
    "statement_logging_sample_rate",
    lazy_value!(Numeric; || 0.1.into()),
    "User-facing session variable indicating how many statement executions should be \
        logged, subject to constraint by the system variable `statement_logging_max_sample_rate` (Materialize).",
    false,
).with_constraint(&NUMERIC_BOUNDED_0_1_INCLUSIVE);

pub static ARRANGEMENT_EXERT_PROPORTIONALITY: VarDefinition = VarDefinition::new(
    "arrangement_exert_proportionality",
    value!(u32; 16),
    "Value that controls how much merge effort to exert on arrangements.",
    true,
);

pub static ENABLE_DEFAULT_CONNECTION_VALIDATION: VarDefinition = VarDefinition::new(
    "enable_default_connection_validation",
    value!(bool; true),
    "LD facing global boolean flag that allows turning default connection validation off for everyone (Materialize).",
    true,
);

pub static STATEMENT_LOGGING_MAX_DATA_CREDIT: VarDefinition = VarDefinition::new(
    "statement_logging_max_data_credit",
    value!(Option<usize>; None),
    // The idea is that during periods of low logging, tokens can accumulate up to this value,
    // and then be depleted during periods of high logging.
    "The maximum number of bytes that can be logged for statement logging in short burts, or NULL if unlimited (Materialize).",
    true,
);

pub static STATEMENT_LOGGING_TARGET_DATA_RATE: VarDefinition = VarDefinition::new(
    "statement_logging_target_data_rate",
    value!(Option<usize>; None),
    "The maximum sustained data rate of statement logging, in bytes per second, or NULL if unlimited (Materialize).",
    true,
);

pub static STATEMENT_LOGGING_MAX_SAMPLE_RATE: VarDefinition = VarDefinition::new_lazy(
    "statement_logging_max_sample_rate",
    lazy_value!(Numeric; || 0.0.into()),
    "The maximum rate at which statements may be logged. If this value is less than \
        that of `statement_logging_sample_rate`, the latter is ignored (Materialize).",
    false,
)
.with_constraint(&NUMERIC_BOUNDED_0_1_INCLUSIVE);

pub static STATEMENT_LOGGING_DEFAULT_SAMPLE_RATE: VarDefinition = VarDefinition::new_lazy(
    "statement_logging_default_sample_rate",
    lazy_value!(Numeric; || 0.0.into()),
    "The default value of `statement_logging_sample_rate` for new sessions (Materialize).",
    false,
)
.with_constraint(&NUMERIC_BOUNDED_0_1_INCLUSIVE);

pub static AUTO_ROUTE_INTROSPECTION_QUERIES: VarDefinition = VarDefinition::new(
    "auto_route_introspection_queries",
    value!(bool; true),
    "Whether to force queries that depend only on system tables, to run on the mz_introspection cluster (Materialize).",
    false,
);

pub static MAX_CONNECTIONS: VarDefinition = VarDefinition::new(
    "max_connections",
    value!(u32; 5000),
    "The maximum number of concurrent connections (PostgreSQL).",
    false,
);

pub static SUPERUSER_RESERVED_CONNECTIONS: VarDefinition = VarDefinition::new(
    "superuser_reserved_connections",
    value!(u32; 3),
    "The number of connections that are reserved for superusers (PostgreSQL).",
    false,
);

/// Controls [`mz_storage_types::parameters::StorageParameters::keep_n_source_status_history_entries`].
pub static KEEP_N_SOURCE_STATUS_HISTORY_ENTRIES: VarDefinition = VarDefinition::new(
    "keep_n_source_status_history_entries",
    value!(usize; 5),
    "On reboot, truncate all but the last n entries per ID in the source_status_history collection (Materialize).",
    true,
);

/// Controls [`mz_storage_types::parameters::StorageParameters::keep_n_sink_status_history_entries`].
pub static KEEP_N_SINK_STATUS_HISTORY_ENTRIES: VarDefinition = VarDefinition::new(
    "keep_n_sink_status_history_entries",
    value!(usize; 5),
    "On reboot, truncate all but the last n entries per ID in the sink_status_history collection (Materialize).",
    true,
);

/// Controls [`mz_storage_types::parameters::StorageParameters::keep_n_privatelink_status_history_entries`].
pub static KEEP_N_PRIVATELINK_STATUS_HISTORY_ENTRIES: VarDefinition = VarDefinition::new(
    "keep_n_privatelink_status_history_entries",
    value!(usize; 5),
    "On reboot, truncate all but the last n entries per ID in the mz_aws_privatelink_connection_status_history \
        collection (Materialize).",
    true,
);

pub static ENABLE_STORAGE_SHARD_FINALIZATION: VarDefinition = VarDefinition::new(
    "enable_storage_shard_finalization",
    value!(bool; true),
    "Whether to allow the storage client to finalize shards (Materialize).",
    true,
);

pub static ENABLE_CONSOLIDATE_AFTER_UNION_NEGATE: VarDefinition = VarDefinition::new(
    "enable_consolidate_after_union_negate",
    value!(bool; true),
    "consolidation after Unions that have a Negated input (Materialize).",
    false,
);

pub static MIN_TIMESTAMP_INTERVAL: VarDefinition = VarDefinition::new(
    "min_timestamp_interval",
    value!(Duration; Duration::from_millis(1000)),
    "Minimum timestamp interval",
    true,
);

pub static MAX_TIMESTAMP_INTERVAL: VarDefinition = VarDefinition::new(
    "max_timestamp_interval",
    value!(Duration; Duration::from_millis(1000)),
    "Maximum timestamp interval",
    true,
);

pub static WEBHOOK_CONCURRENT_REQUEST_LIMIT: VarDefinition = VarDefinition::new(
    "webhook_concurrent_request_limit",
    value!(usize; WEBHOOK_CONCURRENCY_LIMIT),
    "Maximum number of concurrent requests for appending to a webhook source.",
    true,
);

pub static USER_STORAGE_MANAGED_COLLECTIONS_BATCH_DURATION: VarDefinition = VarDefinition::new(
    "user_storage_managed_collections_batch_duration",
    value!(Duration; STORAGE_MANAGED_COLLECTIONS_BATCH_DURATION_DEFAULT),
    "Duration which we'll wait to collect a batch of events for a webhook source.",
    true,
);

pub static ENABLE_DEPENDENCY_READ_HOLD_ASSERTS: VarDefinition = VarDefinition::new(
    "enable_dependency_read_hold_asserts",
    value!(bool; true),
    "Whether to have the storage client check if a subsource's implied capability is less than \
        its write frontier. This should only be set to false in cases where customer envs cannot
        boot (Materialize).",
    true,
);

/// Configuration for gRPC client connections.
pub mod grpc_client {
    use super::*;

    pub static CONNECT_TIMEOUT: VarDefinition = VarDefinition::new(
        "grpc_client_connect_timeout",
        value!(Duration; Duration::from_secs(5)),
        "Timeout to apply to initial gRPC client connection establishment.",
        true,
    );

    pub static HTTP2_KEEP_ALIVE_INTERVAL: VarDefinition = VarDefinition::new(
        "grpc_client_http2_keep_alive_interval",
        value!(Duration; Duration::from_secs(3)),
        "Idle time to wait before sending HTTP/2 PINGs to maintain established gRPC client connections.",
        true,
    );

    pub static HTTP2_KEEP_ALIVE_TIMEOUT: VarDefinition = VarDefinition::new(
        "grpc_client_http2_keep_alive_timeout",
        value!(Duration; Duration::from_secs(5)),
        "Time to wait for HTTP/2 pong response before terminating a gRPC client connection.",
        true,
    );
}

/// Configuration for how cluster replicas are scheduled.
pub mod cluster_scheduling {
    use super::*;
    use mz_orchestrator::scheduling_config::*;

    pub static CLUSTER_MULTI_PROCESS_REPLICA_AZ_AFFINITY_WEIGHT: VarDefinition = VarDefinition::new(
        "cluster_multi_process_replica_az_affinity_weight",
        value!(Option<i32>; DEFAULT_POD_AZ_AFFINITY_WEIGHT),
        "Whether or not to add an availability zone affinity between instances of \
            multi-process replicas. Either an affinity weight or empty (off) (Materialize).",
        true,
    );

    pub static CLUSTER_SOFTEN_REPLICATION_ANTI_AFFINITY: VarDefinition = VarDefinition::new(
        "cluster_soften_replication_anti_affinity",
        value!(bool; DEFAULT_SOFTEN_REPLICATION_ANTI_AFFINITY),
        "Whether or not to turn the node-scope anti affinity between replicas \
            in the same cluster into a preference (Materialize).",
        true,
    );

    pub static CLUSTER_SOFTEN_REPLICATION_ANTI_AFFINITY_WEIGHT: VarDefinition = VarDefinition::new(
        "cluster_soften_replication_anti_affinity_weight",
        value!(i32; DEFAULT_SOFTEN_REPLICATION_ANTI_AFFINITY_WEIGHT),
        "The preference weight for `cluster_soften_replication_anti_affinity` (Materialize).",
        true,
    );

    pub static CLUSTER_ENABLE_TOPOLOGY_SPREAD: VarDefinition = VarDefinition::new(
        "cluster_enable_topology_spread",
        value!(bool; DEFAULT_TOPOLOGY_SPREAD_ENABLED),
        "Whether or not to add topology spread constraints among replicas in the same cluster (Materialize).",
        true,
    );

    pub static CLUSTER_TOPOLOGY_SPREAD_IGNORE_NON_SINGULAR_SCALE: VarDefinition = VarDefinition::new(
        "cluster_topology_spread_ignore_non_singular_scale",
        value!(bool; DEFAULT_TOPOLOGY_SPREAD_IGNORE_NON_SINGULAR_SCALE),
        "If true, ignore replicas with more than 1 process when adding topology spread constraints (Materialize).",
        true,
    );

    pub static CLUSTER_TOPOLOGY_SPREAD_MAX_SKEW: VarDefinition = VarDefinition::new(
        "cluster_topology_spread_max_skew",
        value!(i32; DEFAULT_TOPOLOGY_SPREAD_MAX_SKEW),
        "The `maxSkew` for replica topology spread constraints (Materialize).",
        true,
    );

    pub static CLUSTER_TOPOLOGY_SPREAD_SOFT: VarDefinition = VarDefinition::new(
        "cluster_topology_spread_soft",
        value!(bool; DEFAULT_TOPOLOGY_SPREAD_SOFT),
        "If true, soften the topology spread constraints for replicas (Materialize).",
        true,
    );

    pub static CLUSTER_SOFTEN_AZ_AFFINITY: VarDefinition = VarDefinition::new(
        "cluster_soften_az_affinity",
        value!(bool; DEFAULT_SOFTEN_AZ_AFFINITY),
        "Whether or not to turn the az-scope node affinity for replicas. \
            Note this could violate requests from the user (Materialize).",
        true,
    );

    pub static CLUSTER_SOFTEN_AZ_AFFINITY_WEIGHT: VarDefinition = VarDefinition::new(
        "cluster_soften_az_affinity_weight",
        value!(i32; DEFAULT_SOFTEN_AZ_AFFINITY_WEIGHT),
        "The preference weight for `cluster_soften_az_affinity` (Materialize).",
        true,
    );

    pub static CLUSTER_ALWAYS_USE_DISK: VarDefinition = VarDefinition::new(
        "cluster_always_use_disk",
        value!(bool; DEFAULT_ALWAYS_USE_DISK),
        "Always provisions a replica with disk, regardless of `DISK` DDL option.",
        true,
    );

    const DEFAULT_CHECK_SCHEDULING_POLICIES_INTERVAL: Duration = Duration::from_secs(3);

    pub static CLUSTER_CHECK_SCHEDULING_POLICIES_INTERVAL: VarDefinition = VarDefinition::new(
        "cluster_check_scheduling_policies_interval",
        value!(Duration; DEFAULT_CHECK_SCHEDULING_POLICIES_INTERVAL),
        "How often policies are invoked to automatically start/stop clusters, e.g., \
            for REFRESH EVERY materialized views.",
        true,
    );
}

/// Macro to simplify creating feature flags, i.e. boolean flags that we use to toggle the
/// availability of features.
///
/// The arguments to `feature_flags!` are:
/// - `$name`, which will be the name of the feature flag, in snake_case,
/// - `$feature_desc`, a human-readable description of the feature,
/// - `$value`, which if not provided, defaults to `false` and also defaults `$internal` to `true`.
/// - `$internal`, which if not provided, defaults to `true`. Requires `$value`.
///
/// Note that not all `ServerVar<bool>` are feature flags. Feature flags are for variables that:
/// - Belong to `SystemVars`, _not_ `SessionVars`
/// - Default to false and must be explicitly enabled, or default to `true` and can be explicitly disabled.
///
/// WARNING / CONTRACT: Syntax-related feature flags must always *enable* behavior. In other words,
/// setting a feature flag must make the system more permissive. For example, let's suppose we'd like
/// to gate deprecated upsert syntax behind a feature flag. In this case, do not add a feature flag
/// like `disable_deprecated_upsert_syntax`, as `disable_deprecated_upsert_syntax = on` would
/// _prevent_ the system from parsing the deprecated upsert syntax. Instead, use a feature flag
/// like `enable_deprecated_upsert_syntax`.
///
/// The hazard this protects against is related to reboots after feature flags have been disabled.
/// Say someone creates a Kinesis source while `enable_kinesis_sources = on`. Materialize will
/// commit this source to the system catalog. Then, suppose we discover a catastrophic bug in
/// Kinesis sources and set `enable_kinesis_sources` to `off`. This prevents users from creating
/// new Kinesis sources, but leaves the existing Kinesis sources in place. This is because
/// disabling a feature flag doesn't remove access to catalog objects created while the feature
/// flag was live. On the next reboot, Materialize will proceed to load the Kinesis source from the
/// catalog, reparsing and replanning the `CREATE SOURCE` definition and rechecking the
/// `enable_kinesis_sources` feature flag along the way. Even though the feature flag has been
/// switched to `off`, we need to temporarily re-enable it during parsing and planning to be able
/// to boot successfully.
///
/// Ensuring that all syntax-related feature flags *enable* behavior means that setting all such
/// feature flags to `on` during catalog boot has the desired effect.
macro_rules! feature_flags {
    // Match `$name, $feature_desc, $value, $internal`.
    (@inner
        // The feature flag name.
        name: $name:expr,
        // The feature flag description.
        desc: $desc:literal,
        // The feature flag default value.
        default: $value:expr,
        // Should this feature be visible only internally.
        internal: $internal:expr,
    ) => {
        paste::paste!{
            // Note that the ServerVar is not directly exported; we expect these to be
            // accessible through their FeatureFlag variant.
            static [<$name:upper _VAR>]: VarDefinition = VarDefinition::new(
                stringify!($name),
                value!(bool; $value),
                concat!("Whether ", $desc, " is allowed (Materialize)."),
                $internal
            );

            pub static [<$name:upper >]: FeatureFlag = FeatureFlag {
                flag: &[<$name:upper _VAR>],
                feature_desc: $desc,
            };
        }
    };
    ($({
        // The feature flag name.
        name: $name:expr,
        // The feature flag description.
        desc: $desc:literal,
        // The feature flag default value.
        default: $value:expr,
        // Should this feature be visible only internally.
        internal: $internal:expr,
        // Should the feature be turned on during catalog rehydration when
        // parsing a catalog item.
        enable_for_item_parsing: $enable_for_item_parsing:expr,
    },)+) => {
        $(feature_flags! { @inner
            name: $name,
            desc: $desc,
            default: $value,
            internal: $internal,
        })+

        paste::paste!{
            pub static FEATURE_FLAGS: &'static [&'static VarDefinition] = &[
                $(  & [<$name:upper _VAR>] , )+
            ];
        }

        paste::paste!{
            impl super::SystemVars {
                pub fn enable_all_feature_flags_by_default(&mut self) {
                    $(
                        self.set_default(stringify!($name), super::VarInput::Flat("on"))
                            .expect("setting default value must work");
                    )+
                }

                pub fn enable_for_item_parsing(&mut self) {
                    $(
                        if $enable_for_item_parsing {
                            self.set(stringify!($name), super::VarInput::Flat("on"))
                                .expect("setting default value must work");
                        }
                    )+
                }

                $(
                    pub fn [<$name:lower>](&self) -> bool {
                        *self.expect_value(&[<$name:upper _VAR>])
                    }
                )+
            }
        }
    }
}

feature_flags!(
    // Gates for other feature flags
    {
        name: allow_real_time_recency,
        desc: "real time recency",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    // Actual feature flags
    {
        name: enable_binary_date_bin,
        desc: "the binary version of date_bin function",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_create_sink_denylist_with_options,
        desc: "CREATE SINK with unsafe options",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_create_source_denylist_with_options,
        desc: "CREATE SOURCE with unsafe options",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_date_bin_hopping,
        desc: "the date_bin_hopping function",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_envelope_debezium_in_subscribe,
        desc: "`ENVELOPE DEBEZIUM (KEY (..))`",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_envelope_materialize,
        desc: "ENVELOPE MATERIALIZE",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_explain_pushdown,
        desc: "EXPLAIN FILTER PUSHDOWN",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_index_options,
        desc: "INDEX OPTIONS",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_list_length_max,
        desc: "the list_length_max function",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_list_n_layers,
        desc: "the list_n_layers function",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_list_remove,
        desc: "the list_remove function",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {

        name: enable_logical_compaction_window,
        desc: "RETAIN HISTORY",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_primary_key_not_enforced,
        desc: "PRIMARY KEY NOT ENFORCED",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_multi_worker_storage_persist_sink,
        desc: "multi-worker storage persist sink",
        default: true,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_persist_streaming_snapshot_and_fetch,
        desc: "use the new streaming consolidate for snapshot_and_fetch",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_persist_streaming_compaction,
        desc: "use the new streaming consolidate for compaction",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_raise_statement,
        desc: "RAISE statement",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_repeat_row,
        desc: "the repeat_row function",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_table_check_constraint,
        desc: "CREATE TABLE with a check constraint",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_table_foreign_key,
        desc: "CREATE TABLE with a foreign key",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_table_keys,
        desc: "CREATE TABLE with a primary key or unique constraint",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_unorchestrated_cluster_replicas,
        desc: "unorchestrated cluster replicas",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_unstable_dependencies,
        desc: "depending on unstable objects",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_disk_cluster_replicas,
        desc: "`WITH (DISK)` for cluster replicas",
        default: true,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_within_timestamp_order_by_in_subscribe,
        desc: "`WITHIN TIMESTAMP ORDER BY ..`",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_cardinality_estimates,
        desc: "join planning with cardinality estimates",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_connection_validation_syntax,
        desc: "CREATE CONNECTION .. WITH (VALIDATE) and VALIDATE CONNECTION syntax",
        default: true,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_alter_set_cluster,
        desc: "ALTER ... SET CLUSTER syntax",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_unsafe_functions,
        desc: "executing potentially dangerous functions",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_managed_cluster_availability_zones,
        desc: "MANAGED, AVAILABILITY ZONES syntax",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: statement_logging_use_reproducible_rng,
        desc: "statement logging with reproducible RNG",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_notices_for_index_already_exists,
        desc: "emitting notices for IndexAlreadyExists (doesn't affect EXPLAIN)",
        default: true,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_notices_for_index_too_wide_for_literal_constraints,
        desc: "emitting notices for IndexTooWideForLiteralConstraints (doesn't affect EXPLAIN)",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_notices_for_index_empty_key,
        desc: "emitting notices for indexes with an empty key (doesn't affect EXPLAIN)",
        default: true,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_comment,
        desc: "the COMMENT ON feature for objects",
        default: true,
        internal: false,
        enable_for_item_parsing: true,
    },
    {
        name: enable_alter_swap,
        desc: "the ALTER SWAP feature for objects",
        default: true,
        internal: false,
        enable_for_item_parsing: true,
    },
    {
        name: enable_new_outer_join_lowering,
        desc: "new outer join lowering",
        default: true,
        internal: true,
        enable_for_item_parsing: false,
    },
    {
        name: enable_time_at_time_zone,
        desc: "use of AT TIME ZONE or timezone() with time type",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_aws_connection,
        desc: "CREATE CONNECTION ... TO AWS",
        default: false,
        internal: true,
        enable_for_item_parsing: false,
    },
    {
        name: enable_mysql_source,
        desc: "Create a MySQL connection or source",
        default: false,
        internal: true,
        enable_for_item_parsing: false,
    },
    {
        name: enable_load_generator_key_value,
        desc: "Create a LOAD GENERATOR KEY VALUE",
        default: false,
        internal: true,
        enable_for_item_parsing: false,
    },
    {
        name: enable_expressions_in_limit_syntax,
        desc: "LIMIT <expr> syntax",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_mz_notices,
        desc: "Populate the contents of `mz_internal.mz_notices`",
        default: true,
        internal: true,
        enable_for_item_parsing: false,
    },
    {
        name: enable_eager_delta_joins,
        desc:
            "eager delta joins",
        default: false,
        internal: true,
        enable_for_item_parsing: false,
    },
    {
        name: enable_off_thread_optimization,
        desc: "use off-thread optimization in `CREATE` statements",
        default: true,
        internal: true,
        enable_for_item_parsing: false,
    },
    {
        name: enable_refresh_every_mvs,
        desc: "REFRESH EVERY and REFRESH AT materialized views",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_cluster_schedule_refresh,
        desc: "`SCHEDULE = ON REFRESH` cluster option",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_reduce_mfp_fusion,
        desc: "fusion of MFPs in reductions",
        default: false,
        internal: true,
        enable_for_item_parsing: false,
    },
    {
        name: enable_worker_core_affinity,
        desc: "set core affinity for replica worker threads",
        default: false,
        internal: true,
        enable_for_item_parsing: false,
    },
    {
        name: wait_catalog_consolidation_on_startup,
        desc: "When opening the Catalog, wait for consolidation to complete before returning",
        default: false,
        internal: true,
        enable_for_item_parsing: false,
    },
    {
        name: enable_copy_to_expr,
        desc: "COPY ... TO 's3://...'",
        default: false,
        internal: true,
        enable_for_item_parsing: false,
    },
    {
        name: enable_session_timelines,
        desc: "strong session serializable isolation levels",
        default: false,
        internal: true,
        enable_for_item_parsing: false,
    },
    {
        name: enable_variadic_left_join_lowering,
        desc: "Enable joint HIR ⇒ MIR lowering of stacks of left joins",
        default: false,
        internal: true,
        enable_for_item_parsing: false,
    },
    {
        name: enable_redacted_test_option,
        desc: "Enable useless option to test value redaction",
        default: false,
        internal: true,
        enable_for_item_parsing: true,
    },
    {
        name: enable_letrec_fixpoint_analysis,
        desc: "Enable Lattice-based fixpoint iteration on LetRec nodes in the Analysis framework",
        default: true, // This is just a failsafe switch for the deployment of #25591.
        internal: true,
        enable_for_item_parsing: false,
    },
);

impl From<&super::SystemVars> for OptimizerFeatures {
    fn from(vars: &super::SystemVars) -> Self {
        Self {
            enable_consolidate_after_union_negate: vars.enable_consolidate_after_union_negate(),
            enable_eager_delta_joins: vars.enable_eager_delta_joins(),
            enable_new_outer_join_lowering: vars.enable_new_outer_join_lowering(),
            enable_reduce_mfp_fusion: vars.enable_reduce_mfp_fusion(),
            enable_variadic_left_join_lowering: vars.enable_variadic_left_join_lowering(),
            enable_letrec_fixpoint_analysis: vars.enable_letrec_fixpoint_analysis(),
            persist_fast_path_limit: vars.persist_fast_path_limit(),
            reoptimize_imported_views: false,
        }
    }
}