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::async_runtime;
31use crate::internal::machine::{
32 NEXT_LISTEN_BATCH_RETRYER_CLAMP, NEXT_LISTEN_BATCH_RETRYER_INITIAL_BACKOFF,
33 NEXT_LISTEN_BATCH_RETRYER_MULTIPLIER,
34};
35use crate::internal::state::ROLLUP_THRESHOLD;
36use crate::operators::STORAGE_SOURCE_DECODE_FUEL;
37use crate::read::READER_LEASE_DURATION;
38
39const SELF_MANAGED_VERSIONS: &[Version] = &[
41 Version::new(0, 130, 0),
43 Version::new(0, 147, 0),
45];
46
47#[derive(Debug, Clone)]
99pub struct PersistConfig {
100 pub build_version: Version,
102 pub hostname: String,
104 pub is_cc_active: bool,
106 pub announce_memory_limit: Option<usize>,
108 pub now: NowFn,
110 pub configs: Arc<ConfigSet>,
115 configs_synced_once: Arc<watch::Sender<bool>>,
118 pub compaction_enabled: bool,
120 pub compaction_process_requests: Arc<AtomicBool>,
122 pub compaction_concurrency_limit: usize,
125 pub compaction_queue_size: usize,
128 pub compaction_yield_after_n_updates: usize,
131 pub writer_lease_duration: Duration,
134 pub critical_downgrade_interval: Duration,
136 pub isolated_runtime_worker_threads: usize,
139}
140
141impl std::ops::Deref for PersistConfig {
143 type Target = ConfigSet;
144 fn deref(&self) -> &Self::Target {
145 &self.configs
146 }
147}
148
149impl PersistConfig {
150 pub fn new_default_configs(build_info: &BuildInfo, now: NowFn) -> Self {
153 Self::new(build_info, now, all_dyncfgs(ConfigSet::default()))
154 }
155
156 pub fn new(build_info: &BuildInfo, now: NowFn, configs: ConfigSet) -> Self {
159 let compaction_disabled = mz_ore::env::is_var_truthy("MZ_PERSIST_COMPACTION_DISABLED");
161
162 let (configs_synced_once, _) = watch::channel(false);
164
165 Self {
166 build_version: build_info.semver_version(),
167 is_cc_active: false,
168 announce_memory_limit: None,
169 now,
170 configs: Arc::new(configs),
171 configs_synced_once: Arc::new(configs_synced_once),
172 compaction_enabled: !compaction_disabled,
173 compaction_process_requests: Arc::new(AtomicBool::new(true)),
174 compaction_concurrency_limit: 5,
175 compaction_queue_size: 20,
176 compaction_yield_after_n_updates: 100_000,
177 writer_lease_duration: 60 * Duration::from_secs(60),
178 critical_downgrade_interval: Duration::from_secs(30),
179 isolated_runtime_worker_threads: num_cpus::get(),
180 hostname: std::env::var("HOSTNAME").unwrap_or_else(|_| "unknown".to_owned()),
185 }
186 }
187
188 pub(crate) fn set_config<T: ConfigDefault>(&self, cfg: &Config<T>, val: T) {
189 let mut updates = ConfigUpdates::default();
190 updates.add(cfg, val);
191 updates.apply(self)
192 }
193
194 pub fn apply_from(&self, updates: &ConfigUpdates) {
200 updates.apply(&self.configs);
201 self.configs_synced_once.send_replace(true);
202 }
203
204 #[instrument(level = "info")]
213 pub async fn configs_synced_once(&self) {
214 self.configs_synced_once
215 .subscribe()
216 .wait_for(|synced| *synced)
217 .await
218 .expect("we have a borrow on sender so it cannot drop");
219 }
220
221 pub fn storage_source_decode_fuel(&self) -> usize {
224 STORAGE_SOURCE_DECODE_FUEL.get(self)
225 }
226
227 pub fn set_reader_lease_duration(&self, val: Duration) {
229 self.set_config(&READER_LEASE_DURATION, val);
230 }
231
232 pub fn set_rollup_threshold(&self, val: usize) {
234 self.set_config(&ROLLUP_THRESHOLD, val);
235 }
236
237 pub fn set_next_listen_batch_retryer(&self, val: RetryParameters) {
240 self.set_config(
241 &NEXT_LISTEN_BATCH_RETRYER_INITIAL_BACKOFF,
242 val.initial_backoff,
243 );
244 self.set_config(&NEXT_LISTEN_BATCH_RETRYER_MULTIPLIER, val.multiplier);
245 self.set_config(&NEXT_LISTEN_BATCH_RETRYER_CLAMP, val.clamp);
246 }
247
248 pub fn disable_compaction(&self) {
249 tracing::info!("Disabling Persist Compaction");
250 self.compaction_process_requests
251 .store(false, std::sync::atomic::Ordering::Relaxed);
252 }
253
254 pub fn enable_compaction(&self) {
255 tracing::info!("Enabling Persist Compaction");
256 self.compaction_process_requests
257 .store(true, std::sync::atomic::Ordering::Relaxed);
258 }
259
260 pub fn new_for_tests() -> Self {
262 use mz_build_info::DUMMY_BUILD_INFO;
263 use mz_ore::now::SYSTEM_TIME;
264
265 let mut cfg = Self::new_default_configs(&DUMMY_BUILD_INFO, SYSTEM_TIME.clone());
266 cfg.hostname = "tests".into();
267 cfg.isolated_runtime_worker_threads = async_runtime::TEST_THREADS;
268 cfg
269 }
270}
271
272#[allow(non_upper_case_globals)]
273pub(crate) const MiB: usize = 1024 * 1024;
274
275pub fn all_dyncfgs(configs: ConfigSet) -> ConfigSet {
281 mz_persist::cfg::all_dyn_configs(configs)
282 .add(&crate::batch::BATCH_DELETE_ENABLED)
283 .add(&crate::batch::BLOB_TARGET_SIZE)
284 .add(&crate::batch::INLINE_WRITES_TOTAL_MAX_BYTES)
285 .add(&crate::batch::INLINE_WRITES_SINGLE_MAX_BYTES)
286 .add(&crate::batch::ENCODING_ENABLE_DICTIONARY)
287 .add(&crate::batch::ENCODING_COMPRESSION_FORMAT)
288 .add(&crate::batch::STRUCTURED_KEY_LOWER_LEN)
289 .add(&crate::batch::MAX_RUN_LEN)
290 .add(&crate::batch::MAX_RUNS)
291 .add(&BLOB_OPERATION_TIMEOUT)
292 .add(&BLOB_OPERATION_ATTEMPT_TIMEOUT)
293 .add(&BLOB_CONNECT_TIMEOUT)
294 .add(&BLOB_READ_TIMEOUT)
295 .add(&crate::cfg::CONSENSUS_CONNECTION_POOL_MAX_SIZE)
296 .add(&crate::cfg::CONSENSUS_CONNECTION_POOL_MAX_WAIT)
297 .add(&crate::cfg::CONSENSUS_CONNECTION_POOL_TTL_STAGGER)
298 .add(&crate::cfg::CONSENSUS_CONNECTION_POOL_TTL)
299 .add(&crate::cfg::CRDB_CONNECT_TIMEOUT)
300 .add(&crate::cfg::CRDB_TCP_USER_TIMEOUT)
301 .add(&crate::cfg::USE_CRITICAL_SINCE_TXN)
302 .add(&crate::cfg::USE_CRITICAL_SINCE_CATALOG)
303 .add(&crate::cfg::USE_CRITICAL_SINCE_SOURCE)
304 .add(&crate::cfg::USE_CRITICAL_SINCE_SNAPSHOT)
305 .add(&BATCH_BUILDER_MAX_OUTSTANDING_PARTS)
306 .add(&COMPACTION_HEURISTIC_MIN_INPUTS)
307 .add(&COMPACTION_HEURISTIC_MIN_PARTS)
308 .add(&COMPACTION_HEURISTIC_MIN_UPDATES)
309 .add(&COMPACTION_MEMORY_BOUND_BYTES)
310 .add(&GC_BLOB_DELETE_CONCURRENCY_LIMIT)
311 .add(&STATE_VERSIONS_RECENT_LIVE_DIFFS_LIMIT)
312 .add(&USAGE_STATE_FETCH_CONCURRENCY_LIMIT)
313 .add(&crate::cli::admin::CATALOG_FORCE_COMPACTION_FUEL)
314 .add(&crate::cli::admin::CATALOG_FORCE_COMPACTION_WAIT)
315 .add(&crate::cli::admin::EXPRESSION_CACHE_FORCE_COMPACTION_FUEL)
316 .add(&crate::cli::admin::EXPRESSION_CACHE_FORCE_COMPACTION_WAIT)
317 .add(&crate::fetch::FETCH_SEMAPHORE_COST_ADJUSTMENT)
318 .add(&crate::fetch::FETCH_SEMAPHORE_PERMIT_ADJUSTMENT)
319 .add(&crate::fetch::VALIDATE_PART_BOUNDS_ON_READ)
320 .add(&crate::fetch::OPTIMIZE_IGNORED_DATA_FETCH)
321 .add(&crate::internal::cache::BLOB_CACHE_MEM_LIMIT_BYTES)
322 .add(&crate::internal::cache::BLOB_CACHE_SCALE_WITH_THREADS)
323 .add(&crate::internal::cache::BLOB_CACHE_SCALE_FACTOR_BYTES)
324 .add(&crate::internal::compact::COMPACTION_MINIMUM_TIMEOUT)
325 .add(&crate::internal::compact::COMPACTION_USE_MOST_RECENT_SCHEMA)
326 .add(&crate::internal::compact::COMPACTION_CHECK_PROCESS_FLAG)
327 .add(&crate::internal::machine::CLAIM_UNCLAIMED_COMPACTIONS)
328 .add(&crate::internal::machine::CLAIM_COMPACTION_PERCENT)
329 .add(&crate::internal::machine::CLAIM_COMPACTION_MIN_VERSION)
330 .add(&crate::internal::machine::NEXT_LISTEN_BATCH_RETRYER_CLAMP)
331 .add(&crate::internal::machine::NEXT_LISTEN_BATCH_RETRYER_FIXED_SLEEP)
332 .add(&crate::internal::machine::NEXT_LISTEN_BATCH_RETRYER_INITIAL_BACKOFF)
333 .add(&crate::internal::machine::NEXT_LISTEN_BATCH_RETRYER_MULTIPLIER)
334 .add(&crate::internal::state::ROLLUP_THRESHOLD)
335 .add(&crate::internal::state::ROLLUP_USE_ACTIVE_ROLLUP)
336 .add(&crate::internal::state::GC_FALLBACK_THRESHOLD_MS)
337 .add(&crate::internal::state::GC_USE_ACTIVE_GC)
338 .add(&crate::internal::state::GC_MIN_VERSIONS)
339 .add(&crate::internal::state::GC_MAX_VERSIONS)
340 .add(&crate::internal::state::ROLLUP_FALLBACK_THRESHOLD_MS)
341 .add(&crate::internal::state::ENABLE_INCREMENTAL_COMPACTION)
342 .add(&crate::operators::STORAGE_SOURCE_DECODE_FUEL)
343 .add(&crate::read::READER_LEASE_DURATION)
344 .add(&crate::rpc::PUBSUB_CLIENT_ENABLED)
345 .add(&crate::rpc::PUBSUB_PUSH_DIFF_ENABLED)
346 .add(&crate::rpc::PUBSUB_SAME_PROCESS_DELEGATE_ENABLED)
347 .add(&crate::rpc::PUBSUB_CONNECT_ATTEMPT_TIMEOUT)
348 .add(&crate::rpc::PUBSUB_REQUEST_TIMEOUT)
349 .add(&crate::rpc::PUBSUB_CONNECT_MAX_BACKOFF)
350 .add(&crate::rpc::PUBSUB_CLIENT_SENDER_CHANNEL_SIZE)
351 .add(&crate::rpc::PUBSUB_CLIENT_RECEIVER_CHANNEL_SIZE)
352 .add(&crate::rpc::PUBSUB_SERVER_CONNECTION_CHANNEL_SIZE)
353 .add(&crate::rpc::PUBSUB_STATE_CACHE_SHARD_REF_CHANNEL_SIZE)
354 .add(&crate::rpc::PUBSUB_RECONNECT_BACKOFF)
355 .add(&crate::stats::STATS_AUDIT_PERCENT)
356 .add(&crate::stats::STATS_AUDIT_PANIC)
357 .add(&crate::stats::STATS_BUDGET_BYTES)
358 .add(&crate::stats::STATS_COLLECTION_ENABLED)
359 .add(&crate::stats::STATS_FILTER_ENABLED)
360 .add(&crate::stats::STATS_UNTRIMMABLE_COLUMNS_EQUALS)
361 .add(&crate::stats::STATS_UNTRIMMABLE_COLUMNS_PREFIX)
362 .add(&crate::stats::STATS_UNTRIMMABLE_COLUMNS_SUFFIX)
363 .add(&crate::fetch::PART_DECODE_FORMAT)
364 .add(&crate::write::COMBINE_INLINE_WRITES)
365 .add(&crate::write::VALIDATE_PART_BOUNDS_ON_WRITE)
366}
367
368impl PersistConfig {
369 pub(crate) const DEFAULT_FALLBACK_ROLLUP_THRESHOLD_MULTIPLIER: usize = 3;
370
371 pub fn set_state_versions_recent_live_diffs_limit(&self, val: usize) {
372 self.set_config(&STATE_VERSIONS_RECENT_LIVE_DIFFS_LIMIT, val);
373 }
374}
375
376pub const CONSENSUS_CONNECTION_POOL_MAX_SIZE: Config<usize> = Config::new(
380 "persist_consensus_connection_pool_max_size",
381 50,
382 "The maximum size the connection pool to Postgres/CRDB will grow to.",
383);
384
385const CONSENSUS_CONNECTION_POOL_MAX_WAIT: Config<Duration> = Config::new(
390 "persist_consensus_connection_pool_max_wait",
391 Duration::from_secs(60),
392 "The amount of time we'll wait for a connection to become available.",
393);
394
395const CONSENSUS_CONNECTION_POOL_TTL: Config<Duration> = Config::new(
399 "persist_consensus_connection_pool_ttl",
400 Duration::from_secs(300),
401 "\
402 The minimum TTL of a Consensus connection to Postgres/CRDB before it is \
403 proactively terminated",
404);
405
406const CONSENSUS_CONNECTION_POOL_TTL_STAGGER: Config<Duration> = Config::new(
414 "persist_consensus_connection_pool_ttl_stagger",
415 Duration::from_secs(6),
416 "The minimum time between TTLing Consensus connections to Postgres/CRDB.",
417);
418
419pub const CRDB_CONNECT_TIMEOUT: Config<Duration> = Config::new(
422 "crdb_connect_timeout",
423 Duration::from_secs(5),
424 "The time to connect to CockroachDB before timing out and retrying.",
425);
426
427pub const CRDB_TCP_USER_TIMEOUT: Config<Duration> = Config::new(
431 "crdb_tcp_user_timeout",
432 Duration::from_secs(30),
433 "\
434 The TCP timeout for connections to CockroachDB. Specifies the amount of \
435 time that transmitted data may remain unacknowledged before the TCP \
436 connection is forcibly closed.",
437);
438
439pub const USE_CRITICAL_SINCE_TXN: Config<bool> = Config::new(
441 "persist_use_critical_since_txn",
442 true,
443 "Use the critical since (instead of the overall since) when initializing a subscribe.",
444);
445
446pub const USE_CRITICAL_SINCE_CATALOG: Config<bool> = Config::new(
448 "persist_use_critical_since_catalog",
449 false,
450 "Use the critical since (instead of the overall since) for the Persist-backed catalog.",
451);
452
453pub const USE_CRITICAL_SINCE_SOURCE: Config<bool> = Config::new(
455 "persist_use_critical_since_source",
456 false,
457 "Use the critical since (instead of the overall since) in the Persist source.",
458);
459
460pub const USE_CRITICAL_SINCE_SNAPSHOT: Config<bool> = Config::new(
462 "persist_use_critical_since_snapshot",
463 false,
464 "Use the critical since (instead of the overall since) when taking snapshots in the controller or in fast-path peeks.",
465);
466
467pub const BATCH_BUILDER_MAX_OUTSTANDING_PARTS: Config<usize> = Config::new(
471 "persist_batch_builder_max_outstanding_parts",
472 2,
473 "The number of writes a batch builder can have outstanding before we slow down the writer.",
474);
475
476pub const COMPACTION_HEURISTIC_MIN_INPUTS: Config<usize> = Config::new(
480 "persist_compaction_heuristic_min_inputs",
481 8,
482 "Don't skip compaction if we have more than this many hollow batches as input.",
483);
484
485pub const COMPACTION_HEURISTIC_MIN_PARTS: Config<usize> = Config::new(
489 "persist_compaction_heuristic_min_parts",
490 8,
491 "Don't skip compaction if we have more than this many parts as input.",
492);
493
494pub const COMPACTION_HEURISTIC_MIN_UPDATES: Config<usize> = Config::new(
498 "persist_compaction_heuristic_min_updates",
499 1024,
500 "Don't skip compaction if we have more than this many updates as input.",
501);
502
503pub const COMPACTION_MEMORY_BOUND_BYTES: Config<usize> = Config::new(
508 "persist_compaction_memory_bound_bytes",
509 1024 * MiB,
510 "Attempt to limit compaction to this amount of memory.",
511);
512
513pub const GC_BLOB_DELETE_CONCURRENCY_LIMIT: Config<usize> = Config::new(
515 "persist_gc_blob_delete_concurrency_limit",
516 32,
517 "Limit the number of concurrent deletes GC can perform to this threshold.",
518);
519
520pub const STATE_VERSIONS_RECENT_LIVE_DIFFS_LIMIT: Config<usize> = Config::new(
530 "persist_state_versions_recent_live_diffs_limit",
531 30 * 128,
532 "Fetch this many diffs when fetching recent diffs.",
533);
534
535pub const USAGE_STATE_FETCH_CONCURRENCY_LIMIT: Config<usize> = Config::new(
537 "persist_usage_state_fetch_concurrency_limit",
538 8,
539 "Limit the concurrency in of fetching in the perioding Persist-storage-usage calculation.",
540);
541
542impl PostgresClientKnobs for PersistConfig {
543 fn connection_pool_max_size(&self) -> usize {
544 CONSENSUS_CONNECTION_POOL_MAX_SIZE.get(self)
545 }
546
547 fn connection_pool_max_wait(&self) -> Option<Duration> {
548 Some(CONSENSUS_CONNECTION_POOL_MAX_WAIT.get(self))
549 }
550
551 fn connection_pool_ttl(&self) -> Duration {
552 CONSENSUS_CONNECTION_POOL_TTL.get(self)
553 }
554
555 fn connection_pool_ttl_stagger(&self) -> Duration {
556 CONSENSUS_CONNECTION_POOL_TTL_STAGGER.get(self)
557 }
558
559 fn connect_timeout(&self) -> Duration {
560 CRDB_CONNECT_TIMEOUT.get(self)
561 }
562
563 fn tcp_user_timeout(&self) -> Duration {
564 CRDB_TCP_USER_TIMEOUT.get(self)
565 }
566}
567
568#[derive(Copy, Clone, Debug, Eq, PartialEq, Arbitrary, Serialize, Deserialize)]
569pub struct RetryParameters {
570 pub fixed_sleep: Duration,
571 pub initial_backoff: Duration,
572 pub multiplier: u32,
573 pub clamp: Duration,
574}
575
576impl RetryParameters {
577 pub(crate) fn into_retry(self, now: SystemTime) -> Retry {
578 let seed = now
579 .duration_since(UNIX_EPOCH)
580 .map_or(0, |x| u64::from(x.subsec_nanos()));
581 Retry {
582 fixed_sleep: self.fixed_sleep,
583 initial_backoff: self.initial_backoff,
584 multiplier: self.multiplier,
585 clamp_backoff: self.clamp,
586 seed,
587 }
588 }
589}
590
591pub(crate) const BLOB_OPERATION_TIMEOUT: Config<Duration> = Config::new(
592 "persist_blob_operation_timeout",
593 Duration::from_secs(180),
594 "Maximum time allowed for a network call, including retry attempts.",
595);
596
597pub(crate) const BLOB_OPERATION_ATTEMPT_TIMEOUT: Config<Duration> = Config::new(
598 "persist_blob_operation_attempt_timeout",
599 Duration::from_secs(90),
600 "Maximum time allowed for a single network call.",
601);
602
603pub(crate) const BLOB_CONNECT_TIMEOUT: Config<Duration> = Config::new(
604 "persist_blob_connect_timeout",
605 Duration::from_secs(7),
606 "Maximum time to wait for a socket connection to be made.",
607);
608
609pub(crate) const BLOB_READ_TIMEOUT: Config<Duration> = Config::new(
610 "persist_blob_read_timeout",
611 Duration::from_secs(10),
612 "Maximum time to wait to read the first byte of a response, including connection time.",
613);
614
615impl BlobKnobs for PersistConfig {
616 fn operation_timeout(&self) -> Duration {
617 BLOB_OPERATION_TIMEOUT.get(self)
618 }
619
620 fn operation_attempt_timeout(&self) -> Duration {
621 BLOB_OPERATION_ATTEMPT_TIMEOUT.get(self)
622 }
623
624 fn connect_timeout(&self) -> Duration {
625 BLOB_CONNECT_TIMEOUT.get(self)
626 }
627
628 fn read_timeout(&self) -> Duration {
629 BLOB_READ_TIMEOUT.get(self)
630 }
631
632 fn is_cc_active(&self) -> bool {
633 self.is_cc_active
634 }
635}
636
637pub fn check_data_version(code_version: &Version, data_version: &Version) -> Result<(), String> {
638 check_data_version_with_self_managed_versions(code_version, data_version, SELF_MANAGED_VERSIONS)
639}
640
641pub(crate) fn check_data_version_with_self_managed_versions(
666 code_version: &Version,
667 data_version: &Version,
668 self_managed_versions: &[Version],
669) -> Result<(), String> {
670 let base_code_version = Version {
672 patch: 0,
673 ..code_version.clone()
674 };
675 let base_data_version = Version {
676 patch: 0,
677 ..data_version.clone()
678 };
679 if data_version >= code_version {
680 for window in self_managed_versions.windows(2) {
681 if base_code_version == window[0] && base_data_version <= window[1] {
682 return Ok(());
683 }
684 }
685
686 if let Some(last) = self_managed_versions.last() {
687 if base_code_version == *last
688 && base_data_version
694 .minor
695 .saturating_sub(base_code_version.minor)
696 < 40
697 {
698 return Ok(());
699 }
700 }
701 }
702
703 let max_allowed_data_version = Version::new(
708 code_version.major,
709 code_version.minor.saturating_add(1),
710 u64::MAX,
711 );
712
713 if &max_allowed_data_version < data_version {
714 Err(format!(
715 "{code_version} received persist state from the future {data_version}",
716 ))
717 } else {
718 Ok(())
719 }
720}