1#![allow(missing_docs)]
11
12use std::sync::Arc;
15use std::sync::atomic::AtomicBool;
16use std::time::{Duration, SystemTime, UNIX_EPOCH};
17
18use mz_build_info::BuildInfo;
19use mz_dyncfg::{Config, ConfigDefault, ConfigSet, ConfigUpdates};
20use mz_ore::instrument;
21use mz_ore::now::NowFn;
22use mz_persist::cfg::BlobKnobs;
23use mz_persist::retry::Retry;
24use mz_postgres_client::PostgresClientKnobs;
25use proptest_derive::Arbitrary;
26use semver::Version;
27use serde::{Deserialize, Serialize};
28use tokio::sync::watch;
29
30use crate::internal::machine::{
31 NEXT_LISTEN_BATCH_RETRYER_CLAMP, NEXT_LISTEN_BATCH_RETRYER_INITIAL_BACKOFF,
32 NEXT_LISTEN_BATCH_RETRYER_MULTIPLIER,
33};
34use crate::internal::state::ROLLUP_THRESHOLD;
35use crate::operators::STORAGE_SOURCE_DECODE_FUEL;
36use crate::read::READER_LEASE_DURATION;
37
38const LTS_VERSIONS: &[Version] = &[
39 Version::new(0, 130, 0),
41];
42
43#[derive(Debug, Clone)]
95pub struct PersistConfig {
96 pub build_version: Version,
98 pub hostname: String,
100 pub is_cc_active: bool,
102 pub announce_memory_limit: Option<usize>,
104 pub now: NowFn,
106 pub configs: Arc<ConfigSet>,
111 configs_synced_once: Arc<watch::Sender<bool>>,
114 pub compaction_enabled: bool,
116 pub compaction_process_requests: Arc<AtomicBool>,
118 pub compaction_concurrency_limit: usize,
121 pub compaction_queue_size: usize,
124 pub compaction_yield_after_n_updates: usize,
127 pub writer_lease_duration: Duration,
130 pub critical_downgrade_interval: Duration,
132 pub isolated_runtime_worker_threads: usize,
135}
136
137impl std::ops::Deref for PersistConfig {
139 type Target = ConfigSet;
140 fn deref(&self) -> &Self::Target {
141 &self.configs
142 }
143}
144
145impl PersistConfig {
146 pub fn new_default_configs(build_info: &BuildInfo, now: NowFn) -> Self {
149 Self::new(build_info, now, all_dyncfgs(ConfigSet::default()))
150 }
151
152 pub fn new(build_info: &BuildInfo, now: NowFn, configs: ConfigSet) -> Self {
155 let compaction_disabled = mz_ore::env::is_var_truthy("MZ_PERSIST_COMPACTION_DISABLED");
157
158 let (configs_synced_once, _) = watch::channel(false);
160
161 Self {
162 build_version: build_info.semver_version(),
163 is_cc_active: false,
164 announce_memory_limit: None,
165 now,
166 configs: Arc::new(configs),
167 configs_synced_once: Arc::new(configs_synced_once),
168 compaction_enabled: !compaction_disabled,
169 compaction_process_requests: Arc::new(AtomicBool::new(true)),
170 compaction_concurrency_limit: 5,
171 compaction_queue_size: 20,
172 compaction_yield_after_n_updates: 100_000,
173 writer_lease_duration: 60 * Duration::from_secs(60),
174 critical_downgrade_interval: Duration::from_secs(30),
175 isolated_runtime_worker_threads: num_cpus::get(),
176 hostname: std::env::var("HOSTNAME").unwrap_or_else(|_| "unknown".to_owned()),
181 }
182 }
183
184 pub(crate) fn set_config<T: ConfigDefault>(&self, cfg: &Config<T>, val: T) {
185 let mut updates = ConfigUpdates::default();
186 updates.add(cfg, val);
187 updates.apply(self)
188 }
189
190 pub fn apply_from(&self, updates: &ConfigUpdates) {
196 updates.apply(&self.configs);
197 self.configs_synced_once.send_replace(true);
198 }
199
200 #[instrument(level = "info")]
209 pub async fn configs_synced_once(&self) {
210 self.configs_synced_once
211 .subscribe()
212 .wait_for(|synced| *synced)
213 .await
214 .expect("we have a borrow on sender so it cannot drop");
215 }
216
217 pub fn storage_source_decode_fuel(&self) -> usize {
220 STORAGE_SOURCE_DECODE_FUEL.get(self)
221 }
222
223 pub fn set_reader_lease_duration(&self, val: Duration) {
225 self.set_config(&READER_LEASE_DURATION, val);
226 }
227
228 pub fn set_rollup_threshold(&self, val: usize) {
230 self.set_config(&ROLLUP_THRESHOLD, val);
231 }
232
233 pub fn set_next_listen_batch_retryer(&self, val: RetryParameters) {
236 self.set_config(
237 &NEXT_LISTEN_BATCH_RETRYER_INITIAL_BACKOFF,
238 val.initial_backoff,
239 );
240 self.set_config(&NEXT_LISTEN_BATCH_RETRYER_MULTIPLIER, val.multiplier);
241 self.set_config(&NEXT_LISTEN_BATCH_RETRYER_CLAMP, val.clamp);
242 }
243
244 pub fn disable_compaction(&self) {
245 tracing::info!("Disabling Persist Compaction");
246 self.compaction_process_requests
247 .store(false, std::sync::atomic::Ordering::Relaxed);
248 }
249
250 pub fn enable_compaction(&self) {
251 tracing::info!("Enabling Persist Compaction");
252 self.compaction_process_requests
253 .store(true, std::sync::atomic::Ordering::Relaxed);
254 }
255
256 pub fn new_for_tests() -> Self {
258 use mz_build_info::DUMMY_BUILD_INFO;
259 use mz_ore::now::SYSTEM_TIME;
260
261 let mut cfg = Self::new_default_configs(&DUMMY_BUILD_INFO, SYSTEM_TIME.clone());
262 cfg.hostname = "tests".into();
263 cfg
264 }
265}
266
267#[allow(non_upper_case_globals)]
268pub(crate) const MiB: usize = 1024 * 1024;
269
270pub fn all_dyncfgs(configs: ConfigSet) -> ConfigSet {
276 mz_persist::cfg::all_dyn_configs(configs)
277 .add(&crate::batch::BATCH_DELETE_ENABLED)
278 .add(&crate::batch::BLOB_TARGET_SIZE)
279 .add(&crate::batch::INLINE_WRITES_TOTAL_MAX_BYTES)
280 .add(&crate::batch::INLINE_WRITES_SINGLE_MAX_BYTES)
281 .add(&crate::batch::ENCODING_ENABLE_DICTIONARY)
282 .add(&crate::batch::ENCODING_COMPRESSION_FORMAT)
283 .add(&crate::batch::STRUCTURED_KEY_LOWER_LEN)
284 .add(&crate::batch::MAX_RUN_LEN)
285 .add(&crate::batch::MAX_RUNS)
286 .add(&BLOB_OPERATION_TIMEOUT)
287 .add(&BLOB_OPERATION_ATTEMPT_TIMEOUT)
288 .add(&BLOB_CONNECT_TIMEOUT)
289 .add(&BLOB_READ_TIMEOUT)
290 .add(&crate::cfg::CONSENSUS_CONNECTION_POOL_MAX_SIZE)
291 .add(&crate::cfg::CONSENSUS_CONNECTION_POOL_MAX_WAIT)
292 .add(&crate::cfg::CONSENSUS_CONNECTION_POOL_TTL_STAGGER)
293 .add(&crate::cfg::CONSENSUS_CONNECTION_POOL_TTL)
294 .add(&crate::cfg::CRDB_CONNECT_TIMEOUT)
295 .add(&crate::cfg::CRDB_TCP_USER_TIMEOUT)
296 .add(&crate::cfg::USE_CRITICAL_SINCE_TXN)
297 .add(&crate::cfg::USE_CRITICAL_SINCE_CATALOG)
298 .add(&crate::cfg::USE_CRITICAL_SINCE_SOURCE)
299 .add(&crate::cfg::USE_CRITICAL_SINCE_SNAPSHOT)
300 .add(&crate::cfg::USE_GLOBAL_TXN_CACHE_SOURCE)
301 .add(&BATCH_BUILDER_MAX_OUTSTANDING_PARTS)
302 .add(&COMPACTION_HEURISTIC_MIN_INPUTS)
303 .add(&COMPACTION_HEURISTIC_MIN_PARTS)
304 .add(&COMPACTION_HEURISTIC_MIN_UPDATES)
305 .add(&COMPACTION_MEMORY_BOUND_BYTES)
306 .add(&GC_BLOB_DELETE_CONCURRENCY_LIMIT)
307 .add(&STATE_VERSIONS_RECENT_LIVE_DIFFS_LIMIT)
308 .add(&USAGE_STATE_FETCH_CONCURRENCY_LIMIT)
309 .add(&crate::cli::admin::CATALOG_FORCE_COMPACTION_FUEL)
310 .add(&crate::cli::admin::CATALOG_FORCE_COMPACTION_WAIT)
311 .add(&crate::cli::admin::EXPRESSION_CACHE_FORCE_COMPACTION_FUEL)
312 .add(&crate::cli::admin::EXPRESSION_CACHE_FORCE_COMPACTION_WAIT)
313 .add(&crate::fetch::FETCH_SEMAPHORE_COST_ADJUSTMENT)
314 .add(&crate::fetch::FETCH_SEMAPHORE_PERMIT_ADJUSTMENT)
315 .add(&crate::fetch::OPTIMIZE_IGNORED_DATA_FETCH)
316 .add(&crate::internal::cache::BLOB_CACHE_MEM_LIMIT_BYTES)
317 .add(&crate::internal::cache::BLOB_CACHE_SCALE_WITH_THREADS)
318 .add(&crate::internal::cache::BLOB_CACHE_SCALE_FACTOR_BYTES)
319 .add(&crate::internal::compact::COMPACTION_MINIMUM_TIMEOUT)
320 .add(&crate::internal::compact::COMPACTION_USE_MOST_RECENT_SCHEMA)
321 .add(&crate::internal::compact::COMPACTION_CHECK_PROCESS_FLAG)
322 .add(&crate::internal::machine::CLAIM_UNCLAIMED_COMPACTIONS)
323 .add(&crate::internal::machine::CLAIM_COMPACTION_PERCENT)
324 .add(&crate::internal::machine::CLAIM_COMPACTION_MIN_VERSION)
325 .add(&crate::internal::machine::NEXT_LISTEN_BATCH_RETRYER_CLAMP)
326 .add(&crate::internal::machine::NEXT_LISTEN_BATCH_RETRYER_FIXED_SLEEP)
327 .add(&crate::internal::machine::NEXT_LISTEN_BATCH_RETRYER_INITIAL_BACKOFF)
328 .add(&crate::internal::machine::NEXT_LISTEN_BATCH_RETRYER_MULTIPLIER)
329 .add(&crate::internal::machine::RECORD_COMPACTIONS)
330 .add(&crate::internal::state::ROLLUP_THRESHOLD)
331 .add(&crate::operators::STORAGE_SOURCE_DECODE_FUEL)
332 .add(&crate::read::READER_LEASE_DURATION)
333 .add(&crate::rpc::PUBSUB_CLIENT_ENABLED)
334 .add(&crate::rpc::PUBSUB_PUSH_DIFF_ENABLED)
335 .add(&crate::rpc::PUBSUB_SAME_PROCESS_DELEGATE_ENABLED)
336 .add(&crate::rpc::PUBSUB_CONNECT_ATTEMPT_TIMEOUT)
337 .add(&crate::rpc::PUBSUB_REQUEST_TIMEOUT)
338 .add(&crate::rpc::PUBSUB_CONNECT_MAX_BACKOFF)
339 .add(&crate::rpc::PUBSUB_CLIENT_SENDER_CHANNEL_SIZE)
340 .add(&crate::rpc::PUBSUB_CLIENT_RECEIVER_CHANNEL_SIZE)
341 .add(&crate::rpc::PUBSUB_SERVER_CONNECTION_CHANNEL_SIZE)
342 .add(&crate::rpc::PUBSUB_STATE_CACHE_SHARD_REF_CHANNEL_SIZE)
343 .add(&crate::rpc::PUBSUB_RECONNECT_BACKOFF)
344 .add(&crate::stats::STATS_AUDIT_PERCENT)
345 .add(&crate::stats::STATS_BUDGET_BYTES)
346 .add(&crate::stats::STATS_COLLECTION_ENABLED)
347 .add(&crate::stats::STATS_FILTER_ENABLED)
348 .add(&crate::stats::STATS_UNTRIMMABLE_COLUMNS_EQUALS)
349 .add(&crate::stats::STATS_UNTRIMMABLE_COLUMNS_PREFIX)
350 .add(&crate::stats::STATS_UNTRIMMABLE_COLUMNS_SUFFIX)
351 .add(&crate::fetch::PART_DECODE_FORMAT)
352 .add(&crate::write::COMBINE_INLINE_WRITES)
353}
354
355impl PersistConfig {
356 pub(crate) const DEFAULT_FALLBACK_ROLLUP_THRESHOLD_MULTIPLIER: usize = 3;
357
358 pub fn set_state_versions_recent_live_diffs_limit(&self, val: usize) {
359 self.set_config(&STATE_VERSIONS_RECENT_LIVE_DIFFS_LIMIT, val);
360 }
361}
362
363pub const CONSENSUS_CONNECTION_POOL_MAX_SIZE: Config<usize> = Config::new(
367 "persist_consensus_connection_pool_max_size",
368 50,
369 "The maximum size the connection pool to Postgres/CRDB will grow to.",
370);
371
372const CONSENSUS_CONNECTION_POOL_MAX_WAIT: Config<Duration> = Config::new(
377 "persist_consensus_connection_pool_max_wait",
378 Duration::from_secs(60),
379 "The amount of time we'll wait for a connection to become available.",
380);
381
382const CONSENSUS_CONNECTION_POOL_TTL: Config<Duration> = Config::new(
386 "persist_consensus_connection_pool_ttl",
387 Duration::from_secs(300),
388 "\
389 The minimum TTL of a Consensus connection to Postgres/CRDB before it is \
390 proactively terminated",
391);
392
393const CONSENSUS_CONNECTION_POOL_TTL_STAGGER: Config<Duration> = Config::new(
401 "persist_consensus_connection_pool_ttl_stagger",
402 Duration::from_secs(6),
403 "The minimum time between TTLing Consensus connections to Postgres/CRDB.",
404);
405
406pub const CRDB_CONNECT_TIMEOUT: Config<Duration> = Config::new(
409 "crdb_connect_timeout",
410 Duration::from_secs(5),
411 "The time to connect to CockroachDB before timing out and retrying.",
412);
413
414pub const CRDB_TCP_USER_TIMEOUT: Config<Duration> = Config::new(
418 "crdb_tcp_user_timeout",
419 Duration::from_secs(30),
420 "\
421 The TCP timeout for connections to CockroachDB. Specifies the amount of \
422 time that transmitted data may remain unacknowledged before the TCP \
423 connection is forcibly closed.",
424);
425
426pub const USE_CRITICAL_SINCE_TXN: Config<bool> = Config::new(
428 "persist_use_critical_since_txn",
429 true,
430 "Use the critical since (instead of the overall since) when initializing a subscribe.",
431);
432
433pub const USE_CRITICAL_SINCE_CATALOG: Config<bool> = Config::new(
435 "persist_use_critical_since_catalog",
436 false,
437 "Use the critical since (instead of the overall since) for the Persist-backed catalog.",
438);
439
440pub const USE_CRITICAL_SINCE_SOURCE: Config<bool> = Config::new(
442 "persist_use_critical_since_source",
443 false,
444 "Use the critical since (instead of the overall since) in the Persist source.",
445);
446
447pub const USE_CRITICAL_SINCE_SNAPSHOT: Config<bool> = Config::new(
449 "persist_use_critical_since_snapshot",
450 false,
451 "Use the critical since (instead of the overall since) when taking snapshots in the controller or in fast-path peeks.",
452);
453
454pub const USE_GLOBAL_TXN_CACHE_SOURCE: Config<bool> = Config::new(
456 "use_global_txn_cache_source",
457 true,
458 "Use the process global txn cache (instead of an operator local one) in the Persist source.",
459);
460
461pub const BATCH_BUILDER_MAX_OUTSTANDING_PARTS: Config<usize> = Config::new(
465 "persist_batch_builder_max_outstanding_parts",
466 2,
467 "The number of writes a batch builder can have outstanding before we slow down the writer.",
468);
469
470pub const COMPACTION_HEURISTIC_MIN_INPUTS: Config<usize> = Config::new(
474 "persist_compaction_heuristic_min_inputs",
475 8,
476 "Don't skip compaction if we have more than this many hollow batches as input.",
477);
478
479pub const COMPACTION_HEURISTIC_MIN_PARTS: Config<usize> = Config::new(
483 "persist_compaction_heuristic_min_parts",
484 8,
485 "Don't skip compaction if we have more than this many parts as input.",
486);
487
488pub const COMPACTION_HEURISTIC_MIN_UPDATES: Config<usize> = Config::new(
492 "persist_compaction_heuristic_min_updates",
493 1024,
494 "Don't skip compaction if we have more than this many updates as input.",
495);
496
497pub const COMPACTION_MEMORY_BOUND_BYTES: Config<usize> = Config::new(
502 "persist_compaction_memory_bound_bytes",
503 1024 * MiB,
504 "Attempt to limit compaction to this amount of memory.",
505);
506
507pub const GC_BLOB_DELETE_CONCURRENCY_LIMIT: Config<usize> = Config::new(
509 "persist_gc_blob_delete_concurrency_limit",
510 32,
511 "Limit the number of concurrent deletes GC can perform to this threshold.",
512);
513
514pub const STATE_VERSIONS_RECENT_LIVE_DIFFS_LIMIT: Config<usize> = Config::new(
524 "persist_state_versions_recent_live_diffs_limit",
525 30 * 128,
526 "Fetch this many diffs when fetching recent diffs.",
527);
528
529pub const USAGE_STATE_FETCH_CONCURRENCY_LIMIT: Config<usize> = Config::new(
531 "persist_usage_state_fetch_concurrency_limit",
532 8,
533 "Limit the concurrency in of fetching in the perioding Persist-storage-usage calculation.",
534);
535
536impl PostgresClientKnobs for PersistConfig {
537 fn connection_pool_max_size(&self) -> usize {
538 CONSENSUS_CONNECTION_POOL_MAX_SIZE.get(self)
539 }
540
541 fn connection_pool_max_wait(&self) -> Option<Duration> {
542 Some(CONSENSUS_CONNECTION_POOL_MAX_WAIT.get(self))
543 }
544
545 fn connection_pool_ttl(&self) -> Duration {
546 CONSENSUS_CONNECTION_POOL_TTL.get(self)
547 }
548
549 fn connection_pool_ttl_stagger(&self) -> Duration {
550 CONSENSUS_CONNECTION_POOL_TTL_STAGGER.get(self)
551 }
552
553 fn connect_timeout(&self) -> Duration {
554 CRDB_CONNECT_TIMEOUT.get(self)
555 }
556
557 fn tcp_user_timeout(&self) -> Duration {
558 CRDB_TCP_USER_TIMEOUT.get(self)
559 }
560}
561
562#[derive(Copy, Clone, Debug, Eq, PartialEq, Arbitrary, Serialize, Deserialize)]
563pub struct RetryParameters {
564 pub fixed_sleep: Duration,
565 pub initial_backoff: Duration,
566 pub multiplier: u32,
567 pub clamp: Duration,
568}
569
570impl RetryParameters {
571 pub(crate) fn into_retry(self, now: SystemTime) -> Retry {
572 let seed = now
573 .duration_since(UNIX_EPOCH)
574 .map_or(0, |x| u64::from(x.subsec_nanos()));
575 Retry {
576 fixed_sleep: self.fixed_sleep,
577 initial_backoff: self.initial_backoff,
578 multiplier: self.multiplier,
579 clamp_backoff: self.clamp,
580 seed,
581 }
582 }
583}
584
585pub(crate) const BLOB_OPERATION_TIMEOUT: Config<Duration> = Config::new(
586 "persist_blob_operation_timeout",
587 Duration::from_secs(180),
588 "Maximum time allowed for a network call, including retry attempts.",
589);
590
591pub(crate) const BLOB_OPERATION_ATTEMPT_TIMEOUT: Config<Duration> = Config::new(
592 "persist_blob_operation_attempt_timeout",
593 Duration::from_secs(90),
594 "Maximum time allowed for a single network call.",
595);
596
597pub(crate) const BLOB_CONNECT_TIMEOUT: Config<Duration> = Config::new(
598 "persist_blob_connect_timeout",
599 Duration::from_secs(7),
600 "Maximum time to wait for a socket connection to be made.",
601);
602
603pub(crate) const BLOB_READ_TIMEOUT: Config<Duration> = Config::new(
604 "persist_blob_read_timeout",
605 Duration::from_secs(10),
606 "Maximum time to wait to read the first byte of a response, including connection time.",
607);
608
609impl BlobKnobs for PersistConfig {
610 fn operation_timeout(&self) -> Duration {
611 BLOB_OPERATION_TIMEOUT.get(self)
612 }
613
614 fn operation_attempt_timeout(&self) -> Duration {
615 BLOB_OPERATION_ATTEMPT_TIMEOUT.get(self)
616 }
617
618 fn connect_timeout(&self) -> Duration {
619 BLOB_CONNECT_TIMEOUT.get(self)
620 }
621
622 fn read_timeout(&self) -> Duration {
623 BLOB_READ_TIMEOUT.get(self)
624 }
625
626 fn is_cc_active(&self) -> bool {
627 self.is_cc_active
628 }
629}
630
631pub fn check_data_version(code_version: &Version, data_version: &Version) -> Result<(), String> {
632 check_data_version_with_lts_versions(code_version, data_version, LTS_VERSIONS)
633}
634
635pub(crate) fn check_data_version_with_lts_versions(
660 code_version: &Version,
661 data_version: &Version,
662 lts_versions: &[Version],
663) -> Result<(), String> {
664 let base_code_version = Version {
666 patch: 0,
667 ..code_version.clone()
668 };
669 let base_data_version = Version {
670 patch: 0,
671 ..data_version.clone()
672 };
673 if data_version >= code_version {
674 for window in lts_versions.windows(2) {
675 if base_code_version == window[0] && base_data_version <= window[1] {
676 return Ok(());
677 }
678 }
679
680 if let Some(last) = lts_versions.last() {
681 if base_code_version == *last
682 && base_data_version
688 .minor
689 .saturating_sub(base_code_version.minor)
690 < 40
691 {
692 return Ok(());
693 }
694 }
695 }
696
697 let max_allowed_data_version = Version::new(
702 code_version.major,
703 code_version.minor.saturating_add(1),
704 u64::MAX,
705 );
706
707 if &max_allowed_data_version < data_version {
708 Err(format!(
709 "{code_version} received persist state from the future {data_version}",
710 ))
711 } else {
712 Ok(())
713 }
714}