1use std::borrow::Cow;
70use std::collections::{BTreeMap, BTreeSet, VecDeque};
71use std::net::IpAddr;
72use std::num::NonZeroI64;
73use std::ops::Neg;
74use std::str::FromStr;
75use std::sync::LazyLock;
76use std::sync::{Arc, Mutex};
77use std::thread;
78use std::time::{Duration, Instant};
79use std::{fmt, mem};
80
81use anyhow::Context;
82use chrono::{DateTime, Utc};
83use derivative::Derivative;
84use differential_dataflow::lattice::Lattice;
85use fail::fail_point;
86use futures::StreamExt;
87use futures::future::{BoxFuture, FutureExt, LocalBoxFuture};
88use http::Uri;
89use ipnet::IpNet;
90use itertools::Itertools;
91use mz_adapter_types::bootstrap_builtin_cluster_config::BootstrapBuiltinClusterConfig;
92use mz_adapter_types::compaction::CompactionWindow;
93use mz_adapter_types::connection::ConnectionId;
94use mz_adapter_types::dyncfgs::{ENABLE_0DT_HYDRATE_MIGRATED_BUILTIN_MVS, USER_ID_POOL_BATCH_SIZE};
95use mz_auth::password::Password;
96use mz_build_info::BuildInfo;
97use mz_catalog::builtin::{
98 BUILTINS, BUILTINS_STATIC, MZ_OBJECT_ARRANGEMENT_SIZE_HISTORY, MZ_OBJECT_HYDRATION_HISTORY,
99 MZ_REPLICA_HYDRATION_HISTORY, MZ_STORAGE_USAGE_BY_SHARD,
100};
101use mz_catalog::config::{AwsPrincipalContext, BuiltinItemMigrationConfig, ClusterReplicaSizeMap};
102use mz_catalog::durable::OpenableDurableCatalogState;
103use mz_catalog::expr_cache::{GlobalExpressions, LocalExpressions, latest_item_version};
104use mz_catalog::memory::objects::{
105 CatalogEntry, CatalogItem, ClusterReplicaProcessStatus, DataSourceDesc, ReconfigurationTarget,
106 Table, TableDataSource,
107};
108use mz_cloud_resources::{CloudResourceController, VpcEndpointConfig, VpcEndpointEvent};
109use mz_compute_client::as_of_selection;
110use mz_compute_client::controller::error::{
111 CollectionLookupError, CollectionMissing, DataflowCreationError, InstanceMissing,
112};
113use mz_compute_types::ComputeInstanceId;
114use mz_compute_types::dataflows::LirDataflowDescription;
115use mz_controller::clusters::{
116 ClusterConfig, ClusterEvent, ClusterStatus, ProcessId, ReplicaLocation,
117};
118use mz_controller::{ControllerConfig, Readiness};
119use mz_controller_types::{ClusterId, ReplicaId, WatchSetId};
120use mz_dyncfg::{ConfigUpdates, ParameterScope};
121use mz_expr::{MirRelationExpr, OptimizedMirRelationExpr};
122use mz_license_keys::{ExpirationBehavior, ValidatedLicenseKey};
123use mz_orchestrator::OfflineReason;
124use mz_ore::cast::{CastFrom, CastInto, CastLossy};
125use mz_ore::channel::trigger::Trigger;
126use mz_ore::future::TimeoutError;
127use mz_ore::metrics::MetricsRegistry;
128use mz_ore::now::{EpochMillis, NowFn};
129use mz_ore::task::{AbortOnDropHandle, JoinHandle, spawn};
130use mz_ore::thread::JoinHandleExt;
131use mz_ore::tracing::{OpenTelemetryContext, TracingHandle};
132use mz_ore::url::SensitiveUrl;
133use mz_ore::{
134 assert_none, instrument, soft_assert_eq_or_log, soft_assert_or_log, soft_panic_or_log, stack,
135};
136use mz_persist_client::PersistClient;
137use mz_persist_client::batch::ProtoBatch;
138use mz_persist_client::usage::{ShardsUsageReferenced, StorageUsageClient};
139use mz_repr::adt::numeric::Numeric;
140use mz_repr::explain::{ExplainConfig, ExplainFormat};
141use mz_repr::global_id::TransientIdGen;
142use mz_repr::optimize::{OptimizerFeatureOverrides, OptimizerFeatures, OverrideFrom};
143use mz_repr::role_id::RoleId;
144use mz_repr::{
145 CatalogItemId, Diff, GlobalId, RelationDesc, RelationVersion, SqlRelationType, Timestamp,
146};
147use mz_secrets::cache::CachingSecretsReader;
148use mz_secrets::{SecretsController, SecretsReader};
149use mz_sql::ast::{Raw, Statement};
150use mz_sql::catalog::{CatalogCluster, EnvironmentId};
151use mz_sql::names::{QualifiedItemName, ResolvedIds};
152use mz_sql::optimizer_metrics::OptimizerMetrics;
153use mz_sql::plan::{
154 self, AlterSinkPlan, ConnectionDetails, HirRelationExpr, NetworkPolicyRule, Params,
155};
156use mz_sql::session::metadata::SessionMetadata;
157use mz_sql::session::user::User;
158use mz_sql::session::vars::{MAX_CREDIT_CONSUMPTION_RATE, SystemVars, Var};
159use mz_sql_parser::ast::ExplainStage;
160use mz_sql_parser::ast::display::AstDisplay;
161use mz_storage_client::client::TableData;
162use mz_storage_client::controller::{CollectionDescription, DataSource, ExportDescription};
163use mz_storage_types::connections::Connection as StorageConnection;
164use mz_storage_types::connections::ConnectionContext;
165use mz_storage_types::connections::inline::{IntoInlineConnection, ReferencedConnection};
166use mz_storage_types::read_holds::ReadHold;
167use mz_storage_types::sinks::{S3SinkFormat, StorageSinkDesc};
168use mz_storage_types::sources::kafka::KAFKA_PROGRESS_DESC;
169use mz_storage_types::sources::{IngestionDescription, SourceExport, Timeline};
170use mz_timestamp_oracle::{TimestampOracleConfig, WriteTimestamp};
171use mz_transform::dataflow::DataflowMetainfo;
172use opentelemetry::trace::TraceContextExt;
173use semver::Version;
174use serde::Serialize;
175use thiserror::Error;
176use timely::progress::{Antichain, Timestamp as _};
177use tokio::runtime::Handle as TokioHandle;
178use tokio::select;
179use tokio::sync::{Notify, OwnedMutexGuard, Semaphore, mpsc, oneshot, watch};
180use tokio::time::Interval;
181use tracing::{Instrument, Level, Span, debug, info, info_span, span, warn};
182use tracing_opentelemetry::OpenTelemetrySpanExt;
183use uuid::Uuid;
184
185use crate::active_compute_sink::{ActiveComputeSink, ActiveCopyFrom};
186use crate::catalog::consistency::CheckedCreateSql;
187use crate::catalog::{BuiltinTableUpdate, Catalog, OpenCatalogResult};
188use crate::client::{Client, Handle, truncate_sql_for_logging};
189use crate::command::{Command, ExecuteResponse};
190use crate::config::{
191 ClusterEvalContext, ClusterScopeContext, ReplicaEvalContext, ReplicaScopeContext,
192 ScopedParameters, ScopedParametersScope, SynchronizedParameters, SystemParameterFrontend,
193 SystemParameterSyncConfig,
194};
195use crate::coord::appends::{
196 BuiltinTableAppendCompletion, BuiltinTableAppendNotify, GroupCommitPermit, PendingWriteTxn,
197};
198use crate::coord::caught_up::CaughtUpCheckContext;
199use crate::coord::id_bundle::CollectionIdBundle;
200use crate::coord::introspection::IntrospectionSubscribe;
201use crate::coord::metric_sink::{CuratedMetricSink, InstalledMetricSink, PlannedMetricSink};
202use crate::coord::statement_logging::StatementLogging;
203use crate::coord::timeline::TimelineState;
204use crate::coord::timestamp_selection::TimestampContext;
205use crate::coord::validity::PlanValidity;
206use crate::error::AdapterError;
207use crate::explain::optimizer_trace::{DispatchGuard, OptimizerTrace};
208use crate::metrics::Metrics;
209use crate::optimize::dataflows::{ComputeInstanceSnapshot, DataflowBuilder};
210use crate::optimize::{self, Optimize, OptimizerConfig};
211use crate::session::{EndTransactionAction, Session};
212use crate::statement_logging::{
213 StatementEndedExecutionReason, StatementLifecycleEvent, StatementLoggingId,
214};
215use crate::util::{ClientTransmitter, ResultExt, sort_topological};
216use crate::webhook::{WebhookAppenderInvalidator, WebhookConcurrencyLimiter};
217use crate::{AdapterNotice, ReadHolds, flags};
218
219pub(crate) mod appends;
220pub(crate) mod catalog_serving;
221pub(crate) mod cluster_controller;
222pub(crate) mod consistency;
223pub(crate) mod id_bundle;
224pub(crate) mod in_memory_oracle;
225pub(crate) mod peek;
226pub(crate) mod read_policy;
227pub(crate) mod read_then_write;
228pub(crate) mod sequencer;
229pub(crate) mod statement_logging;
230pub(crate) mod timeline;
231pub(crate) mod timestamp_selection;
232
233pub mod catalog_implications;
234mod caught_up;
235mod command_handler;
236mod ddl;
237pub(crate) mod group_sync;
238mod hydration_history;
239mod indexes;
240mod info_metrics;
241mod introspection;
242mod message_handler;
243mod metric_sink;
244mod privatelink_status;
245mod sql;
246mod validity;
247
248fn box_dispatcher<'a, F>(future: F) -> LocalBoxFuture<'a, ()>
250where
251 F: std::future::Future<Output = ()> + 'a,
252{
253 const {
257 assert!(
258 size_of::<F>() <= 24 * 1024,
259 "coordinator dispatcher future exceeds 24 KiB: box large awaited callees"
260 );
261 }
262 future.boxed_local()
263}
264
265const MIN_LEADER_VERSION_FOR_MIGRATED_MV_WRITES: Version = Version::new(26, 17, 0);
275
276#[derive(Debug)]
302pub(crate) struct IdPool {
303 next: u64,
304 upper: u64,
305}
306
307impl IdPool {
308 pub fn empty() -> Self {
310 IdPool { next: 0, upper: 0 }
311 }
312
313 pub fn allocate(&mut self) -> Option<u64> {
315 if self.next < self.upper {
316 let id = self.next;
317 self.next += 1;
318 Some(id)
319 } else {
320 None
321 }
322 }
323
324 pub fn allocate_many(&mut self, n: u64) -> Option<Vec<u64>> {
327 if self.remaining() >= n {
328 let ids = (self.next..self.next + n).collect();
329 self.next += n;
330 Some(ids)
331 } else {
332 None
333 }
334 }
335
336 pub fn remaining(&self) -> u64 {
338 self.upper - self.next
339 }
340
341 pub fn refill(&mut self, next: u64, upper: u64) {
343 assert!(next <= upper, "invalid pool range: {next}..{upper}");
344 self.next = next;
345 self.upper = upper;
346 }
347}
348
349#[derive(Debug)]
353pub struct ArrangementSizeRecord {
354 pub replica_id: String,
355 pub object_id: String,
356 pub size: i64,
357 pub hydration_complete: bool,
358}
359
360#[derive(Debug)]
361pub enum Message {
362 Command(OpenTelemetryContext, Command),
363 ControllerReady {
364 controller: ControllerReadiness,
365 },
366 PurifiedStatementReady(PurifiedStatementReady),
367 SourceStatementReady {
368 pending: ddl::PendingSourceStatement,
369 response: mz_sql::pure::SourcePreparationResponse,
370 otel_ctx: OpenTelemetryContext,
371 },
372 DdlCommandsReady {
373 pending: ddl::PendingDdlCommit,
374 otel_ctx: OpenTelemetryContext,
375 },
376 GroupCommitInitiate(Span, Option<GroupCommitPermit>),
378 GroupCommitApplied {
382 responses: Vec<crate::util::CompletedClientTransmitter>,
384 statement_logging_ids: Vec<StatementLoggingId>,
386 internal_results: Vec<crate::coord::appends::InternalWriteResponder>,
388 write_ts: Timestamp,
390 },
391 DeferredStatementReady,
392 AdvanceTimelines,
393 ClusterEvent(ClusterEvent),
394 LinearizeReads,
395 StagedBatches {
396 conn_id: ConnectionId,
397 table_id: CatalogItemId,
398 batches: Vec<Result<ProtoBatch, String>>,
399 },
400 StorageUsageSchedule,
401 StorageUsageFetch,
402 StorageUsageUpdate(ShardsUsageReferenced),
403 StorageUsagePrune(Vec<BuiltinTableUpdate>),
404 ArrangementSizesSchedule,
405 ArrangementSizesSnapshot,
406 ArrangementSizesWrite {
407 records: Vec<ArrangementSizeRecord>,
408 collection_ts: EpochMillis,
409 },
410 ArrangementSizesPrune(Vec<BuiltinTableUpdate>),
411 HydrationHistorySchedule,
412 HydrationHistoryRun,
413 CaughtUpCheck(caught_up::CaughtUpCheckRequest),
414 RetireExecute {
417 data: ExecuteContextExtra,
418 otel_ctx: OpenTelemetryContext,
419 reason: StatementEndedExecutionReason,
420 },
421 ExecuteSingleStatementTransaction {
422 ctx: ExecuteContext,
423 otel_ctx: OpenTelemetryContext,
424 stmt: Arc<Statement<Raw>>,
425 params: mz_sql::plan::Params,
426 },
427 CreateIndexStageReady {
428 ctx: ExecuteContext,
429 span: Span,
430 stage: CreateIndexStage,
431 },
432 CreateMetricSinkStageReady {
433 ctx: ExecuteContext,
434 span: Span,
435 stage: CreateMetricSinkStage,
436 },
437 CreateViewStageReady {
438 ctx: ExecuteContext,
439 span: Span,
440 stage: CreateViewStage,
441 },
442 CreateMaterializedViewStageReady {
443 ctx: ExecuteContext,
444 span: Span,
445 stage: CreateMaterializedViewStage,
446 },
447 IntrospectionSubscribeStageReady {
448 span: Span,
449 stage: IntrospectionSubscribeStage,
450 },
451 MetricSinkStageReady {
452 span: Span,
453 stage: MetricSinkStage,
454 },
455 SecretStageReady {
456 ctx: ExecuteContext,
457 span: Span,
458 stage: SecretStage,
459 },
460 ClusterStageReady {
461 ctx: ExecuteContext,
462 span: Span,
463 stage: ClusterStage,
464 },
465 DrainStatementLog,
466 PrivateLinkVpcEndpointEvents(Vec<VpcEndpointEvent>),
467
468 ClusterControllerRequest(cluster_controller::ClusterControllerRequest),
472}
473
474impl Message {
475 pub const fn kind(&self) -> &'static str {
477 match self {
478 Message::Command(_, msg) => match msg {
479 Command::CatalogSnapshot { .. } => "command-catalog_snapshot",
480 Command::Startup { .. } => "command-startup",
481 Command::Execute { .. } => "command-execute",
482 Command::Commit { .. } => "command-commit",
483 Command::CancelRequest { .. } => "command-cancel_request",
484 Command::PrivilegedCancelRequest { .. } => "command-privileged_cancel_request",
485 Command::GetWebhook { .. } => "command-get_webhook",
486 Command::GetSystemVars { .. } => "command-get_system_vars",
487 Command::SetSystemVars { .. } => "command-set_system_vars",
488 Command::UpdateScopedSystemParameters { .. } => {
489 "command-update_scoped_system_parameters"
490 }
491 Command::InstallScopedSystemParameterFrontend { .. } => {
492 "command-install_scoped_system_parameter_frontend"
493 }
494 Command::Terminate { .. } => "command-terminate",
495 Command::RetireExecute { .. } => "command-retire_execute",
496 Command::CheckConsistency { .. } => "command-check_consistency",
497 Command::Dump { .. } => "command-dump",
498 Command::AuthenticatePassword { .. } => "command-auth_check",
499 Command::AuthenticateGetSASLChallenge { .. } => "command-auth_get_sasl_challenge",
500 Command::AuthenticateVerifySASLProof { .. } => "command-auth_verify_sasl_proof",
501 Command::CheckRoleCanLogin { .. } => "command-check_role_can_login",
502 Command::GetComputeInstanceClient { .. } => "get-compute-instance-client",
503 Command::GetOracle { .. } => "get-oracle",
504 Command::DetermineRealTimeRecentTimestamp { .. } => {
505 "determine-real-time-recent-timestamp"
506 }
507 Command::GetTransactionReadHoldsBundle { .. } => {
508 "get-transaction-read-holds-bundle"
509 }
510 Command::StoreTransactionReadHolds { .. } => "store-transaction-read-holds",
511 Command::ExecuteSlowPathPeek { .. } => "execute-slow-path-peek",
512 Command::ExecuteSubscribe { .. } => "execute-subscribe",
513 Command::CopyToPreflight { .. } => "copy-to-preflight",
514 Command::ExecuteCopyTo { .. } => "execute-copy-to",
515 Command::ExecuteSideEffectingFunc { .. } => "execute-side-effecting-func",
516 Command::LookupConnection { .. } => "lookup-connection",
517 Command::InstallPeekWatchSets { .. } => "install-peek-watch-sets",
518 Command::ExplainTimestamp { .. } => "explain-timestamp",
519 Command::StartCopyFromStdin { .. } => "start-copy-from-stdin",
520 Command::InjectAuditEvents { .. } => "inject-audit-events",
521 Command::RegisterConnectionCancelWatch { .. } => "register-connection-cancel-watch",
522 Command::CreateInternalSubscribe { .. } => "create-internal-subscribe",
523 Command::AttemptWrite { .. } => "attempt-write",
524 Command::DropInternalSubscribe { .. } => "drop-internal-subscribe",
525 },
526 Message::ControllerReady {
527 controller: ControllerReadiness::Compute,
528 } => "controller_ready(compute)",
529 Message::ControllerReady {
530 controller: ControllerReadiness::Storage,
531 } => "controller_ready(storage)",
532 Message::ControllerReady {
533 controller: ControllerReadiness::Metrics,
534 } => "controller_ready(metrics)",
535 Message::ControllerReady {
536 controller: ControllerReadiness::Internal,
537 } => "controller_ready(internal)",
538 Message::PurifiedStatementReady(_) => "purified_statement_ready",
539 Message::SourceStatementReady { .. } => "source_statement_ready",
540 Message::DdlCommandsReady { .. } => "ddl_commands_ready",
541 Message::GroupCommitInitiate(..) => "group_commit_initiate",
542 Message::GroupCommitApplied { .. } => "group_commit_applied",
543 Message::AdvanceTimelines => "advance_timelines",
544 Message::ClusterEvent(_) => "cluster_event",
545 Message::LinearizeReads => "linearize_reads",
546 Message::StagedBatches { .. } => "staged_batches",
547 Message::StorageUsageSchedule => "storage_usage_schedule",
548 Message::StorageUsageFetch => "storage_usage_fetch",
549 Message::StorageUsageUpdate(_) => "storage_usage_update",
550 Message::StorageUsagePrune(_) => "storage_usage_prune",
551 Message::ArrangementSizesSchedule => "arrangement_sizes_schedule",
552 Message::ArrangementSizesSnapshot => "arrangement_sizes_snapshot",
553 Message::ArrangementSizesWrite { .. } => "arrangement_sizes_write",
554 Message::ArrangementSizesPrune(_) => "arrangement_sizes_prune",
555 Message::HydrationHistorySchedule => "hydration_history_schedule",
556 Message::HydrationHistoryRun => "hydration_history_run",
557 Message::CaughtUpCheck(_) => "caught_up_check",
558 Message::RetireExecute { .. } => "retire_execute",
559 Message::ExecuteSingleStatementTransaction { .. } => {
560 "execute_single_statement_transaction"
561 }
562 Message::CreateIndexStageReady { .. } => "create_index_stage_ready",
563 Message::CreateMetricSinkStageReady { .. } => "create_metric_sink_stage_ready",
564 Message::CreateViewStageReady { .. } => "create_view_stage_ready",
565 Message::CreateMaterializedViewStageReady { .. } => {
566 "create_materialized_view_stage_ready"
567 }
568 Message::IntrospectionSubscribeStageReady { .. } => {
569 "introspection_subscribe_stage_ready"
570 }
571 Message::MetricSinkStageReady { .. } => "metric_sink_stage_ready",
572 Message::SecretStageReady { .. } => "secret_stage_ready",
573 Message::ClusterStageReady { .. } => "cluster_stage_ready",
574 Message::DrainStatementLog => "drain_statement_log",
575 Message::PrivateLinkVpcEndpointEvents(_) => "private_link_vpc_endpoint_events",
576 Message::ClusterControllerRequest(_) => "cluster_controller_request",
577 Message::DeferredStatementReady => "deferred_statement_ready",
578 }
579 }
580}
581
582#[derive(Debug)]
584pub enum ControllerReadiness {
585 Storage,
587 Compute,
589 Metrics,
591 Internal,
593}
594
595#[derive(Derivative)]
596#[derivative(Debug)]
597pub struct BackgroundWorkResult<T> {
598 #[derivative(Debug = "ignore")]
599 pub ctx: ExecuteContext,
600 pub result: Result<T, AdapterError>,
601 pub params: Params,
602 pub plan_validity: PlanValidity,
603 pub original_stmt: Arc<Statement<Raw>>,
604 pub otel_ctx: OpenTelemetryContext,
605}
606
607pub type PurifiedStatementReady = BackgroundWorkResult<mz_sql::pure::PurifiedStatement>;
608
609#[derive(Debug)]
610pub struct CopyToContext {
611 pub desc: RelationDesc,
613 pub uri: Uri,
615 pub connection: StorageConnection<ReferencedConnection>,
617 pub connection_id: CatalogItemId,
619 pub format: S3SinkFormat,
621 pub max_file_size: u64,
623 pub output_batch_count: Option<u64>,
628}
629
630#[derive(Debug)]
631pub enum CreateIndexStage {
632 Optimize(CreateIndexOptimize),
633 Finish(CreateIndexFinish),
634 Explain(CreateIndexExplain),
635}
636
637#[derive(Debug)]
638pub struct CreateIndexOptimize {
639 validity: PlanValidity,
640 plan: plan::CreateIndexPlan,
641 resolved_ids: ResolvedIds,
642 explain_ctx: ExplainContext,
645}
646
647#[derive(Debug)]
648pub struct CreateIndexFinish {
649 validity: PlanValidity,
650 item_id: CatalogItemId,
651 global_id: GlobalId,
652 plan: plan::CreateIndexPlan,
653 resolved_ids: ResolvedIds,
654 global_mir_plan: optimize::index::GlobalMirPlan,
655 global_lir_plan: optimize::index::GlobalLirPlan,
656 optimizer_features: OptimizerFeatures,
657}
658
659#[derive(Debug)]
660pub struct CreateIndexExplain {
661 validity: PlanValidity,
662 exported_index_id: GlobalId,
663 plan: plan::CreateIndexPlan,
664 df_meta: DataflowMetainfo,
665 explain_ctx: ExplainPlanContext,
666}
667
668#[derive(Debug)]
669pub enum CreateMetricSinkStage {
670 Optimize(CreateMetricSinkOptimize),
671 Finish(CreateMetricSinkFinish),
672}
673
674#[derive(Debug)]
675pub struct CreateMetricSinkOptimize {
676 validity: PlanValidity,
677 plan: plan::CreateMetricSinkPlan,
678 resolved_ids: ResolvedIds,
679}
680
681#[derive(Debug)]
682pub struct CreateMetricSinkFinish {
683 validity: PlanValidity,
684 item_id: CatalogItemId,
685 global_id: GlobalId,
686 plan: plan::CreateMetricSinkPlan,
687 resolved_ids: ResolvedIds,
688 global_mir_plan: optimize::metric_sink::GlobalMirPlan,
689 global_lir_plan: optimize::metric_sink::GlobalLirPlan,
690 optimizer_features: OptimizerFeatures,
691}
692
693#[derive(Debug)]
694pub enum CreateViewStage {
695 Optimize(CreateViewOptimize),
696 Finish(CreateViewFinish),
697 Explain(CreateViewExplain),
698}
699
700#[derive(Debug)]
701pub struct CreateViewOptimize {
702 validity: PlanValidity,
703 plan: plan::CreateViewPlan,
704 resolved_ids: ResolvedIds,
705 explain_ctx: ExplainContext,
708}
709
710#[derive(Debug)]
711pub struct CreateViewFinish {
712 validity: PlanValidity,
713 item_id: CatalogItemId,
715 global_id: GlobalId,
717 plan: plan::CreateViewPlan,
718 resolved_ids: ResolvedIds,
720 optimized_expr: OptimizedMirRelationExpr,
721 optimizer_features: OptimizerFeatures,
722}
723
724#[derive(Debug)]
725pub struct CreateViewExplain {
726 validity: PlanValidity,
727 id: GlobalId,
728 plan: plan::CreateViewPlan,
729 explain_ctx: ExplainPlanContext,
730}
731
732#[derive(Debug)]
733pub enum ClusterStage {
734 Alter(AlterCluster),
735 AwaitReconfiguration(AlterClusterAwaitReconfiguration),
740}
741
742#[derive(Debug)]
743pub struct AlterCluster {
744 validity: PlanValidity,
745 plan: plan::AlterClusterPlan,
746}
747
748#[derive(Debug)]
749pub struct AlterClusterAwaitReconfiguration {
750 validity: PlanValidity,
751 cluster_id: ClusterId,
752 target: ReconfigurationTarget,
756}
757
758#[derive(Debug)]
759pub enum ExplainContext {
760 None,
762 Plan(ExplainPlanContext),
764 PlanInsightsNotice(OptimizerTrace),
767 Pushdown,
769 Timestamp,
772}
773
774impl ExplainContext {
775 pub(crate) fn dispatch_guard(&self) -> Option<DispatchGuard<'_>> {
779 let optimizer_trace = match self {
780 ExplainContext::Plan(explain_ctx) => Some(&explain_ctx.optimizer_trace),
781 ExplainContext::PlanInsightsNotice(optimizer_trace) => Some(optimizer_trace),
782 ExplainContext::None | ExplainContext::Pushdown | ExplainContext::Timestamp => None,
783 };
784 optimizer_trace.map(|optimizer_trace| optimizer_trace.as_guard())
785 }
786
787 pub(crate) fn needs_cluster(&self) -> bool {
788 match self {
789 ExplainContext::None => true,
790 ExplainContext::Plan(..) => false,
791 ExplainContext::PlanInsightsNotice(..) => true,
792 ExplainContext::Pushdown => false,
793 ExplainContext::Timestamp => false,
794 }
795 }
796
797 pub(crate) fn checks_log_reads(&self) -> bool {
800 match self {
801 ExplainContext::None
802 | ExplainContext::Plan(..)
803 | ExplainContext::PlanInsightsNotice(..)
804 | ExplainContext::Pushdown => true,
805 ExplainContext::Timestamp => false,
807 }
808 }
809
810 pub(crate) fn needs_plan_insights(&self) -> bool {
811 matches!(
812 self,
813 ExplainContext::Plan(ExplainPlanContext {
814 stage: ExplainStage::PlanInsights,
815 ..
816 }) | ExplainContext::PlanInsightsNotice(_)
817 )
818 }
819}
820
821#[derive(Debug)]
822pub struct ExplainPlanContext {
823 pub broken: bool,
828 pub config: ExplainConfig,
829 pub format: ExplainFormat,
830 pub stage: ExplainStage,
831 pub replan: Option<GlobalId>,
832 pub desc: Option<RelationDesc>,
833 pub optimizer_trace: OptimizerTrace,
834}
835
836#[derive(Debug)]
837pub enum CreateMaterializedViewStage {
838 Optimize(CreateMaterializedViewOptimize),
839 Finish(CreateMaterializedViewFinish),
840 Explain(CreateMaterializedViewExplain),
841}
842
843#[derive(Debug)]
844pub struct CreateMaterializedViewOptimize {
845 validity: PlanValidity,
846 plan: plan::CreateMaterializedViewPlan,
847 resolved_ids: ResolvedIds,
848 explain_ctx: ExplainContext,
851}
852
853#[derive(Debug)]
854pub struct CreateMaterializedViewFinish {
855 item_id: CatalogItemId,
857 global_id: GlobalId,
859 validity: PlanValidity,
860 plan: plan::CreateMaterializedViewPlan,
861 resolved_ids: ResolvedIds,
862 local_mir_plan: optimize::materialized_view::LocalMirPlan,
863 global_mir_plan: optimize::materialized_view::GlobalMirPlan,
864 global_lir_plan: optimize::materialized_view::GlobalLirPlan,
865 optimizer_features: OptimizerFeatures,
866}
867
868#[derive(Debug)]
869pub struct CreateMaterializedViewExplain {
870 global_id: GlobalId,
871 validity: PlanValidity,
872 plan: plan::CreateMaterializedViewPlan,
873 df_meta: DataflowMetainfo,
874 explain_ctx: ExplainPlanContext,
875}
876
877#[derive(Debug)]
878pub enum IntrospectionSubscribeStage {
879 OptimizeMir(IntrospectionSubscribeOptimizeMir),
880 TimestampOptimizeLir(IntrospectionSubscribeTimestampOptimizeLir),
881 Finish(IntrospectionSubscribeFinish),
882}
883
884#[derive(Debug)]
885pub struct IntrospectionSubscribeOptimizeMir {
886 validity: PlanValidity,
887 plan: plan::SubscribePlan,
888 subscribe_id: GlobalId,
889 cluster_id: ComputeInstanceId,
890 replica_id: ReplicaId,
891}
892
893#[derive(Debug)]
894pub struct IntrospectionSubscribeTimestampOptimizeLir {
895 validity: PlanValidity,
896 optimizer: optimize::subscribe::Optimizer,
897 global_mir_plan: optimize::subscribe::GlobalMirPlan<optimize::subscribe::Unresolved>,
898 cluster_id: ComputeInstanceId,
899 replica_id: ReplicaId,
900}
901
902#[derive(Debug)]
903pub struct IntrospectionSubscribeFinish {
904 validity: PlanValidity,
905 global_lir_plan: optimize::subscribe::GlobalLirPlan,
906 read_holds: ReadHolds,
907 cluster_id: ComputeInstanceId,
908 replica_id: ReplicaId,
909}
910
911#[derive(Debug)]
912pub enum MetricSinkStage {
913 Optimize(MetricSinkOptimize),
914 Finish(MetricSinkFinish),
915}
916
917#[derive(Debug)]
918pub struct MetricSinkOptimize {
919 validity: PlanValidity,
920 definition: &'static CuratedMetricSink,
921 sink_id: GlobalId,
924 expr: HirRelationExpr,
926 desc: RelationDesc,
927 cluster_id: ComputeInstanceId,
928 replica_id: ReplicaId,
929}
930
931#[derive(Debug)]
932pub struct MetricSinkFinish {
933 validity: PlanValidity,
934 definition: &'static CuratedMetricSink,
935 sink_id: GlobalId,
936 global_lir_plan: optimize::metric_sink::GlobalLirPlan,
937 cluster_id: ComputeInstanceId,
938 replica_id: ReplicaId,
939}
940
941#[derive(Debug)]
942pub enum SecretStage {
943 CreateEnsure(CreateSecretEnsure),
944 CreateFinish(CreateSecretFinish),
945 RotateKeysEnsure(RotateKeysSecretEnsure),
946 RotateKeysFinish(RotateKeysSecretFinish),
947 Alter(AlterSecret),
948}
949
950#[derive(Debug)]
951pub struct CreateSecretEnsure {
952 validity: PlanValidity,
953 plan: plan::CreateSecretPlan,
954}
955
956#[derive(Debug)]
957pub struct CreateSecretFinish {
958 validity: PlanValidity,
959 item_id: CatalogItemId,
960 global_id: GlobalId,
961 plan: plan::CreateSecretPlan,
962}
963
964#[derive(Debug)]
965pub struct RotateKeysSecretEnsure {
966 validity: PlanValidity,
967 id: CatalogItemId,
968}
969
970#[derive(Debug)]
971pub struct RotateKeysSecretFinish {
972 validity: PlanValidity,
973 ops: Vec<crate::catalog::Op>,
974}
975
976#[derive(Debug)]
977pub struct AlterSecret {
978 validity: PlanValidity,
979 plan: plan::AlterSecretPlan,
980}
981
982#[derive(Debug, Copy, Clone, PartialEq, Eq)]
987pub enum TargetCluster {
988 CatalogServer,
990 Active,
992 Transaction(ClusterId),
994}
995
996pub(crate) enum StageResult<T> {
998 Handle(JoinHandle<Result<T, AdapterError>>),
1000 HandleRetire(JoinHandle<Result<ExecuteResponse, AdapterError>>),
1002 Immediate(T),
1004 Response(ExecuteResponse),
1006}
1007
1008pub(crate) trait Staged: Send {
1010 type Ctx: StagedContext;
1011
1012 fn validity(&mut self) -> &mut PlanValidity;
1013
1014 async fn stage(
1016 self,
1017 coord: &mut Coordinator,
1018 ctx: &mut Self::Ctx,
1019 ) -> Result<StageResult<Box<Self>>, AdapterError>;
1020
1021 fn message(self, ctx: Self::Ctx, span: Span) -> Message;
1023
1024 fn cancel_enabled(&self) -> bool;
1026}
1027
1028pub trait StagedContext {
1029 fn retire(self, result: Result<ExecuteResponse, AdapterError>);
1030 fn session(&self) -> Option<&Session>;
1031}
1032
1033impl StagedContext for ExecuteContext {
1034 fn retire(self, result: Result<ExecuteResponse, AdapterError>) {
1035 self.retire(result);
1036 }
1037
1038 fn session(&self) -> Option<&Session> {
1039 Some(self.session())
1040 }
1041}
1042
1043impl StagedContext for () {
1044 fn retire(self, _result: Result<ExecuteResponse, AdapterError>) {}
1045
1046 fn session(&self) -> Option<&Session> {
1047 None
1048 }
1049}
1050
1051pub struct Config {
1053 pub controller_config: ControllerConfig,
1054 pub controller_envd_epoch: NonZeroI64,
1055 pub storage: Box<dyn mz_catalog::durable::DurableCatalogState>,
1056 pub timestamp_oracle_url: Option<SensitiveUrl>,
1057 pub unsafe_mode: bool,
1058 pub all_features: bool,
1059 pub build_info: &'static BuildInfo,
1060 pub environment_id: EnvironmentId,
1061 pub metrics_registry: MetricsRegistry,
1062 pub now: NowFn,
1063 pub secrets_controller: Arc<dyn SecretsController>,
1064 pub cloud_resource_controller: Option<Arc<dyn CloudResourceController>>,
1065 pub availability_zones: Vec<String>,
1066 pub cluster_replica_sizes: ClusterReplicaSizeMap,
1067 pub builtin_system_cluster_config: BootstrapBuiltinClusterConfig,
1068 pub builtin_catalog_server_cluster_config: BootstrapBuiltinClusterConfig,
1069 pub builtin_probe_cluster_config: BootstrapBuiltinClusterConfig,
1070 pub builtin_support_cluster_config: BootstrapBuiltinClusterConfig,
1071 pub builtin_analytics_cluster_config: BootstrapBuiltinClusterConfig,
1072 pub system_parameter_defaults: BTreeMap<String, String>,
1073 pub storage_usage_client: StorageUsageClient,
1074 pub storage_usage_collection_interval: Duration,
1075 pub storage_usage_retention_period: Option<Duration>,
1076 pub segment_client: Option<mz_segment::Client>,
1077 pub egress_addresses: Vec<IpNet>,
1078 pub remote_system_parameters: Option<BTreeMap<String, String>>,
1079 pub aws_account_id: Option<String>,
1080 pub aws_privatelink_availability_zones: Option<Vec<String>>,
1081 pub connection_context: ConnectionContext,
1082 pub connection_limit_callback: Box<dyn Fn(u64, u64) -> () + Send + Sync + 'static>,
1083 pub webhook_concurrency_limit: WebhookConcurrencyLimiter,
1084 pub http_host_name: Option<String>,
1085 pub tracing_handle: TracingHandle,
1086 pub read_only_controllers: bool,
1090
1091 pub caught_up_trigger: Option<Trigger>,
1095
1096 pub helm_chart_version: Option<String>,
1097 pub license_key: ValidatedLicenseKey,
1098 pub external_login_password_mz_system: Option<Password>,
1099 pub force_builtin_schema_migration: Option<String>,
1100}
1101
1102#[derive(Debug, Serialize)]
1104pub struct ConnMeta {
1105 #[serde(skip)]
1107 frontend_cancel_tx: watch::Sender<()>,
1108 secret_key: u32,
1113 connected_at: EpochMillis,
1115 user: User,
1116 application_name: String,
1117 uuid: Uuid,
1118 conn_id: ConnectionId,
1119 client_ip: Option<IpAddr>,
1120
1121 drop_sinks: BTreeSet<GlobalId>,
1124
1125 #[serde(skip)]
1127 deferred_lock: Option<OwnedMutexGuard<()>>,
1128
1129 #[serde(skip)]
1131 notice_tx: mpsc::UnboundedSender<AdapterNotice>,
1132
1133 authenticated_role: RoleId,
1137}
1138
1139impl ConnMeta {
1140 pub fn conn_id(&self) -> &ConnectionId {
1141 &self.conn_id
1142 }
1143
1144 pub fn user(&self) -> &User {
1145 &self.user
1146 }
1147
1148 pub fn application_name(&self) -> &str {
1149 &self.application_name
1150 }
1151
1152 pub fn authenticated_role_id(&self) -> &RoleId {
1153 &self.authenticated_role
1154 }
1155
1156 pub fn uuid(&self) -> Uuid {
1157 self.uuid
1158 }
1159
1160 pub fn client_ip(&self) -> Option<IpAddr> {
1161 self.client_ip
1162 }
1163
1164 pub fn connected_at(&self) -> EpochMillis {
1165 self.connected_at
1166 }
1167}
1168
1169#[derive(Debug)]
1170pub struct PendingTxn {
1172 ctx: ExecuteContext,
1174 response: Result<PendingTxnResponse, AdapterError>,
1176 action: EndTransactionAction,
1178}
1179
1180impl PendingTxn {
1181 fn finish(self) {
1182 let PendingTxn {
1183 mut ctx,
1184 response,
1185 action,
1186 } = self;
1187 let changed = ctx.session_mut().vars_mut().end_transaction(action);
1188 let response = response.map(|mut r| {
1189 r.extend_params(changed);
1190 ExecuteResponse::from(r)
1191 });
1192 ctx.retire(response);
1193 }
1194}
1195
1196#[derive(Debug)]
1197pub enum PendingTxnResponse {
1199 Committed {
1201 params: BTreeMap<&'static str, String>,
1203 },
1204 Rolledback {
1206 params: BTreeMap<&'static str, String>,
1208 },
1209}
1210
1211impl PendingTxnResponse {
1212 pub fn extend_params(&mut self, p: impl IntoIterator<Item = (&'static str, String)>) {
1213 match self {
1214 PendingTxnResponse::Committed { params }
1215 | PendingTxnResponse::Rolledback { params } => params.extend(p),
1216 }
1217 }
1218}
1219
1220impl From<PendingTxnResponse> for ExecuteResponse {
1221 fn from(value: PendingTxnResponse) -> Self {
1222 match value {
1223 PendingTxnResponse::Committed { params } => {
1224 ExecuteResponse::TransactionCommitted { params }
1225 }
1226 PendingTxnResponse::Rolledback { params } => {
1227 ExecuteResponse::TransactionRolledBack { params }
1228 }
1229 }
1230 }
1231}
1232
1233#[derive(Debug)]
1234pub struct PendingReadTxn {
1236 txn: PendingTxn,
1237 timestamp_context: TimestampContext,
1239 created: Instant,
1241 num_requeues: u64,
1245 otel_ctx: OpenTelemetryContext,
1247}
1248
1249impl PendingReadTxn {
1250 fn timestamp_to_linearize(&self) -> Option<(&Timeline, &Timestamp)> {
1252 self.timestamp_context.timestamp_to_linearize()
1253 }
1254
1255 fn linearized_by(&self, timeline: &Timeline, applied_ts: &Timestamp) -> bool {
1257 match self.timestamp_to_linearize() {
1258 None => true,
1259 Some((read_timeline, chosen_ts)) => {
1260 read_timeline == timeline && chosen_ts <= applied_ts
1261 }
1262 }
1263 }
1264
1265 fn try_finish_read(self, metrics: &Metrics) -> Option<Self> {
1267 if self.timestamp_to_linearize().is_some() {
1268 return Some(self);
1269 }
1270 metrics.linearize_read_fast_path.inc();
1271 self.finish_with_metrics(metrics, Instant::now());
1272 None
1273 }
1274
1275 fn finish_with_metrics(self, metrics: &Metrics, now: Instant) {
1277 let span = tracing::debug_span!("retire_read_results");
1278 self.otel_ctx.attach_as_parent_to(&span);
1279 let _entered = span.enter();
1280 metrics
1281 .linearize_message_seconds
1282 .with_label_values(&[
1283 "read",
1284 if self.num_requeues == 0 {
1285 "true"
1286 } else {
1287 "false"
1288 },
1289 ])
1290 .observe((now - self.created).as_secs_f64());
1291 self.finish();
1292 }
1293
1294 pub(crate) fn take_context(self) -> ExecuteContext {
1295 self.txn.ctx
1296 }
1297
1298 #[instrument(level = "debug")]
1300 pub fn finish(self) {
1301 self.txn.finish();
1302 }
1303}
1304
1305#[derive(Debug, Default)]
1315#[must_use]
1316pub struct ExecuteContextExtra {
1317 statement_uuid: Option<StatementLoggingId>,
1318}
1319
1320impl ExecuteContextExtra {
1321 pub(crate) fn new(statement_uuid: Option<StatementLoggingId>) -> Self {
1322 Self { statement_uuid }
1323 }
1324 pub fn is_trivial(&self) -> bool {
1325 self.statement_uuid.is_none()
1326 }
1327 pub fn contents(&self) -> Option<StatementLoggingId> {
1328 self.statement_uuid
1329 }
1330 #[must_use]
1334 pub(crate) fn retire(self) -> Option<StatementLoggingId> {
1335 self.statement_uuid
1336 }
1337}
1338
1339#[derive(Debug)]
1349#[must_use]
1350pub struct ExecuteContextGuard {
1351 extra: ExecuteContextExtra,
1352 coordinator_tx: mpsc::UnboundedSender<Message>,
1357}
1358
1359impl Default for ExecuteContextGuard {
1360 fn default() -> Self {
1361 let (tx, _rx) = mpsc::unbounded_channel();
1365 Self {
1366 extra: ExecuteContextExtra::default(),
1367 coordinator_tx: tx,
1368 }
1369 }
1370}
1371
1372impl ExecuteContextGuard {
1373 pub(crate) fn new(
1374 statement_uuid: Option<StatementLoggingId>,
1375 coordinator_tx: mpsc::UnboundedSender<Message>,
1376 ) -> Self {
1377 Self {
1378 extra: ExecuteContextExtra::new(statement_uuid),
1379 coordinator_tx,
1380 }
1381 }
1382 pub fn is_trivial(&self) -> bool {
1383 self.extra.is_trivial()
1384 }
1385 pub fn contents(&self) -> Option<StatementLoggingId> {
1386 self.extra.contents()
1387 }
1388 pub(crate) fn defuse(mut self) -> ExecuteContextExtra {
1395 std::mem::take(&mut self.extra)
1397 }
1398}
1399
1400impl Drop for ExecuteContextGuard {
1401 fn drop(&mut self) {
1402 if let Some(statement_uuid) = self.extra.statement_uuid.take() {
1403 let msg = Message::RetireExecute {
1406 data: ExecuteContextExtra {
1407 statement_uuid: Some(statement_uuid),
1408 },
1409 otel_ctx: OpenTelemetryContext::obtain(),
1410 reason: StatementEndedExecutionReason::Aborted,
1411 };
1412 let _ = self.coordinator_tx.send(msg);
1415 }
1416 }
1417}
1418
1419#[derive(Debug)]
1424pub struct ExecuteContext {
1425 inner: Option<Box<ExecuteContextInner>>,
1427}
1428
1429impl std::ops::Deref for ExecuteContext {
1430 type Target = ExecuteContextInner;
1431 fn deref(&self) -> &Self::Target {
1432 self.inner.as_ref().expect("only consumed by value")
1433 }
1434}
1435
1436impl std::ops::DerefMut for ExecuteContext {
1437 fn deref_mut(&mut self) -> &mut Self::Target {
1438 self.inner.as_mut().expect("only consumed by value")
1439 }
1440}
1441
1442impl Drop for ExecuteContext {
1443 fn drop(&mut self) {
1444 let Some(inner) = self.inner.take() else {
1445 return;
1446 };
1447 tracing::warn!("execute context dropped without retirement, failing the client");
1450 let ExecuteContextInner { tx, session, .. } = *inner;
1451 tx.send(
1452 Err(AdapterError::Internal(
1453 "statement execution abandoned, outcome unknown (server shutting down)".into(),
1454 )),
1455 session,
1456 );
1457 }
1458}
1459
1460#[derive(Derivative)]
1461#[derivative(Debug)]
1462pub struct ExecuteContextInner {
1463 tx: ClientTransmitter<ExecuteResponse>,
1464 internal_cmd_tx: mpsc::UnboundedSender<Message>,
1465 session: Session,
1466 extra: ExecuteContextGuard,
1467 #[derivative(Debug = "ignore")]
1468 response_barriers: Vec<BuiltinTableAppendNotify>,
1469}
1470
1471impl ExecuteContext {
1472 pub fn session(&self) -> &Session {
1473 &self.session
1474 }
1475
1476 pub fn session_mut(&mut self) -> &mut Session {
1477 &mut self.session
1478 }
1479
1480 pub fn tx(&self) -> &ClientTransmitter<ExecuteResponse> {
1481 &self.tx
1482 }
1483
1484 pub fn tx_mut(&mut self) -> &mut ClientTransmitter<ExecuteResponse> {
1485 &mut self.tx
1486 }
1487
1488 pub fn from_parts(
1489 tx: ClientTransmitter<ExecuteResponse>,
1490 internal_cmd_tx: mpsc::UnboundedSender<Message>,
1491 session: Session,
1492 extra: ExecuteContextGuard,
1493 ) -> Self {
1494 Self::from_parts_with_response_barriers(tx, internal_cmd_tx, session, extra, Vec::new())
1495 }
1496
1497 pub fn from_parts_with_response_barriers(
1498 tx: ClientTransmitter<ExecuteResponse>,
1499 internal_cmd_tx: mpsc::UnboundedSender<Message>,
1500 session: Session,
1501 extra: ExecuteContextGuard,
1502 response_barriers: Vec<BuiltinTableAppendNotify>,
1503 ) -> Self {
1504 Self {
1505 inner: Some(
1506 ExecuteContextInner {
1507 tx,
1508 session,
1509 extra,
1510 response_barriers,
1511 internal_cmd_tx,
1512 }
1513 .into(),
1514 ),
1515 }
1516 }
1517
1518 pub fn into_parts(
1532 mut self,
1533 ) -> (
1534 ClientTransmitter<ExecuteResponse>,
1535 mpsc::UnboundedSender<Message>,
1536 Session,
1537 ExecuteContextGuard,
1538 Vec<BuiltinTableAppendNotify>,
1539 ) {
1540 let ExecuteContextInner {
1541 tx,
1542 internal_cmd_tx,
1543 session,
1544 extra,
1545 response_barriers,
1546 } = *self.inner.take().expect("only consumed by value");
1547 (tx, internal_cmd_tx, session, extra, response_barriers)
1548 }
1549
1550 #[instrument(level = "debug")]
1552 pub fn retire(mut self, result: Result<ExecuteResponse, AdapterError>) {
1553 let response_barriers = std::mem::take(&mut self.response_barriers);
1554 if response_barriers.is_empty() {
1555 let (tx, internal_cmd_tx, session, extra, _) = self.into_parts();
1556 retire_execution_context(tx, internal_cmd_tx, session, extra, result);
1557 return;
1558 }
1559 spawn(
1562 || "execute_context::retire_after_response_barriers",
1563 async move {
1564 for barrier in response_barriers {
1565 barrier.await;
1566 }
1567 self.retire(result);
1568 },
1569 );
1570 }
1571
1572 pub(crate) fn delay_response_until(&mut self, barrier: BuiltinTableAppendCompletion) {
1574 self.response_barriers.extend(barrier.into_notify());
1575 }
1576
1577 pub fn extra(&self) -> &ExecuteContextGuard {
1578 &self.extra
1579 }
1580
1581 pub fn extra_mut(&mut self) -> &mut ExecuteContextGuard {
1582 &mut self.extra
1583 }
1584}
1585
1586fn retire_execution_context(
1587 tx: ClientTransmitter<ExecuteResponse>,
1588 internal_cmd_tx: mpsc::UnboundedSender<Message>,
1589 session: Session,
1590 extra: ExecuteContextGuard,
1591 result: Result<ExecuteResponse, AdapterError>,
1592) {
1593 let reason = if extra.is_trivial() {
1594 None
1595 } else {
1596 Some((&result).into())
1597 };
1598 tx.send(result, session);
1599 if let Some(reason) = reason {
1600 let extra = extra.defuse();
1601 if let Err(e) = internal_cmd_tx.send(Message::RetireExecute {
1602 otel_ctx: OpenTelemetryContext::obtain(),
1603 data: extra,
1604 reason,
1605 }) {
1606 warn!("internal_cmd_rx dropped before we could send: {:?}", e);
1607 }
1608 }
1609}
1610
1611#[derive(Debug)]
1612struct ClusterReplicaStatuses(
1613 BTreeMap<ClusterId, BTreeMap<ReplicaId, BTreeMap<ProcessId, ClusterReplicaProcessStatus>>>,
1614);
1615
1616impl ClusterReplicaStatuses {
1617 pub(crate) fn new() -> ClusterReplicaStatuses {
1618 ClusterReplicaStatuses(BTreeMap::new())
1619 }
1620
1621 pub(crate) fn initialize_cluster_statuses(&mut self, cluster_id: ClusterId) {
1625 let prev = self.0.insert(cluster_id, BTreeMap::new());
1626 assert_eq!(
1627 prev, None,
1628 "cluster {cluster_id} statuses already initialized"
1629 );
1630 }
1631
1632 pub(crate) fn initialize_cluster_replica_statuses(
1636 &mut self,
1637 cluster_id: ClusterId,
1638 replica_id: ReplicaId,
1639 num_processes: usize,
1640 time: DateTime<Utc>,
1641 ) {
1642 tracing::info!(
1643 ?cluster_id,
1644 ?replica_id,
1645 ?time,
1646 "initializing cluster replica status"
1647 );
1648 let replica_statuses = self.0.entry(cluster_id).or_default();
1649 let process_statuses = (0..num_processes)
1650 .map(|process_id| {
1651 let status = ClusterReplicaProcessStatus {
1652 status: ClusterStatus::Offline(Some(OfflineReason::Initializing)),
1653 restart_count: 0,
1654 time: time.clone(),
1655 };
1656 (u64::cast_from(process_id), status)
1657 })
1658 .collect();
1659 let prev = replica_statuses.insert(replica_id, process_statuses);
1660 assert_none!(
1661 prev,
1662 "cluster replica {cluster_id}.{replica_id} statuses already initialized"
1663 );
1664 }
1665
1666 pub(crate) fn remove_cluster_statuses(
1670 &mut self,
1671 cluster_id: &ClusterId,
1672 ) -> BTreeMap<ReplicaId, BTreeMap<ProcessId, ClusterReplicaProcessStatus>> {
1673 let prev = self.0.remove(cluster_id);
1674 prev.unwrap_or_else(|| panic!("unknown cluster: {cluster_id}"))
1675 }
1676
1677 pub(crate) fn remove_cluster_replica_statuses(
1681 &mut self,
1682 cluster_id: &ClusterId,
1683 replica_id: &ReplicaId,
1684 ) -> BTreeMap<ProcessId, ClusterReplicaProcessStatus> {
1685 let replica_statuses = self
1686 .0
1687 .get_mut(cluster_id)
1688 .unwrap_or_else(|| panic!("unknown cluster: {cluster_id}"));
1689 let prev = replica_statuses.remove(replica_id);
1690 prev.unwrap_or_else(|| panic!("unknown cluster replica: {cluster_id}.{replica_id}"))
1691 }
1692
1693 pub(crate) fn ensure_cluster_status(
1697 &mut self,
1698 cluster_id: ClusterId,
1699 replica_id: ReplicaId,
1700 process_id: ProcessId,
1701 status: ClusterReplicaProcessStatus,
1702 ) {
1703 let replica_statuses = self
1704 .0
1705 .get_mut(&cluster_id)
1706 .unwrap_or_else(|| panic!("unknown cluster: {cluster_id}"))
1707 .get_mut(&replica_id)
1708 .unwrap_or_else(|| panic!("unknown cluster replica: {cluster_id}.{replica_id}"));
1709 replica_statuses.insert(process_id, status);
1710 }
1711
1712 pub fn get_cluster_replica_status(
1716 &self,
1717 cluster_id: ClusterId,
1718 replica_id: ReplicaId,
1719 ) -> ClusterStatus {
1720 let process_status = self.get_cluster_replica_statuses(cluster_id, replica_id);
1721 Self::cluster_replica_status(process_status)
1722 }
1723
1724 pub fn cluster_replica_status(
1726 process_status: &BTreeMap<ProcessId, ClusterReplicaProcessStatus>,
1727 ) -> ClusterStatus {
1728 process_status
1729 .values()
1730 .fold(ClusterStatus::Online, |s, p| match (s, p.status) {
1731 (ClusterStatus::Online, ClusterStatus::Online) => ClusterStatus::Online,
1732 (x, y) => {
1733 let reason_x = match x {
1734 ClusterStatus::Offline(reason) => reason,
1735 ClusterStatus::Online => None,
1736 };
1737 let reason_y = match y {
1738 ClusterStatus::Offline(reason) => reason,
1739 ClusterStatus::Online => None,
1740 };
1741 ClusterStatus::Offline(reason_x.or(reason_y))
1743 }
1744 })
1745 }
1746
1747 pub(crate) fn get_cluster_replica_statuses(
1751 &self,
1752 cluster_id: ClusterId,
1753 replica_id: ReplicaId,
1754 ) -> &BTreeMap<ProcessId, ClusterReplicaProcessStatus> {
1755 self.try_get_cluster_replica_statuses(cluster_id, replica_id)
1756 .unwrap_or_else(|| panic!("unknown cluster replica: {cluster_id}.{replica_id}"))
1757 }
1758
1759 pub(crate) fn try_get_cluster_replica_statuses(
1761 &self,
1762 cluster_id: ClusterId,
1763 replica_id: ReplicaId,
1764 ) -> Option<&BTreeMap<ProcessId, ClusterReplicaProcessStatus>> {
1765 self.try_get_cluster_statuses(cluster_id)
1766 .and_then(|statuses| statuses.get(&replica_id))
1767 }
1768
1769 pub(crate) fn try_get_cluster_statuses(
1771 &self,
1772 cluster_id: ClusterId,
1773 ) -> Option<&BTreeMap<ReplicaId, BTreeMap<ProcessId, ClusterReplicaProcessStatus>>> {
1774 self.0.get(&cluster_id)
1775 }
1776}
1777
1778#[derive(Derivative)]
1780#[derivative(Debug)]
1781pub struct Coordinator {
1782 #[derivative(Debug = "ignore")]
1784 controller: mz_controller::Controller,
1785 catalog: Arc<Catalog>,
1793 #[derivative(Debug = "ignore")]
1794 checked_create_sql: CheckedCreateSql,
1795
1796 persist_client: PersistClient,
1799
1800 internal_cmd_tx: mpsc::UnboundedSender<Message>,
1802 group_commit_tx: appends::GroupCommitNotifier,
1804 reconcile_now: Arc<Notify>,
1808 group_committer_tx: mpsc::UnboundedSender<appends::TableWriteCmd>,
1809
1810 strict_serializable_reads_tx: mpsc::UnboundedSender<(ConnectionId, PendingReadTxn)>,
1812
1813 linearize_reads_notify: Arc<Notify>,
1817
1818 global_timelines: BTreeMap<Timeline, TimelineState>,
1821
1822 transient_id_gen: Arc<TransientIdGen>,
1824 active_conns: BTreeMap<ConnectionId, ConnMeta>,
1827
1828 txn_read_holds: BTreeMap<ConnectionId, read_policy::ReadHolds>,
1832
1833 peek_registry: Arc<crate::peek_registry::PeekRegistry>,
1835
1836 pending_linearize_read_txns: BTreeMap<ConnectionId, PendingReadTxn>,
1838
1839 active_compute_sinks: BTreeMap<GlobalId, ActiveComputeSink>,
1841 active_webhooks: BTreeMap<CatalogItemId, WebhookAppenderInvalidator>,
1843 active_copies: BTreeMap<ConnectionId, ActiveCopyFrom>,
1846
1847 connection_cancel_watches: BTreeMap<ConnectionId, (watch::Sender<bool>, watch::Receiver<bool>)>,
1858 introspection_subscribes: BTreeMap<GlobalId, IntrospectionSubscribe>,
1860 hydration_history_replica_cursor: Option<ReplicaId>,
1862 hydration_history_sweep: Option<AbortOnDropHandle<()>>,
1864 metric_sinks: BTreeMap<(ReplicaId, &'static str), InstalledMetricSink>,
1869 metric_sink_plans: BTreeMap<&'static str, PlannedMetricSink>,
1872
1873 pending_writes: Vec<PendingWriteTxn>,
1875
1876 occ_write_semaphore: Arc<Semaphore>,
1887
1888 advance_timelines_interval: Interval,
1898
1899 serialized_ddl: LockedVecDeque<DeferredDdl>,
1908
1909 secrets_controller: Arc<dyn SecretsController>,
1912 caching_secrets_reader: CachingSecretsReader,
1914
1915 cloud_resource_controller: Option<Arc<dyn CloudResourceController>>,
1918
1919 storage_usage_client: StorageUsageClient,
1921 storage_usage_collection_interval: Duration,
1923
1924 #[derivative(Debug = "ignore")]
1926 segment_client: Option<mz_segment::Client>,
1927
1928 metrics: Metrics,
1930 optimizer_metrics: OptimizerMetrics,
1932
1933 tracing_handle: TracingHandle,
1935
1936 statement_logging: StatementLogging,
1938
1939 webhook_concurrency_limit: WebhookConcurrencyLimiter,
1941
1942 timestamp_oracle_config: Option<TimestampOracleConfig>,
1945
1946 caught_up_check: Option<CaughtUpCheckContext>,
1950
1951 catalog_info_metrics_registry: MetricsRegistry,
1954
1955 scoped_frontend: Option<Arc<SystemParameterFrontend>>,
1964
1965 installed_watch_sets: BTreeMap<WatchSetId, (ConnectionId, WatchSetResponse)>,
1967
1968 connection_watch_sets: BTreeMap<ConnectionId, BTreeSet<WatchSetId>>,
1970
1971 cluster_replica_statuses: ClusterReplicaStatuses,
1973
1974 read_only_controllers: bool,
1978
1979 buffered_builtin_table_updates: Option<Vec<BuiltinTableUpdate>>,
1987
1988 license_key: ValidatedLicenseKey,
1989
1990 user_id_pool: IdPool,
1992}
1993
1994impl Coordinator {
1995 pub(crate) async fn reconcile_scoped_system_parameters(
2014 &mut self,
2015 scoped: ScopedParameters,
2016 prune_scope: ScopedParametersScope,
2017 ) {
2018 if self.catalog().state().scoped_system_parameters() == &scoped {
2021 return;
2022 }
2023
2024 if let Err(e) = self
2032 .catalog_transact(
2033 None,
2034 vec![crate::catalog::Op::UpdateScopedSystemParameters {
2035 scoped,
2036 prune_scope,
2037 }],
2038 )
2039 .await
2040 {
2041 tracing::warn!("failed to persist scoped system parameters: {e}");
2042 }
2043 }
2044
2045 fn scoped_overrides_create_op(&self, ops: &[crate::catalog::Op]) -> Option<crate::catalog::Op> {
2063 let mut created_clusters = BTreeMap::new();
2064 let mut clusters = Vec::new();
2065 for op in ops {
2066 let crate::catalog::Op::CreateCluster { id, name, .. } = op else {
2067 continue;
2068 };
2069 let cluster = ClusterScopeContext {
2070 id: id.to_string(),
2071 name: name.clone(),
2072 is_builtin: id.is_system(),
2073 };
2074 created_clusters.insert(*id, cluster.clone());
2075 clusters.push(ClusterEvalContext {
2076 cluster_id: *id,
2077 cluster,
2078 });
2079 }
2080
2081 let mut replicas = Vec::new();
2082 for op in ops {
2083 let crate::catalog::Op::CreateClusterReplica {
2084 cluster_id,
2085 replica_id,
2086 name,
2087 config,
2088 ..
2089 } = op
2090 else {
2091 continue;
2092 };
2093 let ReplicaLocation::Managed(location) = &config.location else {
2094 continue;
2095 };
2096 let Some(cluster) = created_clusters.get(cluster_id).cloned().or_else(|| {
2097 self.catalog()
2098 .try_get_cluster(*cluster_id)
2099 .map(|cluster| ClusterScopeContext {
2100 id: cluster_id.to_string(),
2101 name: cluster.name.clone(),
2102 is_builtin: cluster_id.is_system(),
2103 })
2104 }) else {
2105 continue;
2106 };
2107 replicas.push(ReplicaEvalContext {
2108 cluster_id: *cluster_id,
2109 replica_id: *replica_id,
2110 replica: ReplicaScopeContext {
2111 id: replica_id.to_string(),
2112 name: name.clone(),
2113 is_builtin: cluster_id.is_system(),
2114 size: location.size.clone(),
2115 size_family: location.allocation.family().to_string(),
2116 cluster_id: cluster_id.to_string(),
2117 cluster_name: cluster.name.clone(),
2118 },
2119 cluster,
2120 });
2121 }
2122
2123 if clusters.is_empty() && replicas.is_empty() {
2124 return None;
2125 }
2126 let frontend = self.scoped_frontend.clone()?;
2127 let catalog = self.catalog();
2128 let system_config = catalog.system_config();
2129
2130 let replica_param_names: Vec<&'static str> = system_config
2133 .iter_synced()
2134 .filter(|var| var.scope() == ParameterScope::Replica)
2135 .map(|var| var.name())
2136 .collect();
2137 let cluster_param_names: Vec<&'static str> = system_config
2138 .iter_synced()
2139 .filter(|var| var.scope() == ParameterScope::Cluster)
2140 .map(|var| var.name())
2141 .collect();
2142
2143 let params = SynchronizedParameters::new(system_config.clone());
2144 let mut evaluated = ScopedParameters::default();
2145 if !cluster_param_names.is_empty() && !clusters.is_empty() {
2146 evaluated.cluster =
2147 frontend.pull_cluster_overrides(¶ms, &cluster_param_names, &clusters);
2148 }
2149 if !replica_param_names.is_empty() && !replicas.is_empty() {
2150 evaluated.replica =
2151 frontend.pull_replica_overrides(¶ms, &replica_param_names, &replicas);
2152 }
2153 let prune_scope = ScopedParametersScope {
2157 clusters: clusters.iter().map(|cluster| cluster.cluster_id).collect(),
2158 replicas: replicas.iter().map(|replica| replica.replica_id).collect(),
2159 };
2160 Some(crate::catalog::Op::UpdateScopedSystemParameters {
2161 scoped: evaluated,
2162 prune_scope,
2163 })
2164 }
2165
2166 pub(crate) fn replica_dyncfg_overrides(
2172 &self,
2173 ) -> BTreeMap<ComputeInstanceId, BTreeMap<ReplicaId, ConfigUpdates>> {
2174 let replica_overrides = &self.catalog().state().scoped_system_parameters().replica;
2175
2176 let dyncfgs = self.catalog().system_config().dyncfgs();
2177 let mut instance_overrides: BTreeMap<
2178 ComputeInstanceId,
2179 BTreeMap<ReplicaId, ConfigUpdates>,
2180 > = BTreeMap::new();
2181 for cluster in self.catalog().clusters() {
2182 for replica in cluster.replicas() {
2183 let Some(values) = replica_overrides.get(&replica.replica_id) else {
2184 continue;
2185 };
2186 let mut updates = ConfigUpdates::default();
2187 for (name, value) in values {
2188 let Some(entry) = dyncfgs.entry(name) else {
2189 continue;
2192 };
2193 match entry.parse_val(value) {
2194 Ok(val) => updates.add_dynamic(name, val),
2195 Err(e) => {
2196 tracing::warn!(%name, %value, "cannot parse scoped override: {e}")
2197 }
2198 }
2199 }
2200 if !updates.updates.is_empty() {
2201 instance_overrides
2202 .entry(cluster.id)
2203 .or_default()
2204 .insert(replica.replica_id, updates);
2205 }
2206 }
2207 }
2208
2209 instance_overrides
2210 }
2211
2212 pub(crate) fn push_replica_dyncfg_overrides(&mut self) {
2218 let instance_overrides = self.replica_dyncfg_overrides();
2219
2220 self.controller
2235 .update_replica_dyncfg_overrides(instance_overrides);
2236 let compute_config = crate::flags::compute_config(self.catalog().system_config());
2242 self.controller.compute.update_configuration(compute_config);
2243 let storage_config = crate::flags::storage_config(self.catalog().system_config());
2244 self.controller.storage.update_parameters(storage_config);
2245 }
2246
2247 pub(crate) fn cluster_scoped_optimizer_overrides(
2251 &self,
2252 cluster_id: ClusterId,
2253 ) -> OptimizerFeatureOverrides {
2254 self.catalog()
2255 .state()
2256 .cluster_scoped_optimizer_overrides(cluster_id)
2257 }
2258
2259 #[instrument(name = "coord::bootstrap")]
2263 pub(crate) async fn bootstrap(
2264 &mut self,
2265 boot_ts: Timestamp,
2266 migrated_storage_collections_0dt: BTreeSet<CatalogItemId>,
2267 hydrate_migrated_mvs: bool,
2268 mut builtin_table_updates: Vec<BuiltinTableUpdate>,
2269 cached_global_exprs: BTreeMap<GlobalId, GlobalExpressions>,
2270 uncached_local_exprs: BTreeMap<GlobalId, LocalExpressions>,
2271 ) -> Result<(), AdapterError> {
2272 let bootstrap_start = Instant::now();
2273 info!("startup: coordinator init: bootstrap beginning");
2274 info!("startup: coordinator init: bootstrap: preamble beginning");
2275
2276 let cluster_statuses: Vec<(_, Vec<_>)> = self
2279 .catalog()
2280 .clusters()
2281 .map(|cluster| {
2282 (
2283 cluster.id(),
2284 cluster
2285 .replicas()
2286 .map(|replica| {
2287 (replica.replica_id, replica.config.location.num_processes())
2288 })
2289 .collect(),
2290 )
2291 })
2292 .collect();
2293 let now = self.now_datetime();
2294 for (cluster_id, replica_statuses) in cluster_statuses {
2295 self.cluster_replica_statuses
2296 .initialize_cluster_statuses(cluster_id);
2297 for (replica_id, num_processes) in replica_statuses {
2298 self.cluster_replica_statuses
2299 .initialize_cluster_replica_statuses(
2300 cluster_id,
2301 replica_id,
2302 num_processes,
2303 now,
2304 );
2305 }
2306 }
2307
2308 let system_config = self.catalog().system_config();
2309
2310 mz_metrics::update_dyncfg(&system_config.dyncfg_updates());
2312
2313 let compute_config = flags::compute_config(system_config);
2315 let storage_config = flags::storage_config(system_config);
2316 let scheduling_config = flags::orchestrator_scheduling_config(system_config);
2317 let dyncfg_updates = system_config.dyncfg_updates();
2318 self.controller.compute.update_configuration(compute_config);
2319 self.controller.storage.update_parameters(storage_config);
2320 self.controller
2321 .update_orchestrator_scheduling_config(scheduling_config);
2322 self.controller.update_configuration(dyncfg_updates);
2323
2324 let replica_dyncfg_overrides = self.replica_dyncfg_overrides();
2331 self.controller
2332 .update_replica_dyncfg_overrides(replica_dyncfg_overrides);
2333
2334 let enforce_credit_limit_at_bootstrap = !matches!(
2339 self.license_key.expiration_behavior,
2340 ExpirationBehavior::DisableClusterCreation,
2341 );
2342 if enforce_credit_limit_at_bootstrap {
2343 self.validate_resource_limit_numeric(
2344 Numeric::zero(),
2345 self.current_credit_consumption_rate(None),
2346 |system_vars| {
2347 self.license_key
2348 .max_credit_consumption_rate()
2349 .map_or_else(|| system_vars.max_credit_consumption_rate(), Numeric::from)
2350 },
2351 "cluster replica",
2352 MAX_CREDIT_CONSUMPTION_RATE.name(),
2353 )?;
2354 }
2355
2356 let mut policies_to_set: BTreeMap<CompactionWindow, CollectionIdBundle> =
2357 Default::default();
2358
2359 let enable_worker_core_affinity =
2360 self.catalog().system_config().enable_worker_core_affinity();
2361 for instance in self.catalog.clusters() {
2362 self.controller.create_cluster(
2363 instance.id,
2364 ClusterConfig {
2365 arranged_logs: instance.log_indexes.clone(),
2366 workload_class: instance.config.workload_class.clone(),
2367 },
2368 )?;
2369 for replica in instance.replicas() {
2370 let role = instance.role();
2371 self.controller.create_replica(
2372 instance.id,
2373 replica.replica_id,
2374 instance.name.clone(),
2375 replica.name.clone(),
2376 role,
2377 replica.config.clone(),
2378 enable_worker_core_affinity,
2379 )?;
2380 }
2381 }
2382
2383 self.push_replica_dyncfg_overrides();
2395
2396 info!(
2397 "startup: coordinator init: bootstrap: preamble complete in {:?}",
2398 bootstrap_start.elapsed()
2399 );
2400
2401 let init_storage_collections_start = Instant::now();
2402 info!("startup: coordinator init: bootstrap: storage collections init beginning");
2403 self.bootstrap_storage_collections(&migrated_storage_collections_0dt)
2404 .await;
2405 info!(
2406 "startup: coordinator init: bootstrap: storage collections init complete in {:?}",
2407 init_storage_collections_start.elapsed()
2408 );
2409
2410 self.controller.start_compute_introspection_sink();
2415
2416 let sorting_start = Instant::now();
2417 info!("startup: coordinator init: bootstrap: sorting catalog entries");
2418 let entries = self.bootstrap_sort_catalog_entries();
2419 info!(
2420 "startup: coordinator init: bootstrap: sorting catalog entries complete in {:?}",
2421 sorting_start.elapsed()
2422 );
2423
2424 let optimize_dataflows_start = Instant::now();
2425 info!("startup: coordinator init: bootstrap: optimize dataflow plans beginning");
2426 let uncached_global_exps = self.bootstrap_dataflow_plans(&entries, cached_global_exprs)?;
2427 info!(
2428 "startup: coordinator init: bootstrap: optimize dataflow plans complete in {:?}",
2429 optimize_dataflows_start.elapsed()
2430 );
2431
2432 info!(
2433 missed_local = uncached_local_exprs.len(),
2434 missed_global = uncached_global_exps.len(),
2435 "optimized expressions without an expression cache hit at startup"
2436 );
2437 let _fut = self.catalog().update_expression_cache(
2439 uncached_local_exprs.into_iter().collect(),
2440 uncached_global_exps.into_iter().collect(),
2441 Default::default(),
2442 );
2443
2444 let bootstrap_as_ofs_start = Instant::now();
2448 info!("startup: coordinator init: bootstrap: dataflow as-of bootstrapping beginning");
2449 let dataflow_read_holds = self.bootstrap_dataflow_as_ofs().await;
2450 info!(
2451 "startup: coordinator init: bootstrap: dataflow as-of bootstrapping complete in {:?}",
2452 bootstrap_as_ofs_start.elapsed()
2453 );
2454
2455 let postamble_start = Instant::now();
2456 info!("startup: coordinator init: bootstrap: postamble beginning");
2457
2458 let logs: BTreeSet<_> = BUILTINS::logs()
2459 .map(|log| self.catalog().resolve_builtin_log(log))
2460 .flat_map(|item_id| self.catalog().get_global_ids(&item_id))
2461 .collect();
2462
2463 let mut privatelink_connections = BTreeMap::new();
2464
2465 for entry in &entries {
2466 debug!(
2467 "coordinator init: installing {} {}",
2468 entry.item().typ(),
2469 entry.id()
2470 );
2471 let mut policy = entry.item().initial_logical_compaction_window();
2472 match entry.item() {
2473 CatalogItem::Source(source) => {
2479 if source.custom_logical_compaction_window.is_none() {
2481 if let DataSourceDesc::IngestionExport { ingestion_id, .. } =
2482 source.data_source
2483 {
2484 policy = Some(
2485 self.catalog()
2486 .get_entry(&ingestion_id)
2487 .source()
2488 .expect("must be source")
2489 .custom_logical_compaction_window
2490 .unwrap_or_default(),
2491 );
2492 }
2493 }
2494 policies_to_set
2495 .entry(policy.expect("sources have a compaction window"))
2496 .or_insert_with(Default::default)
2497 .storage_ids
2498 .insert(source.global_id());
2499 }
2500 CatalogItem::Table(table) => {
2501 policies_to_set
2502 .entry(policy.expect("tables have a compaction window"))
2503 .or_insert_with(Default::default)
2504 .storage_ids
2505 .extend(table.global_ids());
2506 }
2507 CatalogItem::Index(idx) => {
2508 let policy_entry = policies_to_set
2509 .entry(policy.expect("indexes have a compaction window"))
2510 .or_insert_with(Default::default);
2511
2512 if logs.contains(&idx.on) {
2513 policy_entry
2514 .compute_ids
2515 .entry(idx.cluster_id)
2516 .or_insert_with(BTreeSet::new)
2517 .insert(idx.global_id());
2518 } else {
2519 let df_desc = self
2520 .catalog()
2521 .try_get_physical_plan(&idx.global_id())
2522 .expect("added in `bootstrap_dataflow_plans`")
2523 .clone();
2524
2525 let df_meta = self
2526 .catalog()
2527 .try_get_dataflow_metainfo(&idx.global_id())
2528 .expect("added in `bootstrap_dataflow_plans`");
2529
2530 if self.catalog().state().system_config().enable_mz_notices() {
2531 self.catalog().state().pack_optimizer_notices(
2533 &mut builtin_table_updates,
2534 df_meta.optimizer_notices.iter(),
2535 Diff::ONE,
2536 );
2537 }
2538
2539 policy_entry
2542 .compute_ids
2543 .entry(idx.cluster_id)
2544 .or_insert_with(Default::default)
2545 .extend(df_desc.export_ids());
2546
2547 self.controller
2548 .compute
2549 .create_dataflow(idx.cluster_id, df_desc, None)
2550 .unwrap_or_terminate("cannot fail to create dataflows");
2551 }
2552 }
2553 CatalogItem::View(_) => (),
2554 CatalogItem::MaterializedView(mview) => {
2555 policies_to_set
2561 .entry(policy.expect("materialized views have a compaction window"))
2562 .or_insert_with(Default::default)
2563 .storage_ids
2564 .extend(mview.global_ids());
2565
2566 let mut df_desc = self
2567 .catalog()
2568 .try_get_physical_plan(&mview.global_id_writes())
2569 .expect("added in `bootstrap_dataflow_plans`")
2570 .clone();
2571
2572 if let Some(initial_as_of) = mview.initial_as_of.clone() {
2573 df_desc.set_initial_as_of(initial_as_of);
2574 }
2575
2576 let until = mview
2578 .refresh_schedule
2579 .as_ref()
2580 .and_then(|s| s.last_refresh())
2581 .and_then(|r| r.try_step_forward());
2582 if let Some(until) = until {
2583 df_desc.until.meet_assign(&Antichain::from_elem(until));
2584 }
2585
2586 let df_meta = self
2587 .catalog()
2588 .try_get_dataflow_metainfo(&mview.global_id_writes())
2589 .expect("added in `bootstrap_dataflow_plans`");
2590
2591 if self.catalog().state().system_config().enable_mz_notices() {
2592 self.catalog().state().pack_optimizer_notices(
2594 &mut builtin_table_updates,
2595 df_meta.optimizer_notices.iter(),
2596 Diff::ONE,
2597 );
2598 }
2599
2600 self.ship_dataflow(df_desc, mview.cluster_id, mview.target_replica)
2601 .await;
2602
2603 if mview.replacement_target.is_none() {
2607 let gid = mview.global_id_writes();
2608 if hydrate_migrated_mvs
2609 && migrated_storage_collections_0dt.contains(&entry.id())
2610 {
2611 self.controller
2615 .compute
2616 .allow_writes_in_read_only(mview.cluster_id, gid)
2617 .unwrap_or_terminate("allow_writes cannot fail");
2618 } else {
2619 self.allow_writes(mview.cluster_id, gid);
2620 }
2621 }
2622 }
2623 CatalogItem::MetricSink(metric_sink) => {
2624 let df_desc = self
2625 .catalog()
2626 .try_get_physical_plan(&metric_sink.global_id)
2627 .expect("added in `bootstrap_dataflow_plans`")
2628 .clone();
2629
2630 let df_meta = self
2631 .catalog()
2632 .try_get_dataflow_metainfo(&metric_sink.global_id)
2633 .expect("added in `bootstrap_dataflow_plans`");
2634
2635 if self.catalog().state().system_config().enable_mz_notices() {
2636 self.catalog().state().pack_optimizer_notices(
2638 &mut builtin_table_updates,
2639 df_meta.optimizer_notices.iter(),
2640 Diff::ONE,
2641 );
2642 }
2643
2644 self.ship_dataflow(df_desc, metric_sink.cluster_id, None)
2647 .await;
2648 }
2649 CatalogItem::Sink(sink) => {
2650 policies_to_set
2651 .entry(CompactionWindow::Default)
2652 .or_insert_with(Default::default)
2653 .storage_ids
2654 .insert(sink.global_id());
2655 }
2656 CatalogItem::Connection(catalog_connection) => {
2657 if let ConnectionDetails::AwsPrivatelink(conn) = &catalog_connection.details {
2658 privatelink_connections.insert(
2659 entry.id(),
2660 VpcEndpointConfig {
2661 aws_service_name: conn.service_name.clone(),
2662 availability_zone_ids: conn.availability_zones.clone(),
2663 },
2664 );
2665 }
2666 }
2667 CatalogItem::Log(_)
2669 | CatalogItem::Type(_)
2670 | CatalogItem::Func(_)
2671 | CatalogItem::Secret(_) => {}
2672 }
2673 }
2674
2675 if let Some(cloud_resource_controller) = &self.cloud_resource_controller {
2676 let existing_vpc_endpoints = cloud_resource_controller
2678 .list_vpc_endpoints()
2679 .await
2680 .context("list vpc endpoints")?;
2681 let existing_vpc_endpoints = BTreeSet::from_iter(existing_vpc_endpoints.into_keys());
2682 let desired_vpc_endpoints = privatelink_connections.keys().cloned().collect();
2683 let vpc_endpoints_to_remove = existing_vpc_endpoints.difference(&desired_vpc_endpoints);
2684 for id in vpc_endpoints_to_remove {
2685 cloud_resource_controller
2686 .delete_vpc_endpoint(*id)
2687 .await
2688 .context("deleting extraneous vpc endpoint")?;
2689 }
2690
2691 for (id, spec) in privatelink_connections {
2693 cloud_resource_controller
2694 .ensure_vpc_endpoint(id, spec)
2695 .await
2696 .context("ensuring vpc endpoint")?;
2697 }
2698 }
2699
2700 drop(dataflow_read_holds);
2703 for (cw, policies) in policies_to_set {
2705 self.initialize_read_policies(&policies, cw).await;
2706 }
2707
2708 debug!("startup: coordinator init: bootstrap: initializing migrated builtin tables");
2709 let migrated_updates_fut = if self.controller.read_only() {
2715 let min_timestamp = Timestamp::minimum();
2716 let migrated_builtin_table_updates: Vec<_> = builtin_table_updates
2717 .extract_if(.., |update| {
2718 let gid = self.catalog().get_entry(&update.id).latest_global_id();
2719 migrated_storage_collections_0dt.contains(&update.id)
2720 && self
2721 .controller
2722 .storage_collections
2723 .collection_frontiers(gid)
2724 .expect("all tables are registered")
2725 .write_frontier
2726 .elements()
2727 == &[min_timestamp]
2728 })
2729 .collect();
2730 if migrated_builtin_table_updates.is_empty() {
2731 futures::future::ready(()).boxed()
2732 } else {
2733 let mut grouped_appends: BTreeMap<GlobalId, Vec<TableData>> = BTreeMap::new();
2735 for update in migrated_builtin_table_updates {
2736 let gid = self.catalog().get_entry(&update.id).latest_global_id();
2737 grouped_appends.entry(gid).or_default().push(update.data);
2738 }
2739 info!(
2740 "coordinator init: rehydrating migrated builtin tables in read-only mode: {:?}",
2741 grouped_appends.keys().collect::<Vec<_>>()
2742 );
2743
2744 let mut all_appends = Vec::with_capacity(grouped_appends.len());
2746 for (item_id, table_data) in grouped_appends.into_iter() {
2747 let mut all_rows = Vec::new();
2748 let mut all_data = Vec::new();
2749 for data in table_data {
2750 match data {
2751 TableData::Rows(rows) => all_rows.extend(rows),
2752 TableData::Batches(_) => all_data.push(data),
2753 }
2754 }
2755 differential_dataflow::consolidation::consolidate(&mut all_rows);
2756 all_data.push(TableData::Rows(all_rows));
2757
2758 all_appends.push((item_id, all_data));
2760 }
2761
2762 let fut = self
2763 .controller
2764 .storage
2765 .append_table(min_timestamp, boot_ts.step_forward(), all_appends)
2766 .expect("cannot fail to append");
2767 async {
2768 fut.await
2769 .expect("One-shot shouldn't be dropped during bootstrap")
2770 .unwrap_or_terminate("cannot fail to append")
2771 }
2772 .boxed()
2773 }
2774 } else {
2775 futures::future::ready(()).boxed()
2776 };
2777
2778 info!(
2779 "startup: coordinator init: bootstrap: postamble complete in {:?}",
2780 postamble_start.elapsed()
2781 );
2782
2783 let builtin_update_start = Instant::now();
2784 info!("startup: coordinator init: bootstrap: generate builtin updates beginning");
2785
2786 if self.controller.read_only() {
2787 info!(
2788 "coordinator init: bootstrap: stashing builtin table updates while in read-only mode"
2789 );
2790
2791 self.buffered_builtin_table_updates
2792 .as_mut()
2793 .expect("in read-only mode")
2794 .append(&mut builtin_table_updates);
2795 } else {
2796 self.bootstrap_tables(&entries, builtin_table_updates).await;
2797 };
2798 info!(
2799 "startup: coordinator init: bootstrap: generate builtin updates complete in {:?}",
2800 builtin_update_start.elapsed()
2801 );
2802
2803 let cleanup_secrets_start = Instant::now();
2804 info!("startup: coordinator init: bootstrap: generate secret cleanup beginning");
2805 {
2809 let Self {
2812 secrets_controller,
2813 catalog,
2814 ..
2815 } = self;
2816
2817 let next_user_item_id = catalog.get_next_user_item_id().await?;
2818 let next_system_item_id = catalog.get_next_system_item_id().await?;
2819 let read_only = self.controller.read_only();
2820 let catalog_ids: BTreeSet<CatalogItemId> =
2825 catalog.entries().map(|entry| entry.id()).collect();
2826 let secrets_controller = Arc::clone(secrets_controller);
2827
2828 spawn(|| "cleanup-orphaned-secrets", async move {
2829 if read_only {
2830 info!(
2831 "coordinator init: not cleaning up orphaned secrets while in read-only mode"
2832 );
2833 return;
2834 }
2835 info!("coordinator init: cleaning up orphaned secrets");
2836
2837 match secrets_controller.list().await {
2838 Ok(controller_secrets) => {
2839 let controller_secrets: BTreeSet<CatalogItemId> =
2840 controller_secrets.into_iter().collect();
2841 let orphaned = controller_secrets.difference(&catalog_ids);
2842 for id in orphaned {
2843 let id_too_large = match id {
2844 CatalogItemId::System(id) => *id >= next_system_item_id,
2845 CatalogItemId::User(id) => *id >= next_user_item_id,
2846 CatalogItemId::IntrospectionSourceIndex(_)
2847 | CatalogItemId::Transient(_) => false,
2848 };
2849 if id_too_large {
2850 info!(
2851 %next_user_item_id, %next_system_item_id,
2852 "coordinator init: not deleting orphaned secret {id} that was likely created by a newer deploy generation"
2853 );
2854 } else {
2855 info!("coordinator init: deleting orphaned secret {id}");
2856 fail_point!("orphan_secrets");
2857 if let Err(e) = secrets_controller.delete(*id).await {
2858 warn!(
2859 "Dropping orphaned secret has encountered an error: {}",
2860 e
2861 );
2862 }
2863 }
2864 }
2865 }
2866 Err(e) => warn!("Failed to list secrets during orphan cleanup: {:?}", e),
2867 }
2868 });
2869 }
2870 info!(
2871 "startup: coordinator init: bootstrap: generate secret cleanup complete in {:?}",
2872 cleanup_secrets_start.elapsed()
2873 );
2874
2875 let final_steps_start = Instant::now();
2877 info!(
2878 "startup: coordinator init: bootstrap: migrate builtin tables in read-only mode beginning"
2879 );
2880 migrated_updates_fut
2881 .instrument(info_span!("coord::bootstrap::final"))
2882 .await;
2883
2884 debug!(
2885 "startup: coordinator init: bootstrap: announcing completion of initialization to controller"
2886 );
2887 self.controller.initialization_complete();
2889
2890 self.bootstrap_introspection_subscribes().await;
2892
2893 self.bootstrap_metric_sinks().await;
2895
2896 info!(
2897 "startup: coordinator init: bootstrap: migrate builtin tables in read-only mode complete in {:?}",
2898 final_steps_start.elapsed()
2899 );
2900
2901 info!(
2902 "startup: coordinator init: bootstrap complete in {:?}",
2903 bootstrap_start.elapsed()
2904 );
2905 Ok(())
2906 }
2907
2908 #[allow(clippy::async_yields_async)]
2913 #[instrument]
2914 async fn bootstrap_tables(
2915 &mut self,
2916 entries: &[CatalogEntry],
2917 mut builtin_table_updates: Vec<BuiltinTableUpdate>,
2918 ) {
2919 struct TableMetadata<'a> {
2921 id: CatalogItemId,
2922 name: &'a QualifiedItemName,
2923 table: &'a Table,
2924 }
2925
2926 let table_metas: Vec<_> = entries
2928 .into_iter()
2929 .filter_map(|entry| {
2930 entry.table().map(|table| TableMetadata {
2931 id: entry.id(),
2932 name: entry.name(),
2933 table,
2934 })
2935 })
2936 .collect();
2937
2938 debug!("coordinator init: advancing all tables to current timestamp");
2940 let WriteTimestamp {
2941 timestamp: write_ts,
2942 advance_to,
2943 } = self.get_local_write_ts().await;
2944 let appends = table_metas
2945 .iter()
2946 .map(|meta| (meta.table.global_id_writes(), Vec::new()))
2947 .collect();
2948 let table_fence_rx = self
2952 .controller
2953 .storage
2954 .append_table(write_ts.clone(), advance_to, appends)
2955 .expect("invalid updates");
2956
2957 self.apply_local_write(write_ts).await;
2958
2959 debug!("coordinator init: resetting system tables");
2961 let read_ts = self.get_local_read_ts().await;
2962
2963 let retained_across_restarts = BTreeSet::from([
2964 self.catalog()
2965 .resolve_builtin_table(&MZ_STORAGE_USAGE_BY_SHARD),
2966 self.catalog()
2967 .resolve_builtin_table(&MZ_OBJECT_ARRANGEMENT_SIZE_HISTORY),
2968 self.catalog()
2969 .resolve_builtin_table(&MZ_OBJECT_HYDRATION_HISTORY),
2970 self.catalog()
2971 .resolve_builtin_table(&MZ_REPLICA_HYDRATION_HISTORY),
2972 ]);
2973
2974 let mut retraction_tasks = Vec::new();
2975 let system_tables: Vec<_> = table_metas
2976 .iter()
2977 .filter(|meta| meta.id.is_system() && !retained_across_restarts.contains(&meta.id))
2978 .collect();
2979
2980 for system_table in system_tables {
2981 let table_id = system_table.id;
2982 let full_name = self.catalog().resolve_full_name(system_table.name, None);
2983 debug!("coordinator init: resetting system table {full_name} ({table_id})");
2984
2985 let snapshot_fut = self
2987 .controller
2988 .storage_collections
2989 .snapshot_cursor(system_table.table.global_id_writes(), read_ts);
2990 let batch_fut = self
2991 .controller
2992 .storage_collections
2993 .create_update_builder(system_table.table.global_id_writes());
2994
2995 let task = spawn(|| format!("snapshot-{table_id}"), async move {
2996 let mut batch = batch_fut
2998 .await
2999 .unwrap_or_terminate("cannot fail to create a batch for a BuiltinTable");
3000 tracing::info!(?table_id, "starting snapshot");
3001 let mut snapshot_cursor = snapshot_fut
3003 .await
3004 .unwrap_or_terminate("cannot fail to snapshot");
3005
3006 while let Some(values) = snapshot_cursor.next().await {
3008 for (key, _t, d) in values {
3009 let d_invert = d.neg();
3010 batch.add(&key, &(), &d_invert).await;
3011 }
3012 }
3013 tracing::info!(?table_id, "finished snapshot");
3014
3015 let batch = batch.finish().await;
3016 BuiltinTableUpdate::batch(table_id, batch)
3017 });
3018 retraction_tasks.push(task);
3019 }
3020
3021 let retractions_res = futures::future::join_all(retraction_tasks).await;
3022 for retractions in retractions_res {
3023 builtin_table_updates.push(retractions);
3024 }
3025
3026 table_fence_rx
3028 .await
3029 .expect("One-shot shouldn't be dropped during bootstrap")
3030 .unwrap_or_terminate("cannot fail to append");
3031
3032 info!("coordinator init: sending builtin table updates");
3033 let builtin_updates_fut = self.builtin_table_update().execute(builtin_table_updates);
3034 builtin_updates_fut.await;
3037 }
3038
3039 #[instrument]
3052 async fn bootstrap_storage_collections(
3053 &mut self,
3054 migrated_storage_collections: &BTreeSet<CatalogItemId>,
3055 ) {
3056 let catalog = self.catalog();
3057
3058 let source_desc = |object_id: GlobalId,
3059 data_source: &DataSourceDesc,
3060 desc: &RelationDesc,
3061 timeline: &Timeline| {
3062 let data_source = match data_source.clone() {
3063 DataSourceDesc::Ingestion { desc, cluster_id } => {
3065 let desc = desc.into_inline_connection(catalog.state());
3066 let ingestion = IngestionDescription::new(desc, cluster_id, object_id);
3067 DataSource::Ingestion(ingestion)
3068 }
3069 DataSourceDesc::OldSyntaxIngestion {
3070 desc,
3071 progress_subsource,
3072 data_config,
3073 details,
3074 cluster_id,
3075 } => {
3076 let desc = desc.into_inline_connection(catalog.state());
3077 let data_config = data_config.into_inline_connection(catalog.state());
3078 let progress_subsource =
3081 catalog.get_entry(&progress_subsource).latest_global_id();
3082 let mut ingestion =
3083 IngestionDescription::new(desc, cluster_id, progress_subsource);
3084 let legacy_export = SourceExport {
3085 storage_metadata: (),
3086 data_config,
3087 details,
3088 };
3089 ingestion.source_exports.insert(object_id, legacy_export);
3090
3091 DataSource::Ingestion(ingestion)
3092 }
3093 DataSourceDesc::IngestionExport {
3094 ingestion_id,
3095 external_reference: _,
3096 details,
3097 data_config,
3098 } => {
3099 let ingestion_id = catalog.get_entry(&ingestion_id).latest_global_id();
3102
3103 DataSource::IngestionExport {
3104 ingestion_id,
3105 details,
3106 data_config: data_config.into_inline_connection(catalog.state()),
3107 }
3108 }
3109 DataSourceDesc::Webhook { .. } => DataSource::Webhook,
3110 DataSourceDesc::Progress => DataSource::Progress,
3111 DataSourceDesc::Introspection(introspection) => {
3112 DataSource::Introspection(introspection)
3113 }
3114 DataSourceDesc::Catalog => DataSource::Other,
3115 };
3116 CollectionDescription {
3117 desc: desc.clone(),
3118 data_source,
3119 since: None,
3120 timeline: Some(timeline.clone()),
3121 primary: None,
3122 }
3123 };
3124
3125 let mut compute_collections = vec![];
3126 let mut collections = vec![];
3127 for entry in catalog.entries() {
3128 match entry.item() {
3129 CatalogItem::Source(source) => {
3130 collections.push((
3131 source.global_id(),
3132 source_desc(
3133 source.global_id(),
3134 &source.data_source,
3135 &source.desc,
3136 &source.timeline,
3137 ),
3138 ));
3139 }
3140 CatalogItem::Table(table) => {
3141 match &table.data_source {
3142 TableDataSource::TableWrites { defaults: _ } => {
3143 let versions: BTreeMap<_, _> = table
3144 .collection_descs()
3145 .map(|(gid, version, desc)| (version, (gid, desc)))
3146 .collect();
3147 let collection_descs = versions.iter().map(|(version, (gid, desc))| {
3148 let next_version = version.bump();
3149 let primary_collection =
3150 versions.get(&next_version).map(|(gid, _desc)| gid).copied();
3151 let mut collection_desc =
3152 CollectionDescription::for_table(desc.clone());
3153 collection_desc.primary = primary_collection;
3154
3155 (*gid, collection_desc)
3156 });
3157 collections.extend(collection_descs);
3158 }
3159 TableDataSource::DataSource {
3160 desc: data_source_desc,
3161 timeline,
3162 } => {
3163 soft_assert_eq_or_log!(table.collections.len(), 1);
3165 let collection_descs =
3166 table.collection_descs().map(|(gid, _version, desc)| {
3167 (
3168 gid,
3169 source_desc(
3170 entry.latest_global_id(),
3171 data_source_desc,
3172 &desc,
3173 timeline,
3174 ),
3175 )
3176 });
3177 collections.extend(collection_descs);
3178 }
3179 };
3180 }
3181 CatalogItem::MaterializedView(mv) => {
3182 let mut primary = mv
3190 .replacement_target
3191 .map(|target_id| catalog.get_entry(&target_id).latest_global_id());
3192 let collection_descs = mv.collection_descs().map(|(gid, _version, desc)| {
3193 let mut collection_desc =
3194 CollectionDescription::for_other(desc, mv.initial_as_of.clone());
3195 collection_desc.primary = primary;
3196 primary = Some(gid);
3197 (gid, collection_desc)
3198 });
3199
3200 collections.extend(collection_descs);
3201 compute_collections.push((mv.global_id_writes(), mv.desc.latest()));
3202 }
3203 CatalogItem::Sink(sink) => {
3204 let storage_sink_from_entry = self.catalog().get_entry_by_global_id(&sink.from);
3205 let from_desc = storage_sink_from_entry
3206 .relation_desc()
3207 .expect("sinks can only be built on items with descs")
3208 .into_owned();
3209 let collection_desc = CollectionDescription {
3210 desc: KAFKA_PROGRESS_DESC.clone(),
3212 data_source: DataSource::Sink {
3213 desc: ExportDescription {
3214 sink: StorageSinkDesc {
3215 from: sink.from,
3216 from_desc,
3217 connection: sink
3218 .connection
3219 .clone()
3220 .into_inline_connection(self.catalog().state()),
3221 envelope: sink.envelope,
3222 as_of: Antichain::from_elem(Timestamp::minimum()),
3223 with_snapshot: sink.with_snapshot,
3224 version: sink.version,
3225 from_storage_metadata: (),
3226 to_storage_metadata: (),
3227 commit_interval: sink.commit_interval,
3228 },
3229 instance_id: sink.cluster_id,
3230 },
3231 },
3232 since: None,
3233 timeline: None,
3234 primary: None,
3235 };
3236 collections.push((sink.global_id, collection_desc));
3237 }
3238 CatalogItem::Log(_)
3239 | CatalogItem::View(_)
3240 | CatalogItem::Index(_)
3241 | CatalogItem::Type(_)
3242 | CatalogItem::Func(_)
3243 | CatalogItem::Secret(_)
3244 | CatalogItem::Connection(_)
3245 | CatalogItem::MetricSink(_) => (),
3248 }
3249 }
3250
3251 let register_ts = if self.controller.read_only() {
3252 self.get_local_read_ts().await
3253 } else {
3254 self.get_local_write_ts().await.timestamp
3257 };
3258
3259 let storage_metadata = self.catalog.state().storage_metadata();
3260 let migrated_storage_collections = migrated_storage_collections
3261 .into_iter()
3262 .flat_map(|item_id| self.catalog.get_entry(item_id).global_ids())
3263 .collect();
3264
3265 self.controller
3270 .storage
3271 .evolve_nullability_for_bootstrap(storage_metadata, compute_collections)
3272 .await
3273 .unwrap_or_terminate("cannot fail to evolve collections");
3274
3275 let mut pending: BTreeMap<_, _> = collections.into_iter().collect();
3288
3289 let transitive_dep_gids: BTreeMap<_, _> = pending
3291 .keys()
3292 .map(|gid| {
3293 let entry = self.catalog.get_entry_by_global_id(gid);
3294 let item_id = entry.id();
3295 let deps = self.catalog.state().transitive_uses(item_id);
3296 let dep_gids: BTreeSet<_> = deps
3297 .filter(|dep_id| *dep_id != item_id)
3300 .map(|dep_id| self.catalog.get_entry(&dep_id).latest_global_id())
3301 .filter(|dep_gid| pending.contains_key(dep_gid))
3303 .collect();
3304 (*gid, dep_gids)
3305 })
3306 .collect();
3307
3308 let mut created_gids = Vec::new();
3309
3310 while !pending.is_empty() {
3311 let ready_gids: BTreeSet<_> = pending
3314 .keys()
3315 .filter(|gid| {
3316 let mut deps = transitive_dep_gids[gid].iter();
3317 !deps.any(|dep_gid| pending.contains_key(dep_gid))
3318 })
3319 .copied()
3320 .collect();
3321 let mut ready: Vec<_> = pending
3322 .extract_if(.., |gid, _| ready_gids.contains(gid))
3323 .collect();
3324
3325 for (gid, collection) in &mut ready {
3327 if !gid.is_system() || collection.since.is_some() {
3329 continue;
3330 }
3331
3332 let mut derived_since = Antichain::from_elem(Timestamp::MIN);
3333 for dep_gid in &transitive_dep_gids[gid] {
3334 let (since, _) = self
3335 .controller
3336 .storage
3337 .collection_frontiers(*dep_gid)
3338 .expect("previously registered");
3339 derived_since.join_assign(&since);
3340 }
3341 collection.since = Some(derived_since);
3342 }
3343
3344 if ready.is_empty() {
3345 soft_panic_or_log!(
3346 "cycle in storage collections: {:?}",
3347 pending.keys().collect::<Vec<_>>(),
3348 );
3349 ready = mem::take(&mut pending).into_iter().collect();
3353 }
3354
3355 created_gids.extend(ready.iter().map(|(gid, _collection)| *gid));
3356
3357 self.controller
3358 .storage
3359 .create_collections_for_bootstrap(
3360 storage_metadata,
3361 Some(register_ts),
3362 ready,
3363 &migrated_storage_collections,
3364 )
3365 .await
3366 .unwrap_or_terminate("cannot fail to create collections");
3367 }
3368
3369 self.controller
3371 .storage
3372 .register_table_collections(register_ts, created_gids)
3373 .await
3374 .unwrap_or_terminate("cannot fail to register tables");
3375
3376 if !self.controller.read_only() {
3377 self.apply_local_write(register_ts).await;
3378 }
3379 }
3380
3381 fn bootstrap_sort_catalog_entries(&self) -> Vec<CatalogEntry> {
3388 let mut indexes_on = BTreeMap::<_, Vec<_>>::new();
3389 let mut non_indexes = Vec::new();
3390 for entry in self.catalog().entries().cloned() {
3391 if let Some(index) = entry.index() {
3392 let on = self.catalog().get_entry_by_global_id(&index.on);
3393 indexes_on.entry(on.id()).or_default().push(entry);
3394 } else {
3395 non_indexes.push(entry);
3396 }
3397 }
3398
3399 let key_fn = |entry: &CatalogEntry| entry.id;
3400 let dependencies_fn = |entry: &CatalogEntry| entry.uses();
3401 sort_topological(&mut non_indexes, key_fn, dependencies_fn);
3402
3403 let mut result = Vec::new();
3404 for entry in non_indexes {
3405 let id = entry.id();
3406 result.push(entry);
3407 if let Some(mut indexes) = indexes_on.remove(&id) {
3408 result.append(&mut indexes);
3409 }
3410 }
3411
3412 soft_assert_or_log!(
3413 indexes_on.is_empty(),
3414 "indexes with missing dependencies: {indexes_on:?}",
3415 );
3416
3417 result
3418 }
3419
3420 #[instrument]
3431 fn bootstrap_dataflow_plans(
3432 &mut self,
3433 ordered_catalog_entries: &[CatalogEntry],
3434 mut cached_global_exprs: BTreeMap<GlobalId, GlobalExpressions>,
3435 ) -> Result<BTreeMap<GlobalId, GlobalExpressions>, AdapterError> {
3436 let mut instance_snapshots = BTreeMap::new();
3442 let mut uncached_expressions = BTreeMap::new();
3443
3444 let optimizer_config = |catalog: &Catalog, cluster_id| {
3445 let system_config = catalog.system_config();
3446 let overrides = catalog.get_cluster(cluster_id).config.features();
3447 OptimizerConfig::from(system_config)
3448 .override_from(&overrides)
3449 .override_from(
3452 &catalog
3453 .state()
3454 .cluster_scoped_optimizer_overrides(cluster_id),
3455 )
3456 };
3457
3458 for entry in ordered_catalog_entries {
3459 match entry.item() {
3460 CatalogItem::Index(idx) => {
3461 let compute_instance =
3463 instance_snapshots.entry(idx.cluster_id).or_insert_with(|| {
3464 self.instance_snapshot(idx.cluster_id)
3465 .expect("compute instance exists")
3466 });
3467 let global_id = idx.global_id();
3468
3469 if compute_instance.contains_collection(&global_id) {
3472 continue;
3473 }
3474
3475 let optimizer_config = optimizer_config(&self.catalog, idx.cluster_id);
3476
3477 let (optimized_plan, physical_plan, metainfo) =
3478 match cached_global_exprs.remove(&global_id) {
3479 Some(global_expressions)
3480 if global_expressions.optimizer_features
3481 == optimizer_config.features =>
3482 {
3483 debug!("global expression cache hit for {global_id:?}");
3484 (
3485 global_expressions.global_mir,
3486 global_expressions.physical_plan,
3487 global_expressions.dataflow_metainfos,
3488 )
3489 }
3490 Some(_) | None => {
3491 let (optimized_plan, global_lir_plan) = {
3492 let mut optimizer = optimize::index::Optimizer::new(
3494 self.owned_catalog(),
3495 compute_instance.clone(),
3496 global_id,
3497 optimizer_config.clone(),
3498 self.optimizer_metrics(),
3499 );
3500
3501 let index_plan = optimize::index::Index::new(
3503 entry.name().clone(),
3504 idx.on,
3505 idx.keys.to_vec(),
3506 );
3507 let global_mir_plan = optimizer.optimize(index_plan)?;
3508 let optimized_plan = global_mir_plan.df_desc().clone();
3509
3510 let global_lir_plan = optimizer.optimize(global_mir_plan)?;
3512
3513 (optimized_plan, global_lir_plan)
3514 };
3515
3516 let (physical_plan, metainfo) = global_lir_plan.unapply();
3517 let metainfo = {
3518 let notice_ids =
3520 std::iter::repeat_with(|| self.allocate_transient_id())
3521 .map(|(_item_id, gid)| gid)
3522 .take(metainfo.optimizer_notices.len())
3523 .collect::<Vec<_>>();
3524 self.catalog().render_notices(
3526 metainfo,
3527 notice_ids,
3528 Some(idx.global_id()),
3529 )
3530 };
3531 uncached_expressions.insert(
3532 global_id,
3533 GlobalExpressions {
3534 global_mir: optimized_plan.clone(),
3535 physical_plan: physical_plan.clone(),
3536 dataflow_metainfos: metainfo.clone(),
3537 optimizer_features: optimizer_config.features.clone(),
3538 item_version: RelationVersion::root(),
3539 },
3540 );
3541 (optimized_plan, physical_plan, metainfo)
3542 }
3543 };
3544
3545 let catalog = self.catalog_mut();
3546 catalog.set_optimized_plan(idx.global_id(), optimized_plan);
3547 catalog.set_physical_plan(idx.global_id(), physical_plan);
3548 catalog.set_dataflow_metainfo(idx.global_id(), metainfo);
3549
3550 compute_instance.insert_collection(idx.global_id());
3551 }
3552 CatalogItem::MaterializedView(mv) => {
3553 let compute_instance =
3555 instance_snapshots.entry(mv.cluster_id).or_insert_with(|| {
3556 self.instance_snapshot(mv.cluster_id)
3557 .expect("compute instance exists")
3558 });
3559 let global_id = mv.global_id_writes();
3560
3561 let optimizer_config = optimizer_config(&self.catalog, mv.cluster_id);
3562
3563 let (optimized_plan, physical_plan, metainfo) = match cached_global_exprs
3564 .remove(&global_id)
3565 {
3566 Some(global_expressions)
3567 if global_expressions.optimizer_features
3568 == optimizer_config.features =>
3569 {
3570 debug!("global expression cache hit for {global_id:?}");
3571 (
3572 global_expressions.global_mir,
3573 global_expressions.physical_plan,
3574 global_expressions.dataflow_metainfos,
3575 )
3576 }
3577 Some(_) | None => {
3578 let (_, internal_view_id) = self.allocate_transient_id();
3579 let debug_name = self
3580 .catalog()
3581 .resolve_full_name(entry.name(), None)
3582 .to_string();
3583
3584 let (optimized_plan, global_lir_plan) = {
3585 let mut optimizer = optimize::materialized_view::Optimizer::new(
3587 self.owned_catalog().as_optimizer_catalog(),
3588 compute_instance.clone(),
3589 global_id,
3590 internal_view_id,
3591 mv.desc.latest().iter_names().cloned().collect(),
3592 mv.non_null_assertions.clone(),
3593 mv.refresh_schedule.clone(),
3594 debug_name,
3595 optimizer_config.clone(),
3596 self.optimizer_metrics(),
3597 );
3598
3599 let typ = infer_sql_type_for_catalog(
3602 &mv.raw_expr,
3603 &mv.locally_optimized_expr.as_ref().clone(),
3604 );
3605 let global_mir_plan = optimizer
3606 .optimize((mv.locally_optimized_expr.as_ref().clone(), typ))?;
3607 let optimized_plan = global_mir_plan.df_desc().clone();
3608
3609 let global_lir_plan = optimizer.optimize(global_mir_plan)?;
3611
3612 (optimized_plan, global_lir_plan)
3613 };
3614
3615 let (physical_plan, metainfo) = global_lir_plan.unapply();
3616 let metainfo = {
3617 let notice_ids =
3619 std::iter::repeat_with(|| self.allocate_transient_id())
3620 .map(|(_item_id, global_id)| global_id)
3621 .take(metainfo.optimizer_notices.len())
3622 .collect::<Vec<_>>();
3623 self.catalog().render_notices(
3625 metainfo,
3626 notice_ids,
3627 Some(mv.global_id_writes()),
3628 )
3629 };
3630 uncached_expressions.insert(
3631 global_id,
3632 GlobalExpressions {
3633 global_mir: optimized_plan.clone(),
3634 physical_plan: physical_plan.clone(),
3635 dataflow_metainfos: metainfo.clone(),
3636 optimizer_features: optimizer_config.features.clone(),
3637 item_version: latest_item_version(&mv.collections),
3638 },
3639 );
3640 (optimized_plan, physical_plan, metainfo)
3641 }
3642 };
3643
3644 let catalog = self.catalog_mut();
3645 catalog.set_optimized_plan(mv.global_id_writes(), optimized_plan);
3646 catalog.set_physical_plan(mv.global_id_writes(), physical_plan);
3647 catalog.set_dataflow_metainfo(mv.global_id_writes(), metainfo);
3648
3649 compute_instance.insert_collection(mv.global_id_writes());
3650 }
3651 CatalogItem::MetricSink(metric_sink) => {
3652 let compute_instance = instance_snapshots
3654 .entry(metric_sink.cluster_id)
3655 .or_insert_with(|| {
3656 self.instance_snapshot(metric_sink.cluster_id)
3657 .expect("compute instance exists")
3658 });
3659 let global_id = metric_sink.global_id;
3660 let optimizer_config = optimizer_config(&self.catalog, metric_sink.cluster_id);
3661
3662 let (optimized_plan, physical_plan, metainfo) = match cached_global_exprs
3663 .remove(&global_id)
3664 {
3665 Some(global_expressions)
3666 if global_expressions.optimizer_features
3667 == optimizer_config.features =>
3668 {
3669 debug!("global expression cache hit for {global_id:?}");
3670 (
3671 global_expressions.global_mir,
3672 global_expressions.physical_plan,
3673 global_expressions.dataflow_metainfos,
3674 )
3675 }
3676 Some(_) | None => {
3677 let (_, view_id) = self.allocate_transient_id();
3684
3685 let (optimized_plan, global_lir_plan) = {
3686 let mut optimizer = optimize::metric_sink::Optimizer::new(
3687 self.owned_catalog(),
3688 compute_instance.clone(),
3689 view_id,
3690 global_id,
3691 optimizer_config.clone(),
3692 self.optimizer_metrics(),
3693 );
3694
3695 let metric_sink_plan = optimize::metric_sink::MetricSink::new(
3697 self.catalog()
3698 .resolve_full_name(entry.name(), None)
3699 .to_string(),
3700 optimize::metric_sink::MetricSinkFrom::Id(metric_sink.from),
3701 metric_sink.prefix.clone(),
3702 None,
3703 );
3704 let global_mir_plan = optimizer.optimize(metric_sink_plan)?;
3705 let optimized_plan = global_mir_plan.df_desc().clone();
3706
3707 let global_lir_plan = optimizer.optimize(global_mir_plan)?;
3709
3710 (optimized_plan, global_lir_plan)
3711 };
3712
3713 let (physical_plan, metainfo) = global_lir_plan.unapply();
3714 let metainfo = {
3715 let notice_ids =
3717 std::iter::repeat_with(|| self.allocate_transient_id())
3718 .map(|(_item_id, gid)| gid)
3719 .take(metainfo.optimizer_notices.len())
3720 .collect::<Vec<_>>();
3721 self.catalog()
3723 .render_notices(metainfo, notice_ids, Some(global_id))
3724 };
3725 uncached_expressions.insert(
3726 global_id,
3727 GlobalExpressions {
3728 global_mir: optimized_plan.clone(),
3729 physical_plan: physical_plan.clone(),
3730 dataflow_metainfos: metainfo.clone(),
3731 optimizer_features: optimizer_config.features.clone(),
3732 item_version: RelationVersion::root(),
3733 },
3734 );
3735 (optimized_plan, physical_plan, metainfo)
3736 }
3737 };
3738
3739 let catalog = self.catalog_mut();
3740 catalog.set_optimized_plan(global_id, optimized_plan);
3741 catalog.set_physical_plan(global_id, physical_plan);
3742 catalog.set_dataflow_metainfo(global_id, metainfo);
3743
3744 }
3748 CatalogItem::Table(_)
3749 | CatalogItem::Source(_)
3750 | CatalogItem::Log(_)
3751 | CatalogItem::View(_)
3752 | CatalogItem::Sink(_)
3753 | CatalogItem::Type(_)
3754 | CatalogItem::Func(_)
3755 | CatalogItem::Secret(_)
3756 | CatalogItem::Connection(_) => (),
3757 }
3758 }
3759
3760 Ok(uncached_expressions)
3761 }
3762
3763 async fn bootstrap_dataflow_as_ofs(&mut self) -> BTreeMap<GlobalId, ReadHold> {
3773 let mut catalog_ids = Vec::new();
3774 let mut dataflows = Vec::new();
3775 let mut read_policies = BTreeMap::new();
3776 let mut pending_replacements = BTreeSet::new();
3777 for entry in self.catalog.entries() {
3778 let gid = match entry.item() {
3779 CatalogItem::Index(idx) => idx.global_id(),
3780 CatalogItem::MaterializedView(mv) => {
3781 if mv.replacement_target.is_some() {
3782 pending_replacements.insert(mv.global_id_writes());
3783 }
3784 mv.global_id_writes()
3785 }
3786 CatalogItem::MetricSink(metric_sink) => metric_sink.global_id,
3787 CatalogItem::Table(_)
3788 | CatalogItem::Source(_)
3789 | CatalogItem::Log(_)
3790 | CatalogItem::View(_)
3791 | CatalogItem::Sink(_)
3792 | CatalogItem::Type(_)
3793 | CatalogItem::Func(_)
3794 | CatalogItem::Secret(_)
3795 | CatalogItem::Connection(_) => continue,
3796 };
3797 if let Some(plan) = self.catalog.try_get_physical_plan(&gid) {
3798 catalog_ids.push(gid);
3799 dataflows.push(plan.clone());
3800
3801 if let Some(compaction_window) = entry.item().initial_logical_compaction_window() {
3802 read_policies.insert(gid, compaction_window.into());
3803 }
3804 }
3805 }
3806
3807 let read_ts = self.get_local_read_ts().await;
3808 let read_holds = as_of_selection::run(
3809 &mut dataflows,
3810 &read_policies,
3811 &*self.controller.storage_collections,
3812 read_ts,
3813 self.controller.read_only(),
3814 &pending_replacements,
3815 );
3816
3817 let catalog = self.catalog_mut();
3818 for (id, plan) in catalog_ids.into_iter().zip_eq(dataflows) {
3819 catalog.set_physical_plan(id, plan);
3820 }
3821
3822 read_holds
3823 }
3824
3825 fn serve(
3834 mut self,
3835 mut internal_cmd_rx: mpsc::UnboundedReceiver<Message>,
3836 mut strict_serializable_reads_rx: mpsc::UnboundedReceiver<(ConnectionId, PendingReadTxn)>,
3837 mut cmd_rx: mpsc::UnboundedReceiver<(OpenTelemetryContext, Command)>,
3838 group_commit_rx: appends::GroupCommitWaiter,
3839 ) -> LocalBoxFuture<'static, ()> {
3840 async move {
3841 let mut cluster_events = self.controller.events_stream();
3843 let last_message = Arc::new(Mutex::new(LastMessage {
3844 kind: "none",
3845 stmt: None,
3846 }));
3847
3848 let (idle_tx, mut idle_rx) = tokio::sync::mpsc::channel(1);
3849 let idle_metric = self.metrics.queue_busy_seconds.clone();
3850 let last_message_watchdog = Arc::clone(&last_message);
3851
3852 spawn(|| "coord watchdog", async move {
3853 let mut interval = tokio::time::interval(Duration::from_secs(5));
3858 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
3862
3863 let mut coord_stuck = false;
3865
3866 loop {
3867 interval.tick().await;
3868
3869 let duration = tokio::time::Duration::from_secs(30);
3871 let timeout = tokio::time::timeout(duration, idle_tx.reserve()).await;
3872 let Ok(maybe_permit) = timeout else {
3873 if !coord_stuck {
3875 let last_message = last_message_watchdog.lock().expect("poisoned");
3876 tracing::warn!(
3877 last_message_kind = %last_message.kind,
3878 last_message_sql = %last_message.stmt_to_string(),
3879 "coordinator stuck for {duration:?}",
3880 );
3881 }
3882 coord_stuck = true;
3883
3884 continue;
3885 };
3886
3887 if coord_stuck {
3889 tracing::info!("Coordinator became unstuck");
3890 }
3891 coord_stuck = false;
3892
3893 let Ok(permit) = maybe_permit else {
3895 break;
3896 };
3897
3898 permit.send(idle_metric.start_timer());
3899 }
3900 });
3901
3902 self.schedule_storage_usage_collection().await;
3903 self.schedule_arrangement_sizes_collection();
3904 self.schedule_hydration_history_collection();
3905 self.spawn_privatelink_vpc_endpoints_watch_task();
3906 self.spawn_statement_logging_task();
3907 self.spawn_catalog_info_metrics_task();
3908 self.spawn_cluster_controller_task();
3909 self.spawn_caught_up_check_task();
3910 flags::tracing_config(self.catalog.system_config()).apply(&self.tracing_handle);
3911
3912 let warn_threshold = self
3914 .catalog()
3915 .system_config()
3916 .coord_slow_message_warn_threshold();
3917
3918 const MESSAGE_BATCH: usize = 64;
3920 let mut messages = Vec::with_capacity(MESSAGE_BATCH);
3921 let mut cmd_messages = Vec::with_capacity(MESSAGE_BATCH);
3922
3923 let message_batch = self.metrics.message_batch.clone();
3924
3925 let linearize_reads_notify = Arc::clone(&self.linearize_reads_notify);
3932 let linearize_reads_notified = linearize_reads_notify.notified();
3933 tokio::pin!(linearize_reads_notified);
3934
3935 loop {
3936 select! {
3940 biased;
3945
3946 _ = internal_cmd_rx.recv_many(&mut messages, MESSAGE_BATCH) => {},
3950 Some(event) = cluster_events.next() => {
3954 messages.push(Message::ClusterEvent(event))
3955 },
3956 () = self.controller.ready() => {
3960 let controller = match self.controller.get_readiness() {
3964 Readiness::Storage => ControllerReadiness::Storage,
3965 Readiness::Compute => ControllerReadiness::Compute,
3966 Readiness::Metrics(_) => ControllerReadiness::Metrics,
3967 Readiness::Internal(_) => ControllerReadiness::Internal,
3968 Readiness::NotReady => unreachable!("just signaled as ready"),
3969 };
3970 messages.push(Message::ControllerReady { controller });
3971 }
3972 permit = group_commit_rx.ready() => {
3975 let user_write_spans = self.pending_writes.iter().flat_map(|x| match x {
3981 PendingWriteTxn::User { span, .. } => Some(span),
3982 PendingWriteTxn::System { .. } => None,
3983 });
3984 let span = match user_write_spans.exactly_one() {
3985 Ok(span) => span.clone(),
3986 Err(user_write_spans) => {
3987 let span = info_span!(parent: None, "group_commit_notify");
3988 for s in user_write_spans {
3989 span.follows_from(s);
3990 }
3991 span
3992 }
3993 };
3994 messages.push(Message::GroupCommitInitiate(span, Some(permit)));
3995 },
3996 Some(pending_read_txn) = strict_serializable_reads_rx.recv() => {
4002 let mut pending_read_txns = vec![pending_read_txn];
4003 while let Ok(pending_read_txn) = strict_serializable_reads_rx.try_recv() {
4004 pending_read_txns.push(pending_read_txn);
4005 }
4006 for (conn_id, pending_read_txn) in pending_read_txns {
4007 let prev = self
4008 .pending_linearize_read_txns
4009 .insert(conn_id, pending_read_txn);
4010 soft_assert_or_log!(
4011 prev.is_none(),
4012 "connections can not have multiple concurrent reads, prev: {prev:?}"
4013 )
4014 }
4015 messages.push(Message::LinearizeReads);
4016 }
4017 count = cmd_rx.recv_many(&mut cmd_messages, MESSAGE_BATCH) => {
4021 if count == 0 {
4022 break;
4023 } else {
4024 messages.extend(cmd_messages.drain(..).map(
4025 |(otel_ctx, cmd)| Message::Command(otel_ctx, cmd),
4026 ));
4027 }
4028 },
4029 _ = self.advance_timelines_interval.tick() => {
4033 if self.controller.read_only() {
4037 messages.push(Message::AdvanceTimelines);
4038 } else {
4039 self.group_commit_tx.notify();
4040 }
4041 },
4042 () = linearize_reads_notified.as_mut() => {
4053 linearize_reads_notified.set(linearize_reads_notify.notified());
4054 messages.push(Message::LinearizeReads);
4055 }
4056
4057 timer = idle_rx.recv() => {
4062 timer.expect("does not drop").observe_duration();
4063 self.metrics
4064 .message_handling
4065 .with_label_values(&["watchdog"])
4066 .observe(0.0);
4067 continue;
4068 }
4069 };
4070
4071 message_batch.observe(f64::cast_lossy(messages.len()));
4073
4074 for msg in messages.drain(..) {
4075 let msg_kind = msg.kind();
4078 let span = span!(
4079 target: "mz_adapter::coord::handle_message_loop",
4080 Level::INFO,
4081 "coord::handle_message",
4082 kind = msg_kind
4083 );
4084
4085 *last_message.lock().expect("poisoned") = LastMessage {
4089 kind: msg_kind,
4090 stmt: match &msg {
4091 Message::Command(
4092 _,
4093 Command::Execute {
4094 portal_name,
4095 session,
4096 ..
4097 },
4098 ) => session
4099 .get_portal_unverified(portal_name)
4100 .and_then(|p| p.stmt.as_ref().map(Arc::clone)),
4101 _ => None,
4102 },
4103 };
4104
4105 let start = Instant::now();
4106 self.handle_message(msg).instrument(span.clone()).await;
4107 let duration = start.elapsed();
4108
4109 self.metrics
4110 .message_handling
4111 .with_label_values(&[msg_kind])
4112 .observe(duration.as_secs_f64());
4113
4114 if duration > warn_threshold {
4116 let otel_context = span.context().span().span_context().clone();
4117 let trace_id = otel_context.is_valid().then(|| otel_context.trace_id());
4118 tracing::error!(
4119 ?msg_kind,
4120 ?trace_id,
4121 ?duration,
4122 "very slow coordinator message"
4123 );
4124 }
4125 }
4126 }
4127
4128 if let Some(sweep) = self.hydration_history_sweep.take() {
4132 sweep.abort_and_wait().await;
4133 }
4134
4135 if let Some(catalog) = Arc::into_inner(self.catalog) {
4138 catalog.expire().await;
4139 }
4140 }
4141 .boxed_local()
4142 }
4143
4144 fn catalog(&self) -> &Catalog {
4146 &self.catalog
4147 }
4148
4149 fn owned_catalog(&self) -> Arc<Catalog> {
4152 Arc::clone(&self.catalog)
4153 }
4154
4155 fn optimizer_metrics(&self) -> OptimizerMetrics {
4158 self.optimizer_metrics.clone()
4159 }
4160
4161 fn catalog_mut(&mut self) -> &mut Catalog {
4163 Arc::make_mut(&mut self.catalog)
4171 }
4172
4173 async fn refill_user_id_pool(&mut self, min_count: u64) -> Result<(), AdapterError> {
4178 let batch_size = USER_ID_POOL_BATCH_SIZE.get(self.catalog().system_config().dyncfgs());
4179 let to_allocate = min_count.max(u64::from(batch_size));
4180 let id_ts = self.get_catalog_write_ts().await;
4181 let ids = self.catalog().allocate_user_ids(to_allocate, id_ts).await?;
4182 if let (Some((first_id, _)), Some((last_id, _))) = (ids.first(), ids.last()) {
4183 let start = match first_id {
4184 CatalogItemId::User(id) => *id,
4185 other => {
4186 return Err(AdapterError::Internal(format!(
4187 "expected User CatalogItemId, got {other:?}"
4188 )));
4189 }
4190 };
4191 let end = match last_id {
4192 CatalogItemId::User(id) => *id + 1, other => {
4194 return Err(AdapterError::Internal(format!(
4195 "expected User CatalogItemId, got {other:?}"
4196 )));
4197 }
4198 };
4199 self.user_id_pool.refill(start, end);
4200 } else {
4201 return Err(AdapterError::Internal(
4202 "catalog returned no user IDs".into(),
4203 ));
4204 }
4205 Ok(())
4206 }
4207
4208 async fn allocate_user_id(&mut self) -> Result<(CatalogItemId, GlobalId), AdapterError> {
4210 if let Some(id) = self.user_id_pool.allocate() {
4211 return Ok((CatalogItemId::User(id), GlobalId::User(id)));
4212 }
4213 self.refill_user_id_pool(1).await?;
4214 let id = self.user_id_pool.allocate().expect("ID pool just refilled");
4215 Ok((CatalogItemId::User(id), GlobalId::User(id)))
4216 }
4217
4218 async fn allocate_user_ids(
4220 &mut self,
4221 count: u64,
4222 ) -> Result<Vec<(CatalogItemId, GlobalId)>, AdapterError> {
4223 if self.user_id_pool.remaining() < count {
4224 self.refill_user_id_pool(count).await?;
4225 }
4226 let raw_ids = self
4227 .user_id_pool
4228 .allocate_many(count)
4229 .expect("pool has enough IDs after refill");
4230 Ok(raw_ids
4231 .into_iter()
4232 .map(|id| (CatalogItemId::User(id), GlobalId::User(id)))
4233 .collect())
4234 }
4235
4236 fn connection_context(&self) -> &ConnectionContext {
4238 self.controller.connection_context()
4239 }
4240
4241 fn secrets_reader(&self) -> &Arc<dyn SecretsReader> {
4243 &self.connection_context().secrets_reader
4244 }
4245
4246 #[allow(dead_code)]
4251 pub(crate) fn broadcast_notice(&self, notice: AdapterNotice) {
4252 for meta in self.active_conns.values() {
4253 let _ = meta.notice_tx.send(notice.clone());
4254 }
4255 }
4256
4257 pub(crate) fn broadcast_notice_tx(
4260 &self,
4261 ) -> Box<dyn FnOnce(AdapterNotice) -> () + Send + 'static> {
4262 let senders: Vec<_> = self
4263 .active_conns
4264 .values()
4265 .map(|meta| meta.notice_tx.clone())
4266 .collect();
4267 Box::new(move |notice| {
4268 for tx in senders {
4269 let _ = tx.send(notice.clone());
4270 }
4271 })
4272 }
4273
4274 pub(crate) fn active_conns(&self) -> &BTreeMap<ConnectionId, ConnMeta> {
4275 &self.active_conns
4276 }
4277
4278 #[instrument(level = "debug")]
4279 pub(crate) fn retire_execution(
4280 &self,
4281 reason: StatementEndedExecutionReason,
4282 ctx_extra: ExecuteContextExtra,
4283 ) {
4284 if let Some(uuid) = ctx_extra.retire() {
4285 let ended_at = self.now();
4286 self.end_statement_execution(uuid, reason, ended_at);
4287 }
4288 }
4289
4290 #[instrument(level = "debug")]
4292 pub fn dataflow_builder(&self, instance: ComputeInstanceId) -> DataflowBuilder<'_> {
4293 let compute = self
4294 .instance_snapshot(instance)
4295 .expect("compute instance does not exist");
4296 DataflowBuilder::new(self.catalog().state(), compute)
4297 }
4298
4299 pub fn instance_snapshot(
4301 &self,
4302 id: ComputeInstanceId,
4303 ) -> Result<ComputeInstanceSnapshot, InstanceMissing> {
4304 ComputeInstanceSnapshot::new(&self.controller, id)
4305 }
4306
4307 pub(crate) async fn ship_dataflow(
4314 &mut self,
4315 dataflow: LirDataflowDescription,
4316 instance: ComputeInstanceId,
4317 target_replica: Option<ReplicaId>,
4318 ) {
4319 self.try_ship_dataflow(dataflow, instance, target_replica)
4320 .await
4321 .unwrap_or_terminate("dataflow creation cannot fail");
4322 }
4323
4324 pub(crate) async fn try_ship_dataflow(
4327 &mut self,
4328 dataflow: LirDataflowDescription,
4329 instance: ComputeInstanceId,
4330 target_replica: Option<ReplicaId>,
4331 ) -> Result<(), DataflowCreationError> {
4332 let export_ids = dataflow.exported_index_ids().collect();
4335
4336 self.controller
4337 .compute
4338 .create_dataflow(instance, dataflow, target_replica)?;
4339
4340 self.initialize_compute_read_policies(export_ids, instance, CompactionWindow::Default)
4341 .await;
4342
4343 Ok(())
4344 }
4345
4346 pub(crate) fn allow_writes(&mut self, instance: ComputeInstanceId, id: GlobalId) {
4350 self.controller
4351 .compute
4352 .allow_writes(instance, id)
4353 .unwrap_or_terminate("allow_writes cannot fail");
4354 }
4355
4356 pub(crate) async fn ship_dataflow_and_notice_builtin_table_updates(
4358 &mut self,
4359 dataflow: LirDataflowDescription,
4360 instance: ComputeInstanceId,
4361 notice_builtin_updates_fut: Option<BuiltinTableAppendNotify>,
4362 target_replica: Option<ReplicaId>,
4363 ) {
4364 if let Some(notice_builtin_updates_fut) = notice_builtin_updates_fut {
4365 let ship_dataflow_fut = self.ship_dataflow(dataflow, instance, target_replica);
4366 let ((), ()) =
4367 futures::future::join(notice_builtin_updates_fut, ship_dataflow_fut).await;
4368 } else {
4369 self.ship_dataflow(dataflow, instance, target_replica).await;
4370 }
4371 }
4372
4373 pub fn install_compute_watch_set(
4377 &mut self,
4378 conn_id: ConnectionId,
4379 objects: BTreeSet<GlobalId>,
4380 t: Timestamp,
4381 state: WatchSetResponse,
4382 ) -> Result<(), CollectionLookupError> {
4383 let ws_id = self.controller.install_compute_watch_set(objects, t)?;
4384 self.connection_watch_sets
4385 .entry(conn_id.clone())
4386 .or_default()
4387 .insert(ws_id);
4388 self.installed_watch_sets.insert(ws_id, (conn_id, state));
4389 Ok(())
4390 }
4391
4392 pub fn install_storage_watch_set(
4396 &mut self,
4397 conn_id: ConnectionId,
4398 objects: BTreeSet<GlobalId>,
4399 t: Timestamp,
4400 state: WatchSetResponse,
4401 ) -> Result<(), CollectionMissing> {
4402 let ws_id = self.controller.install_storage_watch_set(objects, t)?;
4403 self.connection_watch_sets
4404 .entry(conn_id.clone())
4405 .or_default()
4406 .insert(ws_id);
4407 self.installed_watch_sets.insert(ws_id, (conn_id, state));
4408 Ok(())
4409 }
4410
4411 pub fn cancel_pending_watchsets(&mut self, conn_id: &ConnectionId) {
4413 if let Some(ws_ids) = self.connection_watch_sets.remove(conn_id) {
4414 for ws_id in ws_ids {
4415 self.installed_watch_sets.remove(&ws_id);
4416 }
4417 }
4418 }
4419
4420 pub async fn dump(&self) -> Result<serde_json::Value, anyhow::Error> {
4424 let global_timelines: BTreeMap<_, _> = self
4430 .global_timelines
4431 .iter()
4432 .map(|(timeline, state)| (timeline.to_string(), format!("{state:?}")))
4433 .collect();
4434 let active_conns: BTreeMap<_, _> = self
4435 .active_conns
4436 .iter()
4437 .map(|(id, meta)| (id.unhandled().to_string(), format!("{meta:?}")))
4438 .collect();
4439 let txn_read_holds: BTreeMap<_, _> = self
4440 .txn_read_holds
4441 .iter()
4442 .map(|(id, capability)| (id.unhandled().to_string(), format!("{capability:?}")))
4443 .collect();
4444 let pending_linearize_read_txns: BTreeMap<_, _> = self
4445 .pending_linearize_read_txns
4446 .iter()
4447 .map(|(id, read_txn)| (id.unhandled().to_string(), format!("{read_txn:?}")))
4448 .collect();
4449
4450 Ok(serde_json::json!({
4451 "global_timelines": global_timelines,
4452 "active_conns": active_conns,
4453 "txn_read_holds": txn_read_holds,
4454 "pending_linearize_read_txns": pending_linearize_read_txns,
4455 "controller": self.controller.dump().await?,
4456 }))
4457 }
4458
4459 async fn prune_storage_usage_events_on_startup(&self, retention_period: Duration) {
4473 let item_id = self
4474 .catalog()
4475 .resolve_builtin_table(&MZ_STORAGE_USAGE_BY_SHARD);
4476 let global_id = self.catalog.get_entry(&item_id).latest_global_id();
4477 let read_ts = self.get_local_read_ts().await;
4478 let current_contents_fut = self
4479 .controller
4480 .storage_collections
4481 .snapshot(global_id, read_ts);
4482 let internal_cmd_tx = self.internal_cmd_tx.clone();
4483 spawn(|| "storage_usage_prune", async move {
4484 let mut current_contents = current_contents_fut
4485 .await
4486 .unwrap_or_terminate("cannot fail to fetch snapshot");
4487 differential_dataflow::consolidation::consolidate(&mut current_contents);
4488
4489 let cutoff_ts = u128::from(read_ts).saturating_sub(retention_period.as_millis());
4490 let mut expired = Vec::new();
4491 for (row, diff) in current_contents {
4492 assert_eq!(
4493 diff, 1,
4494 "consolidated contents should not contain retractions: ({row:#?}, {diff:#?})"
4495 );
4496 let collection_timestamp = row
4498 .unpack()
4499 .get(3)
4500 .expect("definition of mz_storage_by_shard changed")
4501 .unwrap_timestamptz();
4502 let collection_timestamp = collection_timestamp.timestamp_millis();
4503 let collection_timestamp: u128 = collection_timestamp
4504 .try_into()
4505 .expect("all collections happen after Jan 1 1970");
4506 if collection_timestamp < cutoff_ts {
4507 debug!("pruning storage event {row:?}");
4508 let builtin_update = BuiltinTableUpdate::row(item_id, row, Diff::MINUS_ONE);
4509 expired.push(builtin_update);
4510 }
4511 }
4512
4513 let _ = internal_cmd_tx.send(Message::StorageUsagePrune(expired));
4515 });
4516 }
4517
4518 async fn prune_arrangement_sizes_history_on_startup(&self) {
4527 if self.controller.read_only() {
4529 return;
4530 }
4531
4532 let retention_period = mz_adapter_types::dyncfgs::ARRANGEMENT_SIZE_HISTORY_RETENTION_PERIOD
4533 .get(self.catalog().system_config().dyncfgs());
4534 let item_id = self
4535 .catalog()
4536 .resolve_builtin_table(&mz_catalog::builtin::MZ_OBJECT_ARRANGEMENT_SIZE_HISTORY);
4537 let global_id = self.catalog.get_entry(&item_id).latest_global_id();
4538 let read_ts = self.get_local_read_ts().await;
4539 let current_contents_fut = self
4540 .controller
4541 .storage_collections
4542 .snapshot(global_id, read_ts);
4543 let internal_cmd_tx = self.internal_cmd_tx.clone();
4544 spawn(|| "arrangement_sizes_history_prune", async move {
4545 let mut current_contents = current_contents_fut
4546 .await
4547 .unwrap_or_terminate("cannot fail to fetch snapshot");
4548 differential_dataflow::consolidation::consolidate(&mut current_contents);
4549
4550 let cutoff_ts = u128::from(read_ts).saturating_sub(retention_period.as_millis());
4551 let expired =
4552 arrangement_sizes_expired_retractions(current_contents, cutoff_ts, item_id);
4553
4554 let _ = internal_cmd_tx.send(Message::ArrangementSizesPrune(expired));
4558 });
4559 }
4560
4561 fn current_credit_consumption_rate(&self, exclude_cluster: Option<ClusterId>) -> Numeric {
4562 self.catalog()
4563 .state()
4564 .current_credit_consumption_rate(exclude_cluster)
4565 }
4566}
4567
4568fn arrangement_sizes_expired_retractions(
4578 rows: impl IntoIterator<Item = (mz_repr::Row, i64)>,
4579 cutoff_ts: u128,
4580 item_id: CatalogItemId,
4581) -> Vec<BuiltinTableUpdate> {
4582 let mut expired = Vec::new();
4583 for (row, diff) in rows {
4584 if diff != 1 {
4585 soft_panic_or_log!(
4586 "consolidated contents should only contain diff 1: ({row:#?}, {diff:#?})"
4587 );
4588 }
4589 let collection_timestamp = row
4590 .unpack()
4591 .get(3)
4592 .expect("definition of mz_object_arrangement_size_history changed")
4593 .unwrap_timestamptz()
4594 .timestamp_millis();
4595 let collection_timestamp: u128 = collection_timestamp
4596 .try_into()
4597 .expect("all collections happen after Jan 1 1970");
4598 if collection_timestamp < cutoff_ts {
4599 expired.push(BuiltinTableUpdate::row(item_id, row, -Diff::from(diff)));
4600 }
4601 }
4602 expired
4603}
4604
4605#[cfg(test)]
4606impl Coordinator {
4607 #[allow(dead_code)]
4608 async fn verify_ship_dataflow_no_error(&mut self, dataflow: LirDataflowDescription) {
4609 let compute_instance = ComputeInstanceId::user(1).expect("1 is a valid ID");
4617
4618 let _: () = self.ship_dataflow(dataflow, compute_instance, None).await;
4619 }
4620}
4621
4622struct LastMessage {
4624 kind: &'static str,
4625 stmt: Option<Arc<Statement<Raw>>>,
4626}
4627
4628impl LastMessage {
4629 fn stmt_to_string(&self) -> Cow<'static, str> {
4631 self.stmt
4632 .as_ref()
4633 .map(|stmt| truncate_sql_for_logging(stmt.to_ast_string_redacted()).into())
4634 .unwrap_or(Cow::Borrowed("<none>"))
4635 }
4636}
4637
4638impl fmt::Debug for LastMessage {
4639 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4640 f.debug_struct("LastMessage")
4641 .field("kind", &self.kind)
4642 .field("stmt", &self.stmt_to_string())
4643 .finish()
4644 }
4645}
4646
4647impl Drop for LastMessage {
4648 fn drop(&mut self) {
4649 if std::thread::panicking() {
4651 eprintln!("Coordinator panicking, dumping last message\n{self:?}",);
4653 }
4654 }
4655}
4656
4657pub fn serve(
4669 Config {
4670 controller_config,
4671 controller_envd_epoch,
4672 mut storage,
4673 timestamp_oracle_url,
4674 unsafe_mode,
4675 all_features,
4676 build_info,
4677 environment_id,
4678 metrics_registry,
4679 now,
4680 secrets_controller,
4681 cloud_resource_controller,
4682 cluster_replica_sizes,
4683 builtin_system_cluster_config,
4684 builtin_catalog_server_cluster_config,
4685 builtin_probe_cluster_config,
4686 builtin_support_cluster_config,
4687 builtin_analytics_cluster_config,
4688 system_parameter_defaults,
4689 availability_zones,
4690 storage_usage_client,
4691 storage_usage_collection_interval,
4692 storage_usage_retention_period,
4693 segment_client,
4694 egress_addresses,
4695 aws_account_id,
4696 aws_privatelink_availability_zones,
4697 connection_context,
4698 connection_limit_callback,
4699 remote_system_parameters,
4700 webhook_concurrency_limit,
4701 http_host_name,
4702 tracing_handle,
4703 read_only_controllers,
4704 caught_up_trigger: clusters_caught_up_trigger,
4705 helm_chart_version,
4706 license_key,
4707 external_login_password_mz_system,
4708 force_builtin_schema_migration,
4709 }: Config,
4710) -> BoxFuture<'static, Result<(Handle, Client), AdapterError>> {
4711 async move {
4712 let coord_start = Instant::now();
4713 info!("startup: coordinator init: beginning");
4714 info!("startup: coordinator init: preamble beginning");
4715
4716 let _builtins = LazyLock::force(&BUILTINS_STATIC);
4720
4721 let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
4722 let (internal_cmd_tx, internal_cmd_rx) = mpsc::unbounded_channel();
4723 let (strict_serializable_reads_tx, strict_serializable_reads_rx) =
4724 mpsc::unbounded_channel();
4725
4726 if !availability_zones.iter().all_unique() {
4728 coord_bail!("availability zones must be unique");
4729 }
4730
4731 let aws_principal_context = match (
4732 aws_account_id,
4733 connection_context.aws_external_id_prefix.clone(),
4734 ) {
4735 (Some(aws_account_id), Some(aws_external_id_prefix)) => Some(AwsPrincipalContext {
4736 aws_account_id,
4737 aws_external_id_prefix,
4738 }),
4739 _ => None,
4740 };
4741
4742 let aws_privatelink_availability_zones = aws_privatelink_availability_zones
4743 .map(|azs_vec| BTreeSet::from_iter(azs_vec.iter().cloned()));
4744
4745 info!(
4746 "startup: coordinator init: preamble complete in {:?}",
4747 coord_start.elapsed()
4748 );
4749 let oracle_init_start = Instant::now();
4750 info!("startup: coordinator init: timestamp oracle init beginning");
4751
4752 let timestamp_oracle_config = timestamp_oracle_url
4753 .map(|url| TimestampOracleConfig::from_url(&url, &metrics_registry))
4754 .transpose()?;
4755 let mut initial_timestamps =
4756 get_initial_oracle_timestamps(×tamp_oracle_config).await?;
4757
4758 initial_timestamps
4762 .entry(Timeline::EpochMilliseconds)
4763 .or_insert_with(mz_repr::Timestamp::minimum);
4764 let mut timestamp_oracles = BTreeMap::new();
4765 for (timeline, initial_timestamp) in initial_timestamps {
4766 Coordinator::ensure_timeline_state_with_initial_time(
4767 &timeline,
4768 initial_timestamp,
4769 now.clone(),
4770 timestamp_oracle_config.clone(),
4771 &mut timestamp_oracles,
4772 read_only_controllers,
4773 )
4774 .await;
4775 }
4776
4777 let catalog_upper = storage.current_upper().await;
4781 let epoch_millis_oracle = ×tamp_oracles
4787 .get(&Timeline::EpochMilliseconds)
4788 .expect("inserted above")
4789 .oracle;
4790
4791 let boot_now: mz_repr::Timestamp = (now)().into();
4796 if catalog_upper > timeline::write_ts_upper_bound(&boot_now) {
4797 tracing::error!(
4798 %catalog_upper, %boot_now,
4799 "catalog upper is far ahead of the wall clock, so writes and \
4800 strict-serializable reads on the EpochMilliseconds timeline will block \
4801 until the clock catches up",
4802 );
4803 }
4804
4805 let mut boot_ts = if read_only_controllers {
4806 let read_ts = epoch_millis_oracle.read_ts().await;
4807 std::cmp::max(read_ts, catalog_upper)
4808 } else {
4809 epoch_millis_oracle.apply_write(catalog_upper).await;
4812 epoch_millis_oracle.write_ts().await.timestamp
4813 };
4814
4815 info!(
4816 "startup: coordinator init: timestamp oracle init complete in {:?}",
4817 oracle_init_start.elapsed()
4818 );
4819
4820 let catalog_open_start = Instant::now();
4821 info!("startup: coordinator init: catalog open beginning");
4822 let persist_client = controller_config
4823 .persist_clients
4824 .open(controller_config.persist_location.clone())
4825 .await
4826 .context("opening persist client")?;
4827 let builtin_item_migration_config =
4828 BuiltinItemMigrationConfig {
4829 persist_client: persist_client.clone(),
4830 read_only: read_only_controllers,
4831 force_migration: force_builtin_schema_migration,
4832 }
4833 ;
4834 let OpenCatalogResult {
4835 mut catalog,
4836 last_seen_version,
4837 migrated_storage_collections_0dt,
4838 new_builtin_collections,
4839 builtin_table_updates,
4840 cached_global_exprs,
4841 uncached_local_exprs,
4842 } = Catalog::open(mz_catalog::config::Config {
4843 storage,
4844 metrics_registry: &metrics_registry,
4845 state: mz_catalog::config::StateConfig {
4846 unsafe_mode,
4847 all_features,
4848 build_info,
4849 environment_id: environment_id.clone(),
4850 read_only: read_only_controllers,
4851 now: now.clone(),
4852 boot_ts: boot_ts.clone(),
4853 skip_migrations: false,
4854 cluster_replica_sizes,
4855 builtin_system_cluster_config,
4856 builtin_catalog_server_cluster_config,
4857 builtin_probe_cluster_config,
4858 builtin_support_cluster_config,
4859 builtin_analytics_cluster_config,
4860 system_parameter_defaults,
4861 remote_system_parameters,
4862 availability_zones,
4863 egress_addresses,
4864 aws_principal_context,
4865 aws_privatelink_availability_zones,
4866 connection_context,
4867 http_host_name,
4868 builtin_item_migration_config,
4869 persist_client: persist_client.clone(),
4870 enable_expression_cache_override: None,
4871 helm_chart_version,
4872 external_login_password_mz_system,
4873 license_key: license_key.clone(),
4874 },
4875 })
4876 .await?;
4877
4878 let catalog_upper = catalog.current_upper().await;
4881 boot_ts = std::cmp::max(boot_ts, catalog_upper);
4882
4883 if !read_only_controllers {
4884 epoch_millis_oracle.apply_write(boot_ts).await;
4885 }
4886
4887 info!(
4888 "startup: coordinator init: catalog open complete in {:?}",
4889 catalog_open_start.elapsed()
4890 );
4891
4892 let hydrate_migrated_mvs = ENABLE_0DT_HYDRATE_MIGRATED_BUILTIN_MVS
4903 .get(catalog.system_config().dyncfgs())
4904 && last_seen_version
4905 .as_ref()
4906 .is_none_or(|version| *version >= MIN_LEADER_VERSION_FOR_MIGRATED_MV_WRITES);
4907
4908 let coord_thread_start = Instant::now();
4909 info!("startup: coordinator init: coordinator thread start beginning");
4910
4911 let session_id = catalog.config().session_id;
4912 let start_instant = catalog.config().start_instant;
4913
4914 let (bootstrap_tx, bootstrap_rx) = oneshot::channel();
4918 let handle = TokioHandle::current();
4919
4920 let metrics = Metrics::register_into(&metrics_registry);
4921 let metrics_clone = metrics.clone();
4922 let optimizer_metrics = OptimizerMetrics::register_into(
4923 &metrics_registry,
4924 catalog.system_config().optimizer_e2e_latency_warning_threshold(),
4925 );
4926 let segment_client_clone = segment_client.clone();
4927 let coord_now = now.clone();
4928 let advance_timelines_interval =
4929 tokio::time::interval(catalog.system_config().default_timestamp_interval());
4930
4931 let clusters_caught_up_check =
4932 clusters_caught_up_trigger.map(|trigger| {
4933 let new_builtin_items = new_builtin_collections.iter().filter_map(|global_id| {
4948 let entry = catalog
4949 .state()
4950 .try_get_entry_by_global_id(global_id)
4951 .expect("new builtin collections have catalog entries");
4952 let seed = !hydrate_migrated_mvs
4953 || (entry.item().is_storage_collection()
4954 && !migrated_storage_collections_0dt.contains(&entry.id()));
4955 seed.then(|| entry.id())
4956 });
4957 let frozen_migrated_mvs = migrated_storage_collections_0dt
4958 .iter()
4959 .copied()
4960 .filter(|_| !hydrate_migrated_mvs)
4961 .filter(|id| catalog.state().get_entry(id).is_materialized_view());
4962 let mut todo: Vec<_> = new_builtin_items.chain(frozen_migrated_mvs).collect();
4963 let mut exclude_collections = BTreeSet::new();
4964 while let Some(item_id) = todo.pop() {
4965 let entry = catalog.state().get_entry(&item_id);
4966 exclude_collections.extend(entry.global_ids());
4967 todo.extend_from_slice(entry.used_by());
4968 }
4969
4970 CaughtUpCheckContext {
4971 trigger,
4972 exclude_collections,
4973 }
4974 });
4975
4976 if let Some(TimestampOracleConfig::Postgres(pg_config)) =
4977 timestamp_oracle_config.as_ref()
4978 {
4979 let pg_timestamp_oracle_params =
4982 flags::timestamp_oracle_config(catalog.system_config());
4983 pg_timestamp_oracle_params.apply(pg_config);
4984 }
4985
4986 let connection_limit_callback: Arc<dyn Fn(&SystemVars) + Send + Sync> =
4989 Arc::new(move |system_vars: &SystemVars| {
4990 let limit: u64 = system_vars.max_connections().cast_into();
4991 let superuser_reserved: u64 =
4992 system_vars.superuser_reserved_connections().cast_into();
4993
4994 let superuser_reserved = if superuser_reserved >= limit {
4999 tracing::warn!(
5000 "superuser_reserved ({superuser_reserved}) is greater than max connections ({limit})!"
5001 );
5002 limit
5003 } else {
5004 superuser_reserved
5005 };
5006
5007 (connection_limit_callback)(limit, superuser_reserved);
5008 });
5009 catalog.system_config_mut().register_callback(
5010 &mz_sql::session::vars::MAX_CONNECTIONS,
5011 Arc::clone(&connection_limit_callback),
5012 );
5013 catalog.system_config_mut().register_callback(
5014 &mz_sql::session::vars::SUPERUSER_RESERVED_CONNECTIONS,
5015 connection_limit_callback,
5016 );
5017
5018 let (group_commit_tx, group_commit_rx) = appends::notifier();
5019
5020 let parent_span = tracing::Span::current();
5021 let thread = thread::Builder::new()
5022 .stack_size(3 * stack::STACK_SIZE)
5026 .name("coordinator".to_string())
5027 .spawn(move || {
5028 let span = info_span!(parent: parent_span, "coord::coordinator").entered();
5029
5030 let controller = handle
5031 .block_on({
5032 catalog.initialize_controller(
5033 controller_config,
5034 controller_envd_epoch,
5035 read_only_controllers,
5036 )
5037 })
5038 .unwrap_or_terminate("failed to initialize storage_controller");
5039 let catalog_upper = handle.block_on(catalog.current_upper());
5042 boot_ts = std::cmp::max(boot_ts, catalog_upper);
5043 if !read_only_controllers {
5044 let epoch_millis_oracle = ×tamp_oracles
5045 .get(&Timeline::EpochMilliseconds)
5046 .expect("inserted above")
5047 .oracle;
5048 handle.block_on(epoch_millis_oracle.apply_write(boot_ts));
5049 }
5050
5051 let catalog = Arc::new(catalog);
5052 let dyncfgs = catalog.system_config().dyncfgs().clone();
5053 let max_concurrent_occ_writes =
5054 usize::cast_from(catalog.system_config().max_concurrent_occ_writes());
5055
5056 let caching_secrets_reader = CachingSecretsReader::new(secrets_controller.reader());
5057 let (group_committer_tx, group_committer_rx) = mpsc::unbounded_channel();
5058 let mut coord = Coordinator {
5059 controller,
5060 catalog,
5061 checked_create_sql: CheckedCreateSql::default(),
5062 internal_cmd_tx,
5063 group_commit_tx,
5064 reconcile_now: Arc::new(Notify::new()),
5065 group_committer_tx,
5066 strict_serializable_reads_tx,
5067 linearize_reads_notify: Arc::new(Notify::new()),
5068 global_timelines: timestamp_oracles,
5069 transient_id_gen: Arc::new(TransientIdGen::new()),
5070 active_conns: BTreeMap::new(),
5071 txn_read_holds: Default::default(),
5072 peek_registry: Arc::default(),
5073 pending_linearize_read_txns: BTreeMap::new(),
5074 serialized_ddl: LockedVecDeque::new(),
5075 active_compute_sinks: BTreeMap::new(),
5076 active_webhooks: BTreeMap::new(),
5077 active_copies: BTreeMap::new(),
5078 connection_cancel_watches: BTreeMap::new(),
5079 introspection_subscribes: BTreeMap::new(),
5080 hydration_history_replica_cursor: None,
5081 hydration_history_sweep: None,
5082 metric_sinks: BTreeMap::new(),
5083 metric_sink_plans: BTreeMap::new(),
5084 pending_writes: Vec::new(),
5085 occ_write_semaphore: Arc::new(Semaphore::new(max_concurrent_occ_writes)),
5086 advance_timelines_interval,
5087 secrets_controller,
5088 caching_secrets_reader,
5089 cloud_resource_controller,
5090 storage_usage_client,
5091 storage_usage_collection_interval,
5092 segment_client,
5093 metrics,
5094 catalog_info_metrics_registry: metrics_registry.clone(),
5095 scoped_frontend: None,
5096 optimizer_metrics,
5097 tracing_handle,
5098 statement_logging: StatementLogging::new(coord_now.clone(), &dyncfgs),
5099 webhook_concurrency_limit,
5100 timestamp_oracle_config,
5101 caught_up_check: clusters_caught_up_check,
5102 installed_watch_sets: BTreeMap::new(),
5103 connection_watch_sets: BTreeMap::new(),
5104 cluster_replica_statuses: ClusterReplicaStatuses::new(),
5105 read_only_controllers,
5106 buffered_builtin_table_updates: Some(Vec::new()),
5107 license_key,
5108 user_id_pool: IdPool::empty(),
5109 persist_client,
5110 };
5111
5112 handle.block_on(async {
5114 appends::spawn_group_committer(
5115 group_committer_rx,
5116 coord.get_local_timestamp_oracle(),
5117 coord.controller.storage.table_write_handle(),
5118 coord.catalog().upper_handle(),
5119 coord.internal_cmd_tx.clone(),
5120 coord.catalog().config().now.clone(),
5121 coord.metrics.clone(),
5122 coord.catalog().system_config().dyncfgs(),
5123 );
5124 });
5125
5126 let bootstrap = handle.block_on(async {
5127 coord
5128 .bootstrap(
5129 boot_ts,
5130 migrated_storage_collections_0dt,
5131 hydrate_migrated_mvs,
5132 builtin_table_updates,
5133 cached_global_exprs,
5134 uncached_local_exprs,
5135 )
5136 .await?;
5137 coord
5138 .controller
5139 .remove_orphaned_replicas(
5140 coord.catalog().get_next_user_replica_id().await?,
5141 coord.catalog().get_next_system_replica_id().await?,
5142 )
5143 .await
5144 .map_err(AdapterError::Orchestrator)?;
5145
5146 if let Some(retention_period) = storage_usage_retention_period {
5147 coord
5148 .prune_storage_usage_events_on_startup(retention_period)
5149 .await;
5150 }
5151
5152 coord.prune_arrangement_sizes_history_on_startup().await;
5153
5154 Ok(())
5155 });
5156 let ok = bootstrap.is_ok();
5157 drop(span);
5158 bootstrap_tx
5159 .send(bootstrap)
5160 .expect("bootstrap_rx is not dropped until it receives this message");
5161 if ok {
5162 handle.block_on(coord.serve(
5163 internal_cmd_rx,
5164 strict_serializable_reads_rx,
5165 cmd_rx,
5166 group_commit_rx,
5167 ));
5168 }
5169 })
5170 .expect("failed to create coordinator thread");
5171 match bootstrap_rx
5172 .await
5173 .expect("bootstrap_tx always sends a message or panics/halts")
5174 {
5175 Ok(()) => {
5176 info!(
5177 "startup: coordinator init: coordinator thread start complete in {:?}",
5178 coord_thread_start.elapsed()
5179 );
5180 info!(
5181 "startup: coordinator init: complete in {:?}",
5182 coord_start.elapsed()
5183 );
5184 let handle = Handle {
5185 session_id,
5186 start_instant,
5187 _thread: thread.join_on_drop(),
5188 };
5189 let client = Client::new(
5190 build_info,
5191 cmd_tx,
5192 metrics_clone,
5193 now,
5194 environment_id,
5195 segment_client_clone,
5196 );
5197 Ok((handle, client))
5198 }
5199 Err(e) => Err(e),
5200 }
5201 }
5202 .boxed()
5203}
5204
5205async fn get_initial_oracle_timestamps(
5219 timestamp_oracle_config: &Option<TimestampOracleConfig>,
5220) -> Result<BTreeMap<Timeline, Timestamp>, AdapterError> {
5221 let mut initial_timestamps = BTreeMap::new();
5222
5223 if let Some(config) = timestamp_oracle_config {
5224 let oracle_timestamps = config.get_all_timelines().await?;
5225
5226 let debug_msg = || {
5227 oracle_timestamps
5228 .iter()
5229 .map(|(timeline, ts)| format!("{:?} -> {}", timeline, ts))
5230 .join(", ")
5231 };
5232 info!(
5233 "current timestamps from the timestamp oracle: {}",
5234 debug_msg()
5235 );
5236
5237 for (timeline, ts) in oracle_timestamps {
5238 let entry = initial_timestamps
5239 .entry(Timeline::from_str(&timeline).expect("could not parse timeline"));
5240
5241 entry
5242 .and_modify(|current_ts| *current_ts = std::cmp::max(*current_ts, ts))
5243 .or_insert(ts);
5244 }
5245 } else {
5246 info!("no timestamp oracle configured!");
5247 };
5248
5249 let debug_msg = || {
5250 initial_timestamps
5251 .iter()
5252 .map(|(timeline, ts)| format!("{:?}: {}", timeline, ts))
5253 .join(", ")
5254 };
5255 info!("initial oracle timestamps: {}", debug_msg());
5256
5257 Ok(initial_timestamps)
5258}
5259
5260#[instrument]
5261pub async fn load_remote_system_parameters(
5262 storage: &mut Box<dyn OpenableDurableCatalogState>,
5263 system_parameter_sync_config: Option<SystemParameterSyncConfig>,
5264 system_parameter_sync_timeout: Duration,
5265) -> Result<RemoteSystemParameters, AdapterError> {
5266 if let Some(system_parameter_sync_config) = system_parameter_sync_config {
5267 tracing::info!("parameter sync on boot: start sync");
5268
5269 let mut params = SynchronizedParameters::new(SystemVars::default());
5309 let frontend_sync = async {
5310 let frontend =
5311 Arc::new(SystemParameterFrontend::from(&system_parameter_sync_config).await?);
5312 frontend.pull(&mut params);
5313 let ops = params
5314 .modified()
5315 .into_iter()
5316 .map(|param| {
5317 let name = param.name;
5318 let value = param.value;
5319 tracing::info!(name, value, initial = true, "sync parameter");
5320 (name, value)
5321 })
5322 .collect();
5323 tracing::info!("parameter sync on boot: end sync");
5324 Ok(RemoteSystemParameters {
5325 params: Some(ops),
5326 frontend: Some(frontend),
5327 })
5328 };
5329 if !storage.has_system_config_synced_once().await? {
5330 frontend_sync.await
5331 } else {
5332 match mz_ore::future::timeout(system_parameter_sync_timeout, frontend_sync).await {
5333 Ok(ops) => Ok(ops),
5334 Err(TimeoutError::Inner(e)) => Err(e),
5335 Err(TimeoutError::DeadlineElapsed) => {
5336 tracing::info!("parameter sync on boot: sync has timed out");
5337 Ok(RemoteSystemParameters::default())
5338 }
5339 }
5340 }
5341 } else {
5342 Ok(RemoteSystemParameters::default())
5343 }
5344}
5345
5346#[derive(Debug, Default)]
5348pub struct RemoteSystemParameters {
5349 pub params: Option<BTreeMap<String, String>>,
5352 pub frontend: Option<Arc<SystemParameterFrontend>>,
5354}
5355
5356#[derive(Debug)]
5357pub enum WatchSetResponse {
5358 StatementDependenciesReady(StatementLoggingId, StatementLifecycleEvent),
5359 AlterSinkReady(AlterSinkReadyContext),
5360 AlterMaterializedViewReady(AlterMaterializedViewReadyContext),
5361}
5362
5363#[derive(Debug)]
5364pub struct AlterSinkReadyContext {
5365 ctx: Option<ExecuteContext>,
5366 otel_ctx: OpenTelemetryContext,
5367 plan: AlterSinkPlan,
5368 plan_validity: PlanValidity,
5369 read_hold: ReadHolds,
5370}
5371
5372impl AlterSinkReadyContext {
5373 fn ctx(&mut self) -> &mut ExecuteContext {
5374 self.ctx.as_mut().expect("only cleared on drop")
5375 }
5376
5377 fn retire(mut self, result: Result<ExecuteResponse, AdapterError>) {
5378 self.ctx
5379 .take()
5380 .expect("only cleared on drop")
5381 .retire(result);
5382 }
5383}
5384
5385impl Drop for AlterSinkReadyContext {
5386 fn drop(&mut self) {
5387 if let Some(ctx) = self.ctx.take() {
5388 ctx.retire(Err(AdapterError::Canceled));
5389 }
5390 }
5391}
5392
5393#[derive(Debug)]
5394pub struct AlterMaterializedViewReadyContext {
5395 ctx: Option<ExecuteContext>,
5396 otel_ctx: OpenTelemetryContext,
5397 plan: plan::AlterMaterializedViewApplyReplacementPlan,
5398 plan_validity: PlanValidity,
5399}
5400
5401impl AlterMaterializedViewReadyContext {
5402 fn ctx(&mut self) -> &mut ExecuteContext {
5403 self.ctx.as_mut().expect("only cleared on drop")
5404 }
5405
5406 fn retire(mut self, result: Result<ExecuteResponse, AdapterError>) {
5407 self.ctx
5408 .take()
5409 .expect("only cleared on drop")
5410 .retire(result);
5411 }
5412}
5413
5414impl Drop for AlterMaterializedViewReadyContext {
5415 fn drop(&mut self) {
5416 if let Some(ctx) = self.ctx.take() {
5417 ctx.retire(Err(AdapterError::Canceled));
5418 }
5419 }
5420}
5421
5422#[derive(Debug)]
5425struct LockedVecDeque<T> {
5426 items: VecDeque<T>,
5427 lock: Arc<tokio::sync::Mutex<()>>,
5428}
5429
5430impl<T> LockedVecDeque<T> {
5431 pub fn new() -> Self {
5432 Self {
5433 items: VecDeque::new(),
5434 lock: Arc::new(tokio::sync::Mutex::new(())),
5435 }
5436 }
5437
5438 pub fn try_lock_owned(&self) -> Result<OwnedMutexGuard<()>, tokio::sync::TryLockError> {
5439 Arc::clone(&self.lock).try_lock_owned()
5440 }
5441
5442 pub fn is_empty(&self) -> bool {
5443 self.items.is_empty()
5444 }
5445
5446 pub fn push_back(&mut self, value: T) {
5447 self.items.push_back(value)
5448 }
5449
5450 pub fn pop_front(&mut self) -> Option<T> {
5451 self.items.pop_front()
5452 }
5453
5454 pub fn remove(&mut self, index: usize) -> Option<T> {
5455 self.items.remove(index)
5456 }
5457
5458 pub fn iter(&self) -> std::collections::vec_deque::Iter<'_, T> {
5459 self.items.iter()
5460 }
5461}
5462
5463#[derive(Debug)]
5464enum DeferredDdl {
5465 Statement {
5466 ctx: ExecuteContext,
5467 stmt: Arc<Statement<Raw>>,
5468 params: Params,
5469 },
5470 Commit(ddl::PendingDdlCommit),
5471}
5472
5473impl DeferredDdl {
5474 fn conn_id(&self) -> &ConnectionId {
5475 match self {
5476 Self::Statement {
5477 ctx,
5478 stmt: _,
5479 params: _,
5480 } => ctx.session().conn_id(),
5481 Self::Commit(pending) => pending.conn_id(),
5482 }
5483 }
5484}
5485
5486#[derive(Debug, Error)]
5487pub enum NetworkPolicyError {
5488 #[error("Access denied for address {0}")]
5489 AddressDenied(IpAddr),
5490 #[error("Access denied missing IP address")]
5491 MissingIp,
5492}
5493
5494pub(crate) fn validate_ip_with_policy_rules(
5495 ip: &IpAddr,
5496 rules: &Vec<NetworkPolicyRule>,
5497) -> Result<(), NetworkPolicyError> {
5498 if rules.iter().any(|r| r.address.0.contains(ip)) {
5501 Ok(())
5502 } else {
5503 Err(NetworkPolicyError::AddressDenied(ip.clone()))
5504 }
5505}
5506
5507pub(crate) fn infer_sql_type_for_catalog(
5508 hir_expr: &HirRelationExpr,
5509 mir_expr: &MirRelationExpr,
5510) -> SqlRelationType {
5511 let mut typ = hir_expr.top_level_typ();
5512 typ.backport_nullability_and_keys(&mir_expr.typ());
5513 typ
5514}
5515
5516#[cfg(test)]
5517mod execute_context_tests {
5518 use mz_sql::session::vars::{SystemVars, VarInput};
5519 use tokio::sync::{mpsc, oneshot};
5520
5521 use super::*;
5522 use crate::command::Response;
5523 use crate::session::Session;
5524 use crate::util::ClientTransmitter;
5525
5526 #[mz_ore::test(tokio::test)]
5527 async fn test_retire_completed_barrier_answers_without_scheduling() {
5528 let (client_tx, mut client_rx) = oneshot::channel();
5529 let (internal_cmd_tx, _internal_cmd_rx) = mpsc::unbounded_channel();
5530 let mut ctx = ExecuteContext::from_parts(
5531 ClientTransmitter::new(client_tx, internal_cmd_tx.clone()),
5532 internal_cmd_tx,
5533 Session::dummy(),
5534 ExecuteContextGuard::default(),
5535 );
5536
5537 ctx.delay_response_until(BuiltinTableAppendCompletion::completed());
5538 assert!(ctx.response_barriers.is_empty());
5539 ctx.retire(Ok(ExecuteResponse::StartedTransaction));
5540
5541 let response = client_rx.try_recv().expect("response must be synchronous");
5543 assert!(matches!(
5544 response.result,
5545 Ok(ExecuteResponse::StartedTransaction)
5546 ));
5547 }
5548
5549 #[mz_ore::test(tokio::test)]
5550 async fn test_retire_pending_barrier_waits_for_completion() {
5551 let (client_tx, mut client_rx) = oneshot::channel();
5552 let (internal_cmd_tx, _internal_cmd_rx) = mpsc::unbounded_channel();
5553 let (done_tx, done_rx) = oneshot::channel();
5554 let mut ctx = ExecuteContext::from_parts(
5555 ClientTransmitter::new(client_tx, internal_cmd_tx.clone()),
5556 internal_cmd_tx,
5557 Session::dummy(),
5558 ExecuteContextGuard::default(),
5559 );
5560
5561 ctx.delay_response_until(BuiltinTableAppendCompletion::new(Box::pin(async move {
5562 done_rx.await.expect("completion sender stays alive");
5563 })));
5564 ctx.delay_response_until(BuiltinTableAppendCompletion::completed());
5565 assert_eq!(ctx.response_barriers.len(), 1);
5566 ctx.retire(Ok(ExecuteResponse::StartedTransaction));
5567
5568 tokio::task::yield_now().await;
5569 assert!(matches!(
5570 client_rx.try_recv(),
5571 Err(oneshot::error::TryRecvError::Empty)
5572 ));
5573 done_tx.send(()).expect("barrier must retain its receiver");
5574 let response = tokio::time::timeout(Duration::from_secs(5), client_rx)
5575 .await
5576 .expect("response must follow completion")
5577 .expect("client must be answered");
5578 assert!(matches!(
5579 response.result,
5580 Ok(ExecuteResponse::StartedTransaction)
5581 ));
5582 }
5583
5584 fn pending_read(
5585 timestamp_context: TimestampContext,
5586 ) -> (PendingReadTxn, oneshot::Receiver<Response<ExecuteResponse>>) {
5587 let (client_tx, client_rx) = oneshot::channel();
5588 let (internal_cmd_tx, _internal_cmd_rx) = mpsc::unbounded_channel();
5589 let mut session = Session::dummy();
5590 session
5591 .vars_mut()
5592 .set_default("application_name", VarInput::Flat("session"))
5593 .expect("valid default");
5594 session
5595 .vars_mut()
5596 .set(
5597 &SystemVars::new(),
5598 "application_name",
5599 VarInput::Flat("transaction"),
5600 true,
5601 )
5602 .expect("valid local value");
5603 let ctx = ExecuteContext::from_parts(
5604 ClientTransmitter::new(client_tx, internal_cmd_tx.clone()),
5605 internal_cmd_tx,
5606 session,
5607 ExecuteContextGuard::default(),
5608 );
5609 (
5610 PendingReadTxn {
5611 txn: PendingTxn {
5612 ctx,
5613 response: Ok(PendingTxnResponse::Committed {
5614 params: BTreeMap::from([("retained", "value".into())]),
5615 }),
5616 action: EndTransactionAction::Commit,
5617 },
5618 timestamp_context,
5619 created: Instant::now() - Duration::from_secs(1),
5620 num_requeues: 0,
5621 otel_ctx: OpenTelemetryContext::obtain(),
5622 },
5623 client_rx,
5624 )
5625 }
5626
5627 fn timestamp_context(chosen_ts: u64, oracle_ts: Option<u64>) -> TimestampContext {
5628 TimestampContext::TimelineTimestamp {
5629 timeline: Timeline::EpochMilliseconds,
5630 chosen_ts: chosen_ts.into(),
5631 oracle_ts: oracle_ts.map(Into::into),
5632 }
5633 }
5634
5635 #[mz_ore::test(tokio::test)]
5636 async fn test_ready_read_finishes_without_scheduling() {
5637 for context in [
5638 TimestampContext::NoTimestamp,
5639 timestamp_context(u64::MAX, None),
5640 timestamp_context(0, Some(0)),
5641 timestamp_context(99, Some(100)),
5642 timestamp_context(100, Some(100)),
5643 timestamp_context(u64::MAX, Some(u64::MAX)),
5644 ] {
5645 let metrics = Metrics::register_into(&MetricsRegistry::new());
5646 let (pending, mut client_rx) = pending_read(context.clone());
5647
5648 assert!(pending.try_finish_read(&metrics).is_none(), "{context:?}");
5649 let response = client_rx.try_recv().expect("response must be synchronous");
5651 assert_eq!(response.session.vars().application_name(), "session");
5652 let ExecuteResponse::TransactionCommitted { params } =
5653 response.result.expect("commit succeeds")
5654 else {
5655 panic!("expected commit response");
5656 };
5657 assert_eq!(
5658 params.get("application_name").map(String::as_str),
5659 Some("session")
5660 );
5661 assert_eq!(params.get("retained").map(String::as_str), Some("value"));
5662 assert_eq!(metrics.linearize_read_fast_path.get(), 1);
5663 let histogram = metrics
5664 .linearize_message_seconds
5665 .with_label_values(&["read", "true"]);
5666 assert_eq!(histogram.get_sample_count(), 1);
5667 assert!(histogram.get_sample_sum() >= 1.0);
5668 }
5669 }
5670
5671 #[mz_ore::test(tokio::test)]
5672 async fn test_ready_read_rollback_finalizes_session() {
5673 let metrics = Metrics::register_into(&MetricsRegistry::new());
5674 let (mut pending, mut client_rx) = pending_read(timestamp_context(100, Some(100)));
5675 let txn = &mut pending.txn;
5676 txn.action = EndTransactionAction::Rollback;
5677 txn.response = Ok(PendingTxnResponse::Rolledback {
5678 params: BTreeMap::new(),
5679 });
5680
5681 assert!(pending.try_finish_read(&metrics).is_none());
5682 let response = client_rx.try_recv().expect("response must be synchronous");
5683 assert_eq!(response.session.vars().application_name(), "session");
5684 let ExecuteResponse::TransactionRolledBack { params } =
5685 response.result.expect("rollback succeeds")
5686 else {
5687 panic!("expected rollback response");
5688 };
5689 assert_eq!(
5690 params.get("application_name").map(String::as_str),
5691 Some("session")
5692 );
5693 }
5694
5695 #[mz_ore::test(tokio::test)]
5696 async fn test_future_read_remains_pending() {
5697 for (chosen, oracle) in [(1, 0), (101, 100), (u64::MAX, u64::MAX - 1)] {
5698 let metrics = Metrics::register_into(&MetricsRegistry::new());
5699 let context = timestamp_context(chosen, Some(oracle));
5700 let (pending, mut client_rx) = pending_read(context.clone());
5701 let created = pending.created;
5702 let pending = pending
5703 .try_finish_read(&metrics)
5704 .expect("future read must wait");
5705
5706 assert_eq!(pending.timestamp_context, context);
5707 assert_eq!(pending.created, created);
5708 assert_eq!(pending.num_requeues, 0);
5709 assert_eq!(
5710 pending.timestamp_to_linearize(),
5711 Some((&Timeline::EpochMilliseconds, &Timestamp::from(chosen)))
5712 );
5713 assert!(matches!(
5714 client_rx.try_recv(),
5715 Err(oneshot::error::TryRecvError::Empty)
5716 ));
5717 assert_eq!(metrics.linearize_read_fast_path.get(), 0);
5718 assert_eq!(
5719 metrics
5720 .linearize_message_seconds
5721 .with_label_values(&["read", "true"])
5722 .get_sample_count(),
5723 0
5724 );
5725 let ctx = pending.take_context();
5726 assert_eq!(ctx.session().vars().application_name(), "transaction");
5727 ctx.retire(Err(AdapterError::Canceled));
5728 assert!(matches!(
5729 client_rx.try_recv().expect("cancellation responds").result,
5730 Err(AdapterError::Canceled)
5731 ));
5732 }
5733 }
5734
5735 #[mz_ore::test(tokio::test)]
5736 async fn test_ready_read_preserves_response_barrier() {
5737 let metrics = Metrics::register_into(&MetricsRegistry::new());
5738 let (mut pending, mut client_rx) = pending_read(timestamp_context(100, Some(100)));
5739 let (done_tx, done_rx) = oneshot::channel();
5740 let txn = &mut pending.txn;
5741 txn.ctx
5742 .delay_response_until(BuiltinTableAppendCompletion::new(Box::pin(async move {
5743 done_rx.await.expect("completion sender stays alive");
5744 })));
5745
5746 assert!(pending.try_finish_read(&metrics).is_none());
5747 tokio::task::yield_now().await;
5748 assert!(matches!(
5749 client_rx.try_recv(),
5750 Err(oneshot::error::TryRecvError::Empty)
5751 ));
5752 done_tx.send(()).expect("barrier retains receiver");
5753 let response = tokio::time::timeout(Duration::from_secs(5), client_rx)
5754 .await
5755 .expect("response follows completion")
5756 .expect("client answered");
5757 assert!(matches!(
5758 response.result,
5759 Ok(ExecuteResponse::TransactionCommitted { .. })
5760 ));
5761 assert_eq!(response.session.vars().application_name(), "session");
5762 assert_eq!(metrics.linearize_read_fast_path.get(), 1);
5763 }
5764
5765 #[mz_ore::test(tokio::test)]
5766 async fn test_applied_write_linearizes_local_reads_up_to_it() {
5767 let local = Timeline::EpochMilliseconds;
5768 let applied_ts = Timestamp::from(100u64);
5769 for (context, expected) in [
5770 (TimestampContext::NoTimestamp, true),
5771 (timestamp_context(100, Some(100)), true),
5772 (timestamp_context(99, Some(50)), true),
5773 (timestamp_context(100, Some(50)), true),
5774 (timestamp_context(101, Some(50)), false),
5775 (
5776 TimestampContext::TimelineTimestamp {
5777 timeline: Timeline::User("other".into()),
5778 chosen_ts: 99.into(),
5779 oracle_ts: Some(50.into()),
5780 },
5781 false,
5782 ),
5783 ] {
5784 let (pending, _client_rx) = pending_read(context.clone());
5785 assert_eq!(
5786 pending.linearized_by(&local, &applied_ts),
5787 expected,
5788 "{context:?}"
5789 );
5790 }
5791 }
5792
5793 #[mz_ore::test(tokio::test)]
5794 async fn test_queued_read_preserves_requeue_metric() {
5795 let metrics = Metrics::register_into(&MetricsRegistry::new());
5796 let (mut pending, mut client_rx) = pending_read(TimestampContext::NoTimestamp);
5797 pending.num_requeues = 1;
5798 pending.finish_with_metrics(&metrics, Instant::now());
5799
5800 assert!(matches!(
5801 client_rx.try_recv().expect("queued read responds").result,
5802 Ok(ExecuteResponse::TransactionCommitted { .. })
5803 ));
5804 assert_eq!(metrics.linearize_read_fast_path.get(), 0);
5805 assert_eq!(
5806 metrics
5807 .linearize_message_seconds
5808 .with_label_values(&["read", "false"])
5809 .get_sample_count(),
5810 1
5811 );
5812 assert_eq!(
5813 metrics
5814 .linearize_message_seconds
5815 .with_label_values(&["read", "true"])
5816 .get_sample_count(),
5817 0
5818 );
5819 }
5820
5821 #[mz_ore::test]
5824 fn test_retire_answers_client_when_runtime_shuts_down() {
5825 let runtime = tokio::runtime::Runtime::new().expect("can build runtime");
5826
5827 let (client_tx, mut client_rx) = oneshot::channel();
5828 let (internal_cmd_tx, _internal_cmd_rx) = mpsc::unbounded_channel();
5829
5830 runtime.block_on(async {
5831 let ctx = ExecuteContext::from_parts_with_response_barriers(
5832 ClientTransmitter::new(client_tx, internal_cmd_tx.clone()),
5833 internal_cmd_tx,
5834 Session::dummy(),
5835 ExecuteContextGuard::default(),
5836 vec![Box::pin(std::future::pending())],
5838 );
5839 ctx.retire(Ok(ExecuteResponse::StartedTransaction));
5840 });
5841
5842 drop(runtime);
5843
5844 let response = client_rx.try_recv().expect("client must be answered");
5845 assert!(
5846 matches!(response.result, Err(AdapterError::Internal(_))),
5847 "expected an internal error, got {:?}",
5848 response.result
5849 );
5850 }
5851}
5852
5853#[cfg(test)]
5854mod id_pool_tests {
5855 use super::IdPool;
5856
5857 #[mz_ore::test]
5858 fn test_empty_pool() {
5859 let mut pool = IdPool::empty();
5860 assert_eq!(pool.remaining(), 0);
5861 assert_eq!(pool.allocate(), None);
5862 assert_eq!(pool.allocate_many(1), None);
5863 }
5864
5865 #[mz_ore::test]
5866 fn test_allocate_single() {
5867 let mut pool = IdPool::empty();
5868 pool.refill(10, 13);
5869 assert_eq!(pool.remaining(), 3);
5870 assert_eq!(pool.allocate(), Some(10));
5871 assert_eq!(pool.allocate(), Some(11));
5872 assert_eq!(pool.allocate(), Some(12));
5873 assert_eq!(pool.remaining(), 0);
5874 assert_eq!(pool.allocate(), None);
5875 }
5876
5877 #[mz_ore::test]
5878 fn test_allocate_many() {
5879 let mut pool = IdPool::empty();
5880 pool.refill(100, 105);
5881 assert_eq!(pool.allocate_many(3), Some(vec![100, 101, 102]));
5882 assert_eq!(pool.remaining(), 2);
5883 assert_eq!(pool.allocate_many(3), None);
5885 assert_eq!(pool.allocate_many(2), Some(vec![103, 104]));
5887 assert_eq!(pool.remaining(), 0);
5888 }
5889
5890 #[mz_ore::test]
5891 fn test_allocate_many_zero() {
5892 let mut pool = IdPool::empty();
5893 pool.refill(1, 5);
5894 assert_eq!(pool.allocate_many(0), Some(vec![]));
5895 assert_eq!(pool.remaining(), 4);
5896 }
5897
5898 #[mz_ore::test]
5899 fn test_refill_resets_pool() {
5900 let mut pool = IdPool::empty();
5901 pool.refill(0, 2);
5902 assert_eq!(pool.allocate(), Some(0));
5903 pool.refill(50, 52);
5905 assert_eq!(pool.allocate(), Some(50));
5906 assert_eq!(pool.allocate(), Some(51));
5907 assert_eq!(pool.allocate(), None);
5908 }
5909
5910 #[mz_ore::test]
5911 fn test_mixed_allocate_and_allocate_many() {
5912 let mut pool = IdPool::empty();
5913 pool.refill(0, 10);
5914 assert_eq!(pool.allocate(), Some(0));
5915 assert_eq!(pool.allocate_many(3), Some(vec![1, 2, 3]));
5916 assert_eq!(pool.allocate(), Some(4));
5917 assert_eq!(pool.remaining(), 5);
5918 }
5919
5920 #[mz_ore::test]
5921 #[should_panic(expected = "invalid pool range")]
5922 fn test_refill_invalid_range_panics() {
5923 let mut pool = IdPool::empty();
5924 pool.refill(10, 5);
5925 }
5926}
5927
5928#[cfg(test)]
5929mod arrangement_sizes_pruner_tests {
5930 use mz_repr::catalog_item_id::CatalogItemId;
5931 use mz_repr::{Datum, Row};
5932
5933 use super::arrangement_sizes_expired_retractions;
5934
5935 fn history_row(ts_ms: i64) -> Row {
5939 let dt = mz_ore::now::to_datetime(ts_ms.try_into().expect("non-negative"));
5940 Row::pack_slice(&[
5941 Datum::String("r1"),
5942 Datum::String("u1"),
5943 Datum::Int64(123),
5944 Datum::TimestampTz(dt.try_into().expect("fits in TimestampTz")),
5945 ])
5946 }
5947
5948 fn item_id() -> CatalogItemId {
5949 CatalogItemId::User(42)
5951 }
5952
5953 #[mz_ore::test]
5954 fn empty_input_produces_no_retractions() {
5955 let out = arrangement_sizes_expired_retractions(Vec::new(), 1_000, item_id());
5956 assert!(out.is_empty());
5957 }
5958
5959 #[mz_ore::test]
5960 fn retracts_only_rows_strictly_before_cutoff() {
5961 let rows = vec![
5964 (history_row(100), 1),
5965 (history_row(500), 1),
5966 (history_row(1_000), 1), (history_row(5_000), 1),
5968 ];
5969 let out = arrangement_sizes_expired_retractions(rows, 1_000, item_id());
5970 assert_eq!(out.len(), 2);
5971 }
5972
5973 #[mz_ore::test]
5974 #[should_panic(expected = "consolidated contents should only contain diff 1")]
5975 fn retraction_in_input_panics() {
5976 let rows = vec![(history_row(100), -1)];
5977 let _ = arrangement_sizes_expired_retractions(rows, 1_000, item_id());
5978 }
5979}