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::{Either, 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::{
95 USER_ID_POOL_BATCH_SIZE, WITH_0DT_DEPLOYMENT_CAUGHT_UP_CHECK_INTERVAL,
96};
97use mz_auth::password::Password;
98use mz_build_info::BuildInfo;
99use mz_catalog::builtin::{BUILTINS, BUILTINS_STATIC, MZ_AUDIT_EVENTS, MZ_STORAGE_USAGE_BY_SHARD};
100use mz_catalog::config::{AwsPrincipalContext, BuiltinItemMigrationConfig, ClusterReplicaSizeMap};
101use mz_catalog::durable::{AuditLogIterator, OpenableDurableCatalogState};
102use mz_catalog::expr_cache::{GlobalExpressions, LocalExpressions};
103use mz_catalog::memory::objects::{
104 CatalogEntry, CatalogItem, ClusterReplicaProcessStatus, ClusterVariantManaged, Connection,
105 DataSourceDesc, StateDiff, StateUpdate, StateUpdateKind, Table, TableDataSource,
106};
107use mz_cloud_resources::{CloudResourceController, VpcEndpointConfig, VpcEndpointEvent};
108use mz_compute_client::as_of_selection;
109use mz_compute_client::controller::error::{
110 CollectionLookupError, CollectionMissing, DataflowCreationError, InstanceMissing,
111};
112use mz_compute_types::ComputeInstanceId;
113use mz_compute_types::dataflows::DataflowDescription;
114use mz_compute_types::plan::Plan;
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_expr::{MapFilterProject, MirRelationExpr, OptimizedMirRelationExpr, RowSetFinishing};
121use mz_license_keys::ValidatedLicenseKey;
122use mz_orchestrator::OfflineReason;
123use mz_ore::cast::{CastFrom, CastInto, CastLossy};
124use mz_ore::channel::trigger::Trigger;
125use mz_ore::future::TimeoutError;
126use mz_ore::metrics::MetricsRegistry;
127use mz_ore::now::{EpochMillis, NowFn};
128use mz_ore::task::{JoinHandle, spawn};
129use mz_ore::thread::JoinHandleExt;
130use mz_ore::tracing::{OpenTelemetryContext, TracingHandle};
131use mz_ore::url::SensitiveUrl;
132use mz_ore::{
133 assert_none, instrument, soft_assert_eq_or_log, soft_assert_or_log, soft_panic_or_log, stack,
134};
135use mz_persist_client::PersistClient;
136use mz_persist_client::batch::ProtoBatch;
137use mz_persist_client::usage::{ShardsUsageReferenced, StorageUsageClient};
138use mz_repr::adt::numeric::Numeric;
139use mz_repr::explain::{ExplainConfig, ExplainFormat};
140use mz_repr::global_id::TransientIdGen;
141use mz_repr::optimize::{OptimizerFeatures, OverrideFrom};
142use mz_repr::role_id::RoleId;
143use mz_repr::{CatalogItemId, Diff, GlobalId, RelationDesc, SqlRelationType, Timestamp};
144use mz_secrets::cache::CachingSecretsReader;
145use mz_secrets::{SecretsController, SecretsReader};
146use mz_sql::ast::{Raw, Statement};
147use mz_sql::catalog::{CatalogCluster, EnvironmentId};
148use mz_sql::names::{QualifiedItemName, ResolvedIds, SchemaSpecifier};
149use mz_sql::optimizer_metrics::OptimizerMetrics;
150use mz_sql::plan::{
151 self, AlterSinkPlan, ConnectionDetails, CreateConnectionPlan, HirRelationExpr,
152 NetworkPolicyRule, OnTimeoutAction, Params, QueryWhen,
153};
154use mz_sql::session::user::User;
155use mz_sql::session::vars::{MAX_CREDIT_CONSUMPTION_RATE, SystemVars, Var};
156use mz_sql_parser::ast::ExplainStage;
157use mz_sql_parser::ast::display::AstDisplay;
158use mz_storage_client::client::TableData;
159use mz_storage_client::controller::{CollectionDescription, DataSource, ExportDescription};
160use mz_storage_types::connections::Connection as StorageConnection;
161use mz_storage_types::connections::ConnectionContext;
162use mz_storage_types::connections::inline::{IntoInlineConnection, ReferencedConnection};
163use mz_storage_types::read_holds::ReadHold;
164use mz_storage_types::sinks::{S3SinkFormat, StorageSinkDesc};
165use mz_storage_types::sources::kafka::KAFKA_PROGRESS_DESC;
166use mz_storage_types::sources::{IngestionDescription, SourceExport, Timeline};
167use mz_timestamp_oracle::{TimestampOracleConfig, WriteTimestamp};
168use mz_transform::dataflow::DataflowMetainfo;
169use opentelemetry::trace::TraceContextExt;
170use serde::Serialize;
171use thiserror::Error;
172use timely::progress::{Antichain, Timestamp as _};
173use tokio::runtime::Handle as TokioHandle;
174use tokio::select;
175use tokio::sync::{OwnedMutexGuard, mpsc, oneshot, watch};
176use tokio::time::{Interval, MissedTickBehavior};
177use tracing::{Instrument, Level, Span, debug, info, info_span, span, warn};
178use tracing_opentelemetry::OpenTelemetrySpanExt;
179use uuid::Uuid;
180
181use crate::active_compute_sink::{ActiveComputeSink, ActiveCopyFrom};
182use crate::catalog::{BuiltinTableUpdate, Catalog, OpenCatalogResult};
183use crate::client::{Client, Handle};
184use crate::command::{Command, ExecuteResponse};
185use crate::config::{SynchronizedParameters, SystemParameterFrontend, SystemParameterSyncConfig};
186use crate::coord::appends::{
187 BuiltinTableAppendNotify, DeferredOp, GroupCommitPermit, PendingWriteTxn,
188};
189use crate::coord::caught_up::CaughtUpCheckContext;
190use crate::coord::cluster_scheduling::SchedulingDecision;
191use crate::coord::id_bundle::CollectionIdBundle;
192use crate::coord::introspection::IntrospectionSubscribe;
193use crate::coord::peek::PendingPeek;
194use crate::coord::statement_logging::StatementLogging;
195use crate::coord::timeline::{TimelineContext, TimelineState};
196use crate::coord::timestamp_selection::{TimestampContext, TimestampDetermination};
197use crate::coord::validity::PlanValidity;
198use crate::error::AdapterError;
199use crate::explain::insights::PlanInsightsContext;
200use crate::explain::optimizer_trace::{DispatchGuard, OptimizerTrace};
201use crate::metrics::Metrics;
202use crate::optimize::dataflows::{ComputeInstanceSnapshot, DataflowBuilder};
203use crate::optimize::{self, Optimize, OptimizerConfig};
204use crate::session::{EndTransactionAction, Session};
205use crate::statement_logging::{
206 StatementEndedExecutionReason, StatementLifecycleEvent, StatementLoggingId,
207};
208use crate::util::{ClientTransmitter, ResultExt, sort_topological};
209use crate::webhook::{WebhookAppenderInvalidator, WebhookConcurrencyLimiter};
210use crate::{AdapterNotice, ReadHolds, flags};
211
212pub(crate) mod appends;
213pub(crate) mod catalog_serving;
214pub(crate) mod cluster_scheduling;
215pub(crate) mod consistency;
216pub(crate) mod id_bundle;
217pub(crate) mod in_memory_oracle;
218pub(crate) mod peek;
219pub(crate) mod read_policy;
220pub(crate) mod sequencer;
221pub(crate) mod statement_logging;
222pub(crate) mod timeline;
223pub(crate) mod timestamp_selection;
224
225pub mod catalog_implications;
226mod caught_up;
227mod command_handler;
228mod ddl;
229mod indexes;
230mod introspection;
231mod message_handler;
232mod privatelink_status;
233mod sql;
234mod validity;
235
236#[derive(Debug)]
262pub(crate) struct IdPool {
263 next: u64,
264 upper: u64,
265}
266
267impl IdPool {
268 pub fn empty() -> Self {
270 IdPool { next: 0, upper: 0 }
271 }
272
273 pub fn allocate(&mut self) -> Option<u64> {
275 if self.next < self.upper {
276 let id = self.next;
277 self.next += 1;
278 Some(id)
279 } else {
280 None
281 }
282 }
283
284 pub fn allocate_many(&mut self, n: u64) -> Option<Vec<u64>> {
287 if self.remaining() >= n {
288 let ids = (self.next..self.next + n).collect();
289 self.next += n;
290 Some(ids)
291 } else {
292 None
293 }
294 }
295
296 pub fn remaining(&self) -> u64 {
298 self.upper - self.next
299 }
300
301 pub fn refill(&mut self, next: u64, upper: u64) {
303 assert!(next <= upper, "invalid pool range: {next}..{upper}");
304 self.next = next;
305 self.upper = upper;
306 }
307}
308
309#[derive(Debug)]
310pub enum Message {
311 Command(OpenTelemetryContext, Command),
312 ControllerReady {
313 controller: ControllerReadiness,
314 },
315 PurifiedStatementReady(PurifiedStatementReady),
316 CreateConnectionValidationReady(CreateConnectionValidationReady),
317 AlterConnectionValidationReady(AlterConnectionValidationReady),
318 TryDeferred {
319 conn_id: ConnectionId,
321 acquired_lock: Option<(CatalogItemId, tokio::sync::OwnedMutexGuard<()>)>,
331 },
332 GroupCommitInitiate(Span, Option<GroupCommitPermit>),
334 DeferredStatementReady,
335 AdvanceTimelines,
336 ClusterEvent(ClusterEvent),
337 CancelPendingPeeks {
338 conn_id: ConnectionId,
339 },
340 LinearizeReads,
341 StagedBatches {
342 conn_id: ConnectionId,
343 table_id: CatalogItemId,
344 batches: Vec<Result<ProtoBatch, String>>,
345 },
346 StorageUsageSchedule,
347 StorageUsageFetch,
348 StorageUsageUpdate(ShardsUsageReferenced),
349 StorageUsagePrune(Vec<BuiltinTableUpdate>),
350 RetireExecute {
353 data: ExecuteContextExtra,
354 otel_ctx: OpenTelemetryContext,
355 reason: StatementEndedExecutionReason,
356 },
357 ExecuteSingleStatementTransaction {
358 ctx: ExecuteContext,
359 otel_ctx: OpenTelemetryContext,
360 stmt: Arc<Statement<Raw>>,
361 params: mz_sql::plan::Params,
362 },
363 PeekStageReady {
364 ctx: ExecuteContext,
365 span: Span,
366 stage: PeekStage,
367 },
368 CreateIndexStageReady {
369 ctx: ExecuteContext,
370 span: Span,
371 stage: CreateIndexStage,
372 },
373 CreateViewStageReady {
374 ctx: ExecuteContext,
375 span: Span,
376 stage: CreateViewStage,
377 },
378 CreateMaterializedViewStageReady {
379 ctx: ExecuteContext,
380 span: Span,
381 stage: CreateMaterializedViewStage,
382 },
383 SubscribeStageReady {
384 ctx: ExecuteContext,
385 span: Span,
386 stage: SubscribeStage,
387 },
388 IntrospectionSubscribeStageReady {
389 span: Span,
390 stage: IntrospectionSubscribeStage,
391 },
392 SecretStageReady {
393 ctx: ExecuteContext,
394 span: Span,
395 stage: SecretStage,
396 },
397 ClusterStageReady {
398 ctx: ExecuteContext,
399 span: Span,
400 stage: ClusterStage,
401 },
402 ExplainTimestampStageReady {
403 ctx: ExecuteContext,
404 span: Span,
405 stage: ExplainTimestampStage,
406 },
407 DrainStatementLog,
408 PrivateLinkVpcEndpointEvents(Vec<VpcEndpointEvent>),
409 CheckSchedulingPolicies,
410
411 SchedulingDecisions(Vec<(&'static str, Vec<(ClusterId, SchedulingDecision)>)>),
416}
417
418impl Message {
419 pub const fn kind(&self) -> &'static str {
421 match self {
422 Message::Command(_, msg) => match msg {
423 Command::CatalogSnapshot { .. } => "command-catalog_snapshot",
424 Command::Startup { .. } => "command-startup",
425 Command::Execute { .. } => "command-execute",
426 Command::Commit { .. } => "command-commit",
427 Command::CancelRequest { .. } => "command-cancel_request",
428 Command::PrivilegedCancelRequest { .. } => "command-privileged_cancel_request",
429 Command::GetWebhook { .. } => "command-get_webhook",
430 Command::GetSystemVars { .. } => "command-get_system_vars",
431 Command::SetSystemVars { .. } => "command-set_system_vars",
432 Command::Terminate { .. } => "command-terminate",
433 Command::RetireExecute { .. } => "command-retire_execute",
434 Command::CheckConsistency { .. } => "command-check_consistency",
435 Command::Dump { .. } => "command-dump",
436 Command::AuthenticatePassword { .. } => "command-auth_check",
437 Command::AuthenticateGetSASLChallenge { .. } => "command-auth_get_sasl_challenge",
438 Command::AuthenticateVerifySASLProof { .. } => "command-auth_verify_sasl_proof",
439 Command::CheckRoleCanLogin { .. } => "command-check_role_can_login",
440 Command::GetComputeInstanceClient { .. } => "get-compute-instance-client",
441 Command::GetOracle { .. } => "get-oracle",
442 Command::DetermineRealTimeRecentTimestamp { .. } => {
443 "determine-real-time-recent-timestamp"
444 }
445 Command::GetTransactionReadHoldsBundle { .. } => {
446 "get-transaction-read-holds-bundle"
447 }
448 Command::StoreTransactionReadHolds { .. } => "store-transaction-read-holds",
449 Command::ExecuteSlowPathPeek { .. } => "execute-slow-path-peek",
450 Command::ExecuteSubscribe { .. } => "execute-subscribe",
451 Command::CopyToPreflight { .. } => "copy-to-preflight",
452 Command::ExecuteCopyTo { .. } => "execute-copy-to",
453 Command::ExecuteSideEffectingFunc { .. } => "execute-side-effecting-func",
454 Command::RegisterFrontendPeek { .. } => "register-frontend-peek",
455 Command::UnregisterFrontendPeek { .. } => "unregister-frontend-peek",
456 Command::ExplainTimestamp { .. } => "explain-timestamp",
457 Command::FrontendStatementLogging(..) => "frontend-statement-logging",
458 Command::StartCopyFromStdin { .. } => "start-copy-from-stdin",
459 Command::InjectAuditEvents { .. } => "inject-audit-events",
460 },
461 Message::ControllerReady {
462 controller: ControllerReadiness::Compute,
463 } => "controller_ready(compute)",
464 Message::ControllerReady {
465 controller: ControllerReadiness::Storage,
466 } => "controller_ready(storage)",
467 Message::ControllerReady {
468 controller: ControllerReadiness::Metrics,
469 } => "controller_ready(metrics)",
470 Message::ControllerReady {
471 controller: ControllerReadiness::Internal,
472 } => "controller_ready(internal)",
473 Message::PurifiedStatementReady(_) => "purified_statement_ready",
474 Message::CreateConnectionValidationReady(_) => "create_connection_validation_ready",
475 Message::TryDeferred { .. } => "try_deferred",
476 Message::GroupCommitInitiate(..) => "group_commit_initiate",
477 Message::AdvanceTimelines => "advance_timelines",
478 Message::ClusterEvent(_) => "cluster_event",
479 Message::CancelPendingPeeks { .. } => "cancel_pending_peeks",
480 Message::LinearizeReads => "linearize_reads",
481 Message::StagedBatches { .. } => "staged_batches",
482 Message::StorageUsageSchedule => "storage_usage_schedule",
483 Message::StorageUsageFetch => "storage_usage_fetch",
484 Message::StorageUsageUpdate(_) => "storage_usage_update",
485 Message::StorageUsagePrune(_) => "storage_usage_prune",
486 Message::RetireExecute { .. } => "retire_execute",
487 Message::ExecuteSingleStatementTransaction { .. } => {
488 "execute_single_statement_transaction"
489 }
490 Message::PeekStageReady { .. } => "peek_stage_ready",
491 Message::ExplainTimestampStageReady { .. } => "explain_timestamp_stage_ready",
492 Message::CreateIndexStageReady { .. } => "create_index_stage_ready",
493 Message::CreateViewStageReady { .. } => "create_view_stage_ready",
494 Message::CreateMaterializedViewStageReady { .. } => {
495 "create_materialized_view_stage_ready"
496 }
497 Message::SubscribeStageReady { .. } => "subscribe_stage_ready",
498 Message::IntrospectionSubscribeStageReady { .. } => {
499 "introspection_subscribe_stage_ready"
500 }
501 Message::SecretStageReady { .. } => "secret_stage_ready",
502 Message::ClusterStageReady { .. } => "cluster_stage_ready",
503 Message::DrainStatementLog => "drain_statement_log",
504 Message::AlterConnectionValidationReady(..) => "alter_connection_validation_ready",
505 Message::PrivateLinkVpcEndpointEvents(_) => "private_link_vpc_endpoint_events",
506 Message::CheckSchedulingPolicies => "check_scheduling_policies",
507 Message::SchedulingDecisions { .. } => "scheduling_decision",
508 Message::DeferredStatementReady => "deferred_statement_ready",
509 }
510 }
511}
512
513#[derive(Debug)]
515pub enum ControllerReadiness {
516 Storage,
518 Compute,
520 Metrics,
522 Internal,
524}
525
526#[derive(Derivative)]
527#[derivative(Debug)]
528pub struct BackgroundWorkResult<T> {
529 #[derivative(Debug = "ignore")]
530 pub ctx: ExecuteContext,
531 pub result: Result<T, AdapterError>,
532 pub params: Params,
533 pub plan_validity: PlanValidity,
534 pub original_stmt: Arc<Statement<Raw>>,
535 pub otel_ctx: OpenTelemetryContext,
536}
537
538pub type PurifiedStatementReady = BackgroundWorkResult<mz_sql::pure::PurifiedStatement>;
539
540#[derive(Derivative)]
541#[derivative(Debug)]
542pub struct ValidationReady<T> {
543 #[derivative(Debug = "ignore")]
544 pub ctx: ExecuteContext,
545 pub result: Result<T, AdapterError>,
546 pub resolved_ids: ResolvedIds,
547 pub connection_id: CatalogItemId,
548 pub connection_gid: GlobalId,
549 pub plan_validity: PlanValidity,
550 pub otel_ctx: OpenTelemetryContext,
551}
552
553pub type CreateConnectionValidationReady = ValidationReady<CreateConnectionPlan>;
554pub type AlterConnectionValidationReady = ValidationReady<Connection>;
555
556#[derive(Debug)]
557pub enum PeekStage {
558 LinearizeTimestamp(PeekStageLinearizeTimestamp),
560 RealTimeRecency(PeekStageRealTimeRecency),
561 TimestampReadHold(PeekStageTimestampReadHold),
562 Optimize(PeekStageOptimize),
563 Finish(PeekStageFinish),
565 ExplainPlan(PeekStageExplainPlan),
567 ExplainPushdown(PeekStageExplainPushdown),
568 CopyToPreflight(PeekStageCopyTo),
570 CopyToDataflow(PeekStageCopyTo),
572}
573
574#[derive(Debug)]
575pub struct CopyToContext {
576 pub desc: RelationDesc,
578 pub uri: Uri,
580 pub connection: StorageConnection<ReferencedConnection>,
582 pub connection_id: CatalogItemId,
584 pub format: S3SinkFormat,
586 pub max_file_size: u64,
588 pub output_batch_count: Option<u64>,
593}
594
595#[derive(Debug)]
596pub struct PeekStageLinearizeTimestamp {
597 validity: PlanValidity,
598 plan: mz_sql::plan::SelectPlan,
599 max_query_result_size: Option<u64>,
600 source_ids: BTreeSet<GlobalId>,
601 target_replica: Option<ReplicaId>,
602 timeline_context: TimelineContext,
603 optimizer: Either<optimize::peek::Optimizer, optimize::copy_to::Optimizer>,
604 explain_ctx: ExplainContext,
607}
608
609#[derive(Debug)]
610pub struct PeekStageRealTimeRecency {
611 validity: PlanValidity,
612 plan: mz_sql::plan::SelectPlan,
613 max_query_result_size: Option<u64>,
614 source_ids: BTreeSet<GlobalId>,
615 target_replica: Option<ReplicaId>,
616 timeline_context: TimelineContext,
617 oracle_read_ts: Option<Timestamp>,
618 optimizer: Either<optimize::peek::Optimizer, optimize::copy_to::Optimizer>,
619 explain_ctx: ExplainContext,
622}
623
624#[derive(Debug)]
625pub struct PeekStageTimestampReadHold {
626 validity: PlanValidity,
627 plan: mz_sql::plan::SelectPlan,
628 max_query_result_size: Option<u64>,
629 source_ids: BTreeSet<GlobalId>,
630 target_replica: Option<ReplicaId>,
631 timeline_context: TimelineContext,
632 oracle_read_ts: Option<Timestamp>,
633 real_time_recency_ts: Option<mz_repr::Timestamp>,
634 optimizer: Either<optimize::peek::Optimizer, optimize::copy_to::Optimizer>,
635 explain_ctx: ExplainContext,
638}
639
640#[derive(Debug)]
641pub struct PeekStageOptimize {
642 validity: PlanValidity,
643 plan: mz_sql::plan::SelectPlan,
644 max_query_result_size: Option<u64>,
645 source_ids: BTreeSet<GlobalId>,
646 id_bundle: CollectionIdBundle,
647 target_replica: Option<ReplicaId>,
648 determination: TimestampDetermination,
649 optimizer: Either<optimize::peek::Optimizer, optimize::copy_to::Optimizer>,
650 explain_ctx: ExplainContext,
653}
654
655#[derive(Debug)]
656pub struct PeekStageFinish {
657 validity: PlanValidity,
658 plan: mz_sql::plan::SelectPlan,
659 max_query_result_size: Option<u64>,
660 id_bundle: CollectionIdBundle,
661 target_replica: Option<ReplicaId>,
662 source_ids: BTreeSet<GlobalId>,
663 determination: TimestampDetermination,
664 cluster_id: ComputeInstanceId,
665 finishing: RowSetFinishing,
666 plan_insights_optimizer_trace: Option<OptimizerTrace>,
669 insights_ctx: Option<Box<PlanInsightsContext>>,
670 global_lir_plan: optimize::peek::GlobalLirPlan,
671 optimization_finished_at: EpochMillis,
672}
673
674#[derive(Debug)]
675pub struct PeekStageCopyTo {
676 validity: PlanValidity,
677 optimizer: optimize::copy_to::Optimizer,
678 global_lir_plan: optimize::copy_to::GlobalLirPlan,
679 optimization_finished_at: EpochMillis,
680 source_ids: BTreeSet<GlobalId>,
681}
682
683#[derive(Debug)]
684pub struct PeekStageExplainPlan {
685 validity: PlanValidity,
686 optimizer: optimize::peek::Optimizer,
687 df_meta: DataflowMetainfo,
688 explain_ctx: ExplainPlanContext,
689 insights_ctx: Option<Box<PlanInsightsContext>>,
690}
691
692#[derive(Debug)]
693pub struct PeekStageExplainPushdown {
694 validity: PlanValidity,
695 determination: TimestampDetermination,
696 imports: BTreeMap<GlobalId, MapFilterProject>,
697}
698
699#[derive(Debug)]
700pub enum CreateIndexStage {
701 Optimize(CreateIndexOptimize),
702 Finish(CreateIndexFinish),
703 Explain(CreateIndexExplain),
704}
705
706#[derive(Debug)]
707pub struct CreateIndexOptimize {
708 validity: PlanValidity,
709 plan: plan::CreateIndexPlan,
710 resolved_ids: ResolvedIds,
711 explain_ctx: ExplainContext,
714}
715
716#[derive(Debug)]
717pub struct CreateIndexFinish {
718 validity: PlanValidity,
719 item_id: CatalogItemId,
720 global_id: GlobalId,
721 plan: plan::CreateIndexPlan,
722 resolved_ids: ResolvedIds,
723 global_mir_plan: optimize::index::GlobalMirPlan,
724 global_lir_plan: optimize::index::GlobalLirPlan,
725 optimizer_features: OptimizerFeatures,
726}
727
728#[derive(Debug)]
729pub struct CreateIndexExplain {
730 validity: PlanValidity,
731 exported_index_id: GlobalId,
732 plan: plan::CreateIndexPlan,
733 df_meta: DataflowMetainfo,
734 explain_ctx: ExplainPlanContext,
735}
736
737#[derive(Debug)]
738pub enum CreateViewStage {
739 Optimize(CreateViewOptimize),
740 Finish(CreateViewFinish),
741 Explain(CreateViewExplain),
742}
743
744#[derive(Debug)]
745pub struct CreateViewOptimize {
746 validity: PlanValidity,
747 plan: plan::CreateViewPlan,
748 resolved_ids: ResolvedIds,
749 explain_ctx: ExplainContext,
752}
753
754#[derive(Debug)]
755pub struct CreateViewFinish {
756 validity: PlanValidity,
757 item_id: CatalogItemId,
759 global_id: GlobalId,
761 plan: plan::CreateViewPlan,
762 resolved_ids: ResolvedIds,
764 optimized_expr: OptimizedMirRelationExpr,
765}
766
767#[derive(Debug)]
768pub struct CreateViewExplain {
769 validity: PlanValidity,
770 id: GlobalId,
771 plan: plan::CreateViewPlan,
772 explain_ctx: ExplainPlanContext,
773}
774
775#[derive(Debug)]
776pub enum ExplainTimestampStage {
777 Optimize(ExplainTimestampOptimize),
778 RealTimeRecency(ExplainTimestampRealTimeRecency),
779 Finish(ExplainTimestampFinish),
780}
781
782#[derive(Debug)]
783pub struct ExplainTimestampOptimize {
784 validity: PlanValidity,
785 plan: plan::ExplainTimestampPlan,
786 cluster_id: ClusterId,
787}
788
789#[derive(Debug)]
790pub struct ExplainTimestampRealTimeRecency {
791 validity: PlanValidity,
792 format: ExplainFormat,
793 optimized_plan: OptimizedMirRelationExpr,
794 cluster_id: ClusterId,
795 when: QueryWhen,
796}
797
798#[derive(Debug)]
799pub struct ExplainTimestampFinish {
800 validity: PlanValidity,
801 format: ExplainFormat,
802 optimized_plan: OptimizedMirRelationExpr,
803 cluster_id: ClusterId,
804 source_ids: BTreeSet<GlobalId>,
805 when: QueryWhen,
806 real_time_recency_ts: Option<Timestamp>,
807}
808
809#[derive(Debug)]
810pub enum ClusterStage {
811 Alter(AlterCluster),
812 WaitForHydrated(AlterClusterWaitForHydrated),
813 Finalize(AlterClusterFinalize),
814}
815
816#[derive(Debug)]
817pub struct AlterCluster {
818 validity: PlanValidity,
819 plan: plan::AlterClusterPlan,
820}
821
822#[derive(Debug)]
823pub struct AlterClusterWaitForHydrated {
824 validity: PlanValidity,
825 plan: plan::AlterClusterPlan,
826 new_config: ClusterVariantManaged,
827 timeout_time: Instant,
828 on_timeout: OnTimeoutAction,
829}
830
831#[derive(Debug)]
832pub struct AlterClusterFinalize {
833 validity: PlanValidity,
834 plan: plan::AlterClusterPlan,
835 new_config: ClusterVariantManaged,
836}
837
838#[derive(Debug)]
839pub enum ExplainContext {
840 None,
842 Plan(ExplainPlanContext),
844 PlanInsightsNotice(OptimizerTrace),
847 Pushdown,
849}
850
851impl ExplainContext {
852 pub(crate) fn dispatch_guard(&self) -> Option<DispatchGuard<'_>> {
856 let optimizer_trace = match self {
857 ExplainContext::Plan(explain_ctx) => Some(&explain_ctx.optimizer_trace),
858 ExplainContext::PlanInsightsNotice(optimizer_trace) => Some(optimizer_trace),
859 _ => None,
860 };
861 optimizer_trace.map(|optimizer_trace| optimizer_trace.as_guard())
862 }
863
864 pub(crate) fn needs_cluster(&self) -> bool {
865 match self {
866 ExplainContext::None => true,
867 ExplainContext::Plan(..) => false,
868 ExplainContext::PlanInsightsNotice(..) => true,
869 ExplainContext::Pushdown => false,
870 }
871 }
872
873 pub(crate) fn needs_plan_insights(&self) -> bool {
874 matches!(
875 self,
876 ExplainContext::Plan(ExplainPlanContext {
877 stage: ExplainStage::PlanInsights,
878 ..
879 }) | ExplainContext::PlanInsightsNotice(_)
880 )
881 }
882}
883
884#[derive(Debug)]
885pub struct ExplainPlanContext {
886 pub broken: bool,
891 pub config: ExplainConfig,
892 pub format: ExplainFormat,
893 pub stage: ExplainStage,
894 pub replan: Option<GlobalId>,
895 pub desc: Option<RelationDesc>,
896 pub optimizer_trace: OptimizerTrace,
897}
898
899#[derive(Debug)]
900pub enum CreateMaterializedViewStage {
901 Optimize(CreateMaterializedViewOptimize),
902 Finish(CreateMaterializedViewFinish),
903 Explain(CreateMaterializedViewExplain),
904}
905
906#[derive(Debug)]
907pub struct CreateMaterializedViewOptimize {
908 validity: PlanValidity,
909 plan: plan::CreateMaterializedViewPlan,
910 resolved_ids: ResolvedIds,
911 explain_ctx: ExplainContext,
914}
915
916#[derive(Debug)]
917pub struct CreateMaterializedViewFinish {
918 item_id: CatalogItemId,
920 global_id: GlobalId,
922 validity: PlanValidity,
923 plan: plan::CreateMaterializedViewPlan,
924 resolved_ids: ResolvedIds,
925 local_mir_plan: optimize::materialized_view::LocalMirPlan,
926 global_mir_plan: optimize::materialized_view::GlobalMirPlan,
927 global_lir_plan: optimize::materialized_view::GlobalLirPlan,
928 optimizer_features: OptimizerFeatures,
929}
930
931#[derive(Debug)]
932pub struct CreateMaterializedViewExplain {
933 global_id: GlobalId,
934 validity: PlanValidity,
935 plan: plan::CreateMaterializedViewPlan,
936 df_meta: DataflowMetainfo,
937 explain_ctx: ExplainPlanContext,
938}
939
940#[derive(Debug)]
941pub enum SubscribeStage {
942 OptimizeMir(SubscribeOptimizeMir),
943 TimestampOptimizeLir(SubscribeTimestampOptimizeLir),
944 Finish(SubscribeFinish),
945 Explain(SubscribeExplain),
946}
947
948#[derive(Debug)]
949pub struct SubscribeOptimizeMir {
950 validity: PlanValidity,
951 plan: plan::SubscribePlan,
952 timeline: TimelineContext,
953 dependency_ids: BTreeSet<GlobalId>,
954 cluster_id: ComputeInstanceId,
955 replica_id: Option<ReplicaId>,
956 explain_ctx: ExplainContext,
959}
960
961#[derive(Debug)]
962pub struct SubscribeTimestampOptimizeLir {
963 validity: PlanValidity,
964 plan: plan::SubscribePlan,
965 timeline: TimelineContext,
966 optimizer: optimize::subscribe::Optimizer,
967 global_mir_plan: optimize::subscribe::GlobalMirPlan<optimize::subscribe::Unresolved>,
968 dependency_ids: BTreeSet<GlobalId>,
969 replica_id: Option<ReplicaId>,
970 explain_ctx: ExplainContext,
973}
974
975#[derive(Debug)]
976pub struct SubscribeFinish {
977 validity: PlanValidity,
978 cluster_id: ComputeInstanceId,
979 replica_id: Option<ReplicaId>,
980 plan: plan::SubscribePlan,
981 global_lir_plan: optimize::subscribe::GlobalLirPlan,
982 dependency_ids: BTreeSet<GlobalId>,
983}
984
985#[derive(Debug)]
986pub struct SubscribeExplain {
987 validity: PlanValidity,
988 optimizer: optimize::subscribe::Optimizer,
989 df_meta: DataflowMetainfo,
990 cluster_id: ComputeInstanceId,
991 explain_ctx: ExplainPlanContext,
992}
993
994#[derive(Debug)]
995pub enum IntrospectionSubscribeStage {
996 OptimizeMir(IntrospectionSubscribeOptimizeMir),
997 TimestampOptimizeLir(IntrospectionSubscribeTimestampOptimizeLir),
998 Finish(IntrospectionSubscribeFinish),
999}
1000
1001#[derive(Debug)]
1002pub struct IntrospectionSubscribeOptimizeMir {
1003 validity: PlanValidity,
1004 plan: plan::SubscribePlan,
1005 subscribe_id: GlobalId,
1006 cluster_id: ComputeInstanceId,
1007 replica_id: ReplicaId,
1008}
1009
1010#[derive(Debug)]
1011pub struct IntrospectionSubscribeTimestampOptimizeLir {
1012 validity: PlanValidity,
1013 optimizer: optimize::subscribe::Optimizer,
1014 global_mir_plan: optimize::subscribe::GlobalMirPlan<optimize::subscribe::Unresolved>,
1015 cluster_id: ComputeInstanceId,
1016 replica_id: ReplicaId,
1017}
1018
1019#[derive(Debug)]
1020pub struct IntrospectionSubscribeFinish {
1021 validity: PlanValidity,
1022 global_lir_plan: optimize::subscribe::GlobalLirPlan,
1023 read_holds: ReadHolds,
1024 cluster_id: ComputeInstanceId,
1025 replica_id: ReplicaId,
1026}
1027
1028#[derive(Debug)]
1029pub enum SecretStage {
1030 CreateEnsure(CreateSecretEnsure),
1031 CreateFinish(CreateSecretFinish),
1032 RotateKeysEnsure(RotateKeysSecretEnsure),
1033 RotateKeysFinish(RotateKeysSecretFinish),
1034 Alter(AlterSecret),
1035}
1036
1037#[derive(Debug)]
1038pub struct CreateSecretEnsure {
1039 validity: PlanValidity,
1040 plan: plan::CreateSecretPlan,
1041}
1042
1043#[derive(Debug)]
1044pub struct CreateSecretFinish {
1045 validity: PlanValidity,
1046 item_id: CatalogItemId,
1047 global_id: GlobalId,
1048 plan: plan::CreateSecretPlan,
1049}
1050
1051#[derive(Debug)]
1052pub struct RotateKeysSecretEnsure {
1053 validity: PlanValidity,
1054 id: CatalogItemId,
1055}
1056
1057#[derive(Debug)]
1058pub struct RotateKeysSecretFinish {
1059 validity: PlanValidity,
1060 ops: Vec<crate::catalog::Op>,
1061}
1062
1063#[derive(Debug)]
1064pub struct AlterSecret {
1065 validity: PlanValidity,
1066 plan: plan::AlterSecretPlan,
1067}
1068
1069#[derive(Debug, Copy, Clone, PartialEq, Eq)]
1074pub enum TargetCluster {
1075 CatalogServer,
1077 Active,
1079 Transaction(ClusterId),
1081}
1082
1083pub(crate) enum StageResult<T> {
1085 Handle(JoinHandle<Result<T, AdapterError>>),
1087 HandleRetire(JoinHandle<Result<ExecuteResponse, AdapterError>>),
1089 Immediate(T),
1091 Response(ExecuteResponse),
1093}
1094
1095pub(crate) trait Staged: Send {
1097 type Ctx: StagedContext;
1098
1099 fn validity(&mut self) -> &mut PlanValidity;
1100
1101 async fn stage(
1103 self,
1104 coord: &mut Coordinator,
1105 ctx: &mut Self::Ctx,
1106 ) -> Result<StageResult<Box<Self>>, AdapterError>;
1107
1108 fn message(self, ctx: Self::Ctx, span: Span) -> Message;
1110
1111 fn cancel_enabled(&self) -> bool;
1113}
1114
1115pub trait StagedContext {
1116 fn retire(self, result: Result<ExecuteResponse, AdapterError>);
1117 fn session(&self) -> Option<&Session>;
1118}
1119
1120impl StagedContext for ExecuteContext {
1121 fn retire(self, result: Result<ExecuteResponse, AdapterError>) {
1122 self.retire(result);
1123 }
1124
1125 fn session(&self) -> Option<&Session> {
1126 Some(self.session())
1127 }
1128}
1129
1130impl StagedContext for () {
1131 fn retire(self, _result: Result<ExecuteResponse, AdapterError>) {}
1132
1133 fn session(&self) -> Option<&Session> {
1134 None
1135 }
1136}
1137
1138pub struct Config {
1140 pub controller_config: ControllerConfig,
1141 pub controller_envd_epoch: NonZeroI64,
1142 pub storage: Box<dyn mz_catalog::durable::DurableCatalogState>,
1143 pub audit_logs_iterator: AuditLogIterator,
1144 pub timestamp_oracle_url: Option<SensitiveUrl>,
1145 pub unsafe_mode: bool,
1146 pub all_features: bool,
1147 pub build_info: &'static BuildInfo,
1148 pub environment_id: EnvironmentId,
1149 pub metrics_registry: MetricsRegistry,
1150 pub now: NowFn,
1151 pub secrets_controller: Arc<dyn SecretsController>,
1152 pub cloud_resource_controller: Option<Arc<dyn CloudResourceController>>,
1153 pub availability_zones: Vec<String>,
1154 pub cluster_replica_sizes: ClusterReplicaSizeMap,
1155 pub builtin_system_cluster_config: BootstrapBuiltinClusterConfig,
1156 pub builtin_catalog_server_cluster_config: BootstrapBuiltinClusterConfig,
1157 pub builtin_probe_cluster_config: BootstrapBuiltinClusterConfig,
1158 pub builtin_support_cluster_config: BootstrapBuiltinClusterConfig,
1159 pub builtin_analytics_cluster_config: BootstrapBuiltinClusterConfig,
1160 pub system_parameter_defaults: BTreeMap<String, String>,
1161 pub storage_usage_client: StorageUsageClient,
1162 pub storage_usage_collection_interval: Duration,
1163 pub storage_usage_retention_period: Option<Duration>,
1164 pub segment_client: Option<mz_segment::Client>,
1165 pub egress_addresses: Vec<IpNet>,
1166 pub remote_system_parameters: Option<BTreeMap<String, String>>,
1167 pub aws_account_id: Option<String>,
1168 pub aws_privatelink_availability_zones: Option<Vec<String>>,
1169 pub connection_context: ConnectionContext,
1170 pub connection_limit_callback: Box<dyn Fn(u64, u64) -> () + Send + Sync + 'static>,
1171 pub webhook_concurrency_limit: WebhookConcurrencyLimiter,
1172 pub http_host_name: Option<String>,
1173 pub tracing_handle: TracingHandle,
1174 pub read_only_controllers: bool,
1178
1179 pub caught_up_trigger: Option<Trigger>,
1183
1184 pub helm_chart_version: Option<String>,
1185 pub license_key: ValidatedLicenseKey,
1186 pub external_login_password_mz_system: Option<Password>,
1187 pub force_builtin_schema_migration: Option<String>,
1188}
1189
1190#[derive(Debug, Serialize)]
1192pub struct ConnMeta {
1193 secret_key: u32,
1198 connected_at: EpochMillis,
1200 user: User,
1201 application_name: String,
1202 uuid: Uuid,
1203 conn_id: ConnectionId,
1204 client_ip: Option<IpAddr>,
1205
1206 drop_sinks: BTreeSet<GlobalId>,
1209
1210 #[serde(skip)]
1212 deferred_lock: Option<OwnedMutexGuard<()>>,
1213
1214 pending_cluster_alters: BTreeSet<ClusterId>,
1217
1218 #[serde(skip)]
1220 notice_tx: mpsc::UnboundedSender<AdapterNotice>,
1221
1222 authenticated_role: RoleId,
1226}
1227
1228impl ConnMeta {
1229 pub fn conn_id(&self) -> &ConnectionId {
1230 &self.conn_id
1231 }
1232
1233 pub fn user(&self) -> &User {
1234 &self.user
1235 }
1236
1237 pub fn application_name(&self) -> &str {
1238 &self.application_name
1239 }
1240
1241 pub fn authenticated_role_id(&self) -> &RoleId {
1242 &self.authenticated_role
1243 }
1244
1245 pub fn uuid(&self) -> Uuid {
1246 self.uuid
1247 }
1248
1249 pub fn client_ip(&self) -> Option<IpAddr> {
1250 self.client_ip
1251 }
1252
1253 pub fn connected_at(&self) -> EpochMillis {
1254 self.connected_at
1255 }
1256}
1257
1258#[derive(Debug)]
1259pub struct PendingTxn {
1261 ctx: ExecuteContext,
1263 response: Result<PendingTxnResponse, AdapterError>,
1265 action: EndTransactionAction,
1267}
1268
1269#[derive(Debug)]
1270pub enum PendingTxnResponse {
1272 Committed {
1274 params: BTreeMap<&'static str, String>,
1276 },
1277 Rolledback {
1279 params: BTreeMap<&'static str, String>,
1281 },
1282}
1283
1284impl PendingTxnResponse {
1285 pub fn extend_params(&mut self, p: impl IntoIterator<Item = (&'static str, String)>) {
1286 match self {
1287 PendingTxnResponse::Committed { params }
1288 | PendingTxnResponse::Rolledback { params } => params.extend(p),
1289 }
1290 }
1291}
1292
1293impl From<PendingTxnResponse> for ExecuteResponse {
1294 fn from(value: PendingTxnResponse) -> Self {
1295 match value {
1296 PendingTxnResponse::Committed { params } => {
1297 ExecuteResponse::TransactionCommitted { params }
1298 }
1299 PendingTxnResponse::Rolledback { params } => {
1300 ExecuteResponse::TransactionRolledBack { params }
1301 }
1302 }
1303 }
1304}
1305
1306#[derive(Debug)]
1307pub struct PendingReadTxn {
1309 txn: PendingRead,
1311 timestamp_context: TimestampContext,
1313 created: Instant,
1315 num_requeues: u64,
1319 otel_ctx: OpenTelemetryContext,
1321}
1322
1323impl PendingReadTxn {
1324 pub fn timestamp_context(&self) -> &TimestampContext {
1326 &self.timestamp_context
1327 }
1328
1329 pub(crate) fn take_context(self) -> ExecuteContext {
1330 self.txn.take_context()
1331 }
1332}
1333
1334#[derive(Debug)]
1335enum PendingRead {
1337 Read {
1338 txn: PendingTxn,
1340 },
1341 ReadThenWrite {
1342 ctx: ExecuteContext,
1344 tx: oneshot::Sender<Option<ExecuteContext>>,
1347 },
1348}
1349
1350impl PendingRead {
1351 #[instrument(level = "debug")]
1356 pub fn finish(self) -> Option<(ExecuteContext, Result<ExecuteResponse, AdapterError>)> {
1357 match self {
1358 PendingRead::Read {
1359 txn:
1360 PendingTxn {
1361 mut ctx,
1362 response,
1363 action,
1364 },
1365 ..
1366 } => {
1367 let changed = ctx.session_mut().vars_mut().end_transaction(action);
1368 let response = response.map(|mut r| {
1370 r.extend_params(changed);
1371 ExecuteResponse::from(r)
1372 });
1373
1374 Some((ctx, response))
1375 }
1376 PendingRead::ReadThenWrite { ctx, tx, .. } => {
1377 let _ = tx.send(Some(ctx));
1379 None
1380 }
1381 }
1382 }
1383
1384 fn label(&self) -> &'static str {
1385 match self {
1386 PendingRead::Read { .. } => "read",
1387 PendingRead::ReadThenWrite { .. } => "read_then_write",
1388 }
1389 }
1390
1391 pub(crate) fn take_context(self) -> ExecuteContext {
1392 match self {
1393 PendingRead::Read { txn, .. } => txn.ctx,
1394 PendingRead::ReadThenWrite { ctx, tx, .. } => {
1395 let _ = tx.send(None);
1398 ctx
1399 }
1400 }
1401 }
1402}
1403
1404#[derive(Debug, Default)]
1414#[must_use]
1415pub struct ExecuteContextExtra {
1416 statement_uuid: Option<StatementLoggingId>,
1417}
1418
1419impl ExecuteContextExtra {
1420 pub(crate) fn new(statement_uuid: Option<StatementLoggingId>) -> Self {
1421 Self { statement_uuid }
1422 }
1423 pub fn is_trivial(&self) -> bool {
1424 self.statement_uuid.is_none()
1425 }
1426 pub fn contents(&self) -> Option<StatementLoggingId> {
1427 self.statement_uuid
1428 }
1429 #[must_use]
1433 pub(crate) fn retire(self) -> Option<StatementLoggingId> {
1434 self.statement_uuid
1435 }
1436}
1437
1438#[derive(Debug)]
1448#[must_use]
1449pub struct ExecuteContextGuard {
1450 extra: ExecuteContextExtra,
1451 coordinator_tx: mpsc::UnboundedSender<Message>,
1456}
1457
1458impl Default for ExecuteContextGuard {
1459 fn default() -> Self {
1460 let (tx, _rx) = mpsc::unbounded_channel();
1464 Self {
1465 extra: ExecuteContextExtra::default(),
1466 coordinator_tx: tx,
1467 }
1468 }
1469}
1470
1471impl ExecuteContextGuard {
1472 pub(crate) fn new(
1473 statement_uuid: Option<StatementLoggingId>,
1474 coordinator_tx: mpsc::UnboundedSender<Message>,
1475 ) -> Self {
1476 Self {
1477 extra: ExecuteContextExtra::new(statement_uuid),
1478 coordinator_tx,
1479 }
1480 }
1481 pub fn is_trivial(&self) -> bool {
1482 self.extra.is_trivial()
1483 }
1484 pub fn contents(&self) -> Option<StatementLoggingId> {
1485 self.extra.contents()
1486 }
1487 pub(crate) fn defuse(mut self) -> ExecuteContextExtra {
1494 std::mem::take(&mut self.extra)
1496 }
1497}
1498
1499impl Drop for ExecuteContextGuard {
1500 fn drop(&mut self) {
1501 if let Some(statement_uuid) = self.extra.statement_uuid.take() {
1502 let msg = Message::RetireExecute {
1505 data: ExecuteContextExtra {
1506 statement_uuid: Some(statement_uuid),
1507 },
1508 otel_ctx: OpenTelemetryContext::obtain(),
1509 reason: StatementEndedExecutionReason::Aborted,
1510 };
1511 let _ = self.coordinator_tx.send(msg);
1514 }
1515 }
1516}
1517
1518#[derive(Debug)]
1530pub struct ExecuteContext {
1531 inner: Box<ExecuteContextInner>,
1532}
1533
1534impl std::ops::Deref for ExecuteContext {
1535 type Target = ExecuteContextInner;
1536 fn deref(&self) -> &Self::Target {
1537 &*self.inner
1538 }
1539}
1540
1541impl std::ops::DerefMut for ExecuteContext {
1542 fn deref_mut(&mut self) -> &mut Self::Target {
1543 &mut *self.inner
1544 }
1545}
1546
1547#[derive(Debug)]
1548pub struct ExecuteContextInner {
1549 tx: ClientTransmitter<ExecuteResponse>,
1550 internal_cmd_tx: mpsc::UnboundedSender<Message>,
1551 session: Session,
1552 extra: ExecuteContextGuard,
1553}
1554
1555impl ExecuteContext {
1556 pub fn session(&self) -> &Session {
1557 &self.session
1558 }
1559
1560 pub fn session_mut(&mut self) -> &mut Session {
1561 &mut self.session
1562 }
1563
1564 pub fn tx(&self) -> &ClientTransmitter<ExecuteResponse> {
1565 &self.tx
1566 }
1567
1568 pub fn tx_mut(&mut self) -> &mut ClientTransmitter<ExecuteResponse> {
1569 &mut self.tx
1570 }
1571
1572 pub fn from_parts(
1573 tx: ClientTransmitter<ExecuteResponse>,
1574 internal_cmd_tx: mpsc::UnboundedSender<Message>,
1575 session: Session,
1576 extra: ExecuteContextGuard,
1577 ) -> Self {
1578 Self {
1579 inner: ExecuteContextInner {
1580 tx,
1581 session,
1582 extra,
1583 internal_cmd_tx,
1584 }
1585 .into(),
1586 }
1587 }
1588
1589 pub fn into_parts(
1598 self,
1599 ) -> (
1600 ClientTransmitter<ExecuteResponse>,
1601 mpsc::UnboundedSender<Message>,
1602 Session,
1603 ExecuteContextGuard,
1604 ) {
1605 let ExecuteContextInner {
1606 tx,
1607 internal_cmd_tx,
1608 session,
1609 extra,
1610 } = *self.inner;
1611 (tx, internal_cmd_tx, session, extra)
1612 }
1613
1614 #[instrument(level = "debug")]
1616 pub fn retire(self, result: Result<ExecuteResponse, AdapterError>) {
1617 let ExecuteContextInner {
1618 tx,
1619 internal_cmd_tx,
1620 session,
1621 extra,
1622 } = *self.inner;
1623 let reason = if extra.is_trivial() {
1624 None
1625 } else {
1626 Some((&result).into())
1627 };
1628 tx.send(result, session);
1629 if let Some(reason) = reason {
1630 let extra = extra.defuse();
1632 if let Err(e) = internal_cmd_tx.send(Message::RetireExecute {
1633 otel_ctx: OpenTelemetryContext::obtain(),
1634 data: extra,
1635 reason,
1636 }) {
1637 warn!("internal_cmd_rx dropped before we could send: {:?}", e);
1638 }
1639 }
1640 }
1641
1642 pub fn extra(&self) -> &ExecuteContextGuard {
1643 &self.extra
1644 }
1645
1646 pub fn extra_mut(&mut self) -> &mut ExecuteContextGuard {
1647 &mut self.extra
1648 }
1649}
1650
1651#[derive(Debug)]
1652struct ClusterReplicaStatuses(
1653 BTreeMap<ClusterId, BTreeMap<ReplicaId, BTreeMap<ProcessId, ClusterReplicaProcessStatus>>>,
1654);
1655
1656impl ClusterReplicaStatuses {
1657 pub(crate) fn new() -> ClusterReplicaStatuses {
1658 ClusterReplicaStatuses(BTreeMap::new())
1659 }
1660
1661 pub(crate) fn initialize_cluster_statuses(&mut self, cluster_id: ClusterId) {
1665 let prev = self.0.insert(cluster_id, BTreeMap::new());
1666 assert_eq!(
1667 prev, None,
1668 "cluster {cluster_id} statuses already initialized"
1669 );
1670 }
1671
1672 pub(crate) fn initialize_cluster_replica_statuses(
1676 &mut self,
1677 cluster_id: ClusterId,
1678 replica_id: ReplicaId,
1679 num_processes: usize,
1680 time: DateTime<Utc>,
1681 ) {
1682 tracing::info!(
1683 ?cluster_id,
1684 ?replica_id,
1685 ?time,
1686 "initializing cluster replica status"
1687 );
1688 let replica_statuses = self.0.entry(cluster_id).or_default();
1689 let process_statuses = (0..num_processes)
1690 .map(|process_id| {
1691 let status = ClusterReplicaProcessStatus {
1692 status: ClusterStatus::Offline(Some(OfflineReason::Initializing)),
1693 time: time.clone(),
1694 };
1695 (u64::cast_from(process_id), status)
1696 })
1697 .collect();
1698 let prev = replica_statuses.insert(replica_id, process_statuses);
1699 assert_none!(
1700 prev,
1701 "cluster replica {cluster_id}.{replica_id} statuses already initialized"
1702 );
1703 }
1704
1705 pub(crate) fn remove_cluster_statuses(
1709 &mut self,
1710 cluster_id: &ClusterId,
1711 ) -> BTreeMap<ReplicaId, BTreeMap<ProcessId, ClusterReplicaProcessStatus>> {
1712 let prev = self.0.remove(cluster_id);
1713 prev.unwrap_or_else(|| panic!("unknown cluster: {cluster_id}"))
1714 }
1715
1716 pub(crate) fn remove_cluster_replica_statuses(
1720 &mut self,
1721 cluster_id: &ClusterId,
1722 replica_id: &ReplicaId,
1723 ) -> BTreeMap<ProcessId, ClusterReplicaProcessStatus> {
1724 let replica_statuses = self
1725 .0
1726 .get_mut(cluster_id)
1727 .unwrap_or_else(|| panic!("unknown cluster: {cluster_id}"));
1728 let prev = replica_statuses.remove(replica_id);
1729 prev.unwrap_or_else(|| panic!("unknown cluster replica: {cluster_id}.{replica_id}"))
1730 }
1731
1732 pub(crate) fn ensure_cluster_status(
1736 &mut self,
1737 cluster_id: ClusterId,
1738 replica_id: ReplicaId,
1739 process_id: ProcessId,
1740 status: ClusterReplicaProcessStatus,
1741 ) {
1742 let replica_statuses = self
1743 .0
1744 .get_mut(&cluster_id)
1745 .unwrap_or_else(|| panic!("unknown cluster: {cluster_id}"))
1746 .get_mut(&replica_id)
1747 .unwrap_or_else(|| panic!("unknown cluster replica: {cluster_id}.{replica_id}"));
1748 replica_statuses.insert(process_id, status);
1749 }
1750
1751 pub fn get_cluster_replica_status(
1755 &self,
1756 cluster_id: ClusterId,
1757 replica_id: ReplicaId,
1758 ) -> ClusterStatus {
1759 let process_status = self.get_cluster_replica_statuses(cluster_id, replica_id);
1760 Self::cluster_replica_status(process_status)
1761 }
1762
1763 pub fn cluster_replica_status(
1765 process_status: &BTreeMap<ProcessId, ClusterReplicaProcessStatus>,
1766 ) -> ClusterStatus {
1767 process_status
1768 .values()
1769 .fold(ClusterStatus::Online, |s, p| match (s, p.status) {
1770 (ClusterStatus::Online, ClusterStatus::Online) => ClusterStatus::Online,
1771 (x, y) => {
1772 let reason_x = match x {
1773 ClusterStatus::Offline(reason) => reason,
1774 ClusterStatus::Online => None,
1775 };
1776 let reason_y = match y {
1777 ClusterStatus::Offline(reason) => reason,
1778 ClusterStatus::Online => None,
1779 };
1780 ClusterStatus::Offline(reason_x.or(reason_y))
1782 }
1783 })
1784 }
1785
1786 pub(crate) fn get_cluster_replica_statuses(
1790 &self,
1791 cluster_id: ClusterId,
1792 replica_id: ReplicaId,
1793 ) -> &BTreeMap<ProcessId, ClusterReplicaProcessStatus> {
1794 self.try_get_cluster_replica_statuses(cluster_id, replica_id)
1795 .unwrap_or_else(|| panic!("unknown cluster replica: {cluster_id}.{replica_id}"))
1796 }
1797
1798 pub(crate) fn try_get_cluster_replica_statuses(
1800 &self,
1801 cluster_id: ClusterId,
1802 replica_id: ReplicaId,
1803 ) -> Option<&BTreeMap<ProcessId, ClusterReplicaProcessStatus>> {
1804 self.try_get_cluster_statuses(cluster_id)
1805 .and_then(|statuses| statuses.get(&replica_id))
1806 }
1807
1808 pub(crate) fn try_get_cluster_statuses(
1810 &self,
1811 cluster_id: ClusterId,
1812 ) -> Option<&BTreeMap<ReplicaId, BTreeMap<ProcessId, ClusterReplicaProcessStatus>>> {
1813 self.0.get(&cluster_id)
1814 }
1815}
1816
1817#[derive(Derivative)]
1819#[derivative(Debug)]
1820pub struct Coordinator {
1821 #[derivative(Debug = "ignore")]
1823 controller: mz_controller::Controller,
1824 catalog: Arc<Catalog>,
1832
1833 persist_client: PersistClient,
1836
1837 internal_cmd_tx: mpsc::UnboundedSender<Message>,
1839 group_commit_tx: appends::GroupCommitNotifier,
1841
1842 strict_serializable_reads_tx: mpsc::UnboundedSender<(ConnectionId, PendingReadTxn)>,
1844
1845 global_timelines: BTreeMap<Timeline, TimelineState>,
1848
1849 transient_id_gen: Arc<TransientIdGen>,
1851 active_conns: BTreeMap<ConnectionId, ConnMeta>,
1854
1855 txn_read_holds: BTreeMap<ConnectionId, read_policy::ReadHolds>,
1859
1860 pending_peeks: BTreeMap<Uuid, PendingPeek>,
1864 client_pending_peeks: BTreeMap<ConnectionId, BTreeMap<Uuid, ClusterId>>,
1866
1867 pending_linearize_read_txns: BTreeMap<ConnectionId, PendingReadTxn>,
1869
1870 active_compute_sinks: BTreeMap<GlobalId, ActiveComputeSink>,
1872 active_webhooks: BTreeMap<CatalogItemId, WebhookAppenderInvalidator>,
1874 active_copies: BTreeMap<ConnectionId, ActiveCopyFrom>,
1877
1878 staged_cancellation: BTreeMap<ConnectionId, (watch::Sender<bool>, watch::Receiver<bool>)>,
1881 introspection_subscribes: BTreeMap<GlobalId, IntrospectionSubscribe>,
1883
1884 write_locks: BTreeMap<CatalogItemId, Arc<tokio::sync::Mutex<()>>>,
1886 deferred_write_ops: BTreeMap<ConnectionId, DeferredOp>,
1888
1889 pending_writes: Vec<PendingWriteTxn>,
1891
1892 advance_timelines_interval: Interval,
1902
1903 serialized_ddl: LockedVecDeque<DeferredPlanStatement>,
1912
1913 secrets_controller: Arc<dyn SecretsController>,
1916 caching_secrets_reader: CachingSecretsReader,
1918
1919 cloud_resource_controller: Option<Arc<dyn CloudResourceController>>,
1922
1923 storage_usage_client: StorageUsageClient,
1925 storage_usage_collection_interval: Duration,
1927
1928 #[derivative(Debug = "ignore")]
1930 segment_client: Option<mz_segment::Client>,
1931
1932 metrics: Metrics,
1934 optimizer_metrics: OptimizerMetrics,
1936
1937 tracing_handle: TracingHandle,
1939
1940 statement_logging: StatementLogging,
1942
1943 webhook_concurrency_limit: WebhookConcurrencyLimiter,
1945
1946 timestamp_oracle_config: Option<TimestampOracleConfig>,
1949
1950 check_cluster_scheduling_policies_interval: Interval,
1952
1953 cluster_scheduling_decisions: BTreeMap<ClusterId, BTreeMap<&'static str, SchedulingDecision>>,
1957
1958 caught_up_check_interval: Interval,
1961
1962 caught_up_check: Option<CaughtUpCheckContext>,
1965
1966 installed_watch_sets: BTreeMap<WatchSetId, (ConnectionId, WatchSetResponse)>,
1968
1969 connection_watch_sets: BTreeMap<ConnectionId, BTreeSet<WatchSetId>>,
1971
1972 cluster_replica_statuses: ClusterReplicaStatuses,
1974
1975 read_only_controllers: bool,
1979
1980 buffered_builtin_table_updates: Option<Vec<BuiltinTableUpdate>>,
1988
1989 license_key: ValidatedLicenseKey,
1990
1991 user_id_pool: IdPool,
1993}
1994
1995impl Coordinator {
1996 #[instrument(name = "coord::bootstrap")]
2000 pub(crate) async fn bootstrap(
2001 &mut self,
2002 boot_ts: Timestamp,
2003 migrated_storage_collections_0dt: BTreeSet<CatalogItemId>,
2004 mut builtin_table_updates: Vec<BuiltinTableUpdate>,
2005 cached_global_exprs: BTreeMap<GlobalId, GlobalExpressions>,
2006 uncached_local_exprs: BTreeMap<GlobalId, LocalExpressions>,
2007 audit_logs_iterator: AuditLogIterator,
2008 ) -> Result<(), AdapterError> {
2009 let bootstrap_start = Instant::now();
2010 info!("startup: coordinator init: bootstrap beginning");
2011 info!("startup: coordinator init: bootstrap: preamble beginning");
2012
2013 let cluster_statuses: Vec<(_, Vec<_>)> = self
2016 .catalog()
2017 .clusters()
2018 .map(|cluster| {
2019 (
2020 cluster.id(),
2021 cluster
2022 .replicas()
2023 .map(|replica| {
2024 (replica.replica_id, replica.config.location.num_processes())
2025 })
2026 .collect(),
2027 )
2028 })
2029 .collect();
2030 let now = self.now_datetime();
2031 for (cluster_id, replica_statuses) in cluster_statuses {
2032 self.cluster_replica_statuses
2033 .initialize_cluster_statuses(cluster_id);
2034 for (replica_id, num_processes) in replica_statuses {
2035 self.cluster_replica_statuses
2036 .initialize_cluster_replica_statuses(
2037 cluster_id,
2038 replica_id,
2039 num_processes,
2040 now,
2041 );
2042 }
2043 }
2044
2045 let system_config = self.catalog().system_config();
2046
2047 mz_metrics::update_dyncfg(&system_config.dyncfg_updates());
2049
2050 let compute_config = flags::compute_config(system_config);
2052 let storage_config = flags::storage_config(system_config);
2053 let scheduling_config = flags::orchestrator_scheduling_config(system_config);
2054 let dyncfg_updates = system_config.dyncfg_updates();
2055 self.controller.compute.update_configuration(compute_config);
2056 self.controller.storage.update_parameters(storage_config);
2057 self.controller
2058 .update_orchestrator_scheduling_config(scheduling_config);
2059 self.controller.update_configuration(dyncfg_updates);
2060
2061 self.validate_resource_limit_numeric(
2062 Numeric::zero(),
2063 self.current_credit_consumption_rate(),
2064 |system_vars| {
2065 self.license_key
2066 .max_credit_consumption_rate()
2067 .map_or_else(|| system_vars.max_credit_consumption_rate(), Numeric::from)
2068 },
2069 "cluster replica",
2070 MAX_CREDIT_CONSUMPTION_RATE.name(),
2071 )?;
2072
2073 let mut policies_to_set: BTreeMap<CompactionWindow, CollectionIdBundle> =
2074 Default::default();
2075
2076 let enable_worker_core_affinity =
2077 self.catalog().system_config().enable_worker_core_affinity();
2078 for instance in self.catalog.clusters() {
2079 self.controller.create_cluster(
2080 instance.id,
2081 ClusterConfig {
2082 arranged_logs: instance.log_indexes.clone(),
2083 workload_class: instance.config.workload_class.clone(),
2084 },
2085 )?;
2086 for replica in instance.replicas() {
2087 let role = instance.role();
2088 self.controller.create_replica(
2089 instance.id,
2090 replica.replica_id,
2091 instance.name.clone(),
2092 replica.name.clone(),
2093 role,
2094 replica.config.clone(),
2095 enable_worker_core_affinity,
2096 )?;
2097 }
2098 }
2099
2100 info!(
2101 "startup: coordinator init: bootstrap: preamble complete in {:?}",
2102 bootstrap_start.elapsed()
2103 );
2104
2105 let init_storage_collections_start = Instant::now();
2106 info!("startup: coordinator init: bootstrap: storage collections init beginning");
2107 self.bootstrap_storage_collections(&migrated_storage_collections_0dt)
2108 .await;
2109 info!(
2110 "startup: coordinator init: bootstrap: storage collections init complete in {:?}",
2111 init_storage_collections_start.elapsed()
2112 );
2113
2114 self.controller.start_compute_introspection_sink();
2119
2120 let sorting_start = Instant::now();
2121 info!("startup: coordinator init: bootstrap: sorting catalog entries");
2122 let entries = self.bootstrap_sort_catalog_entries();
2123 info!(
2124 "startup: coordinator init: bootstrap: sorting catalog entries complete in {:?}",
2125 sorting_start.elapsed()
2126 );
2127
2128 let optimize_dataflows_start = Instant::now();
2129 info!("startup: coordinator init: bootstrap: optimize dataflow plans beginning");
2130 let uncached_global_exps = self.bootstrap_dataflow_plans(&entries, cached_global_exprs)?;
2131 info!(
2132 "startup: coordinator init: bootstrap: optimize dataflow plans complete in {:?}",
2133 optimize_dataflows_start.elapsed()
2134 );
2135
2136 let _fut = self.catalog().update_expression_cache(
2138 uncached_local_exprs.into_iter().collect(),
2139 uncached_global_exps.into_iter().collect(),
2140 Default::default(),
2141 );
2142
2143 let bootstrap_as_ofs_start = Instant::now();
2147 info!("startup: coordinator init: bootstrap: dataflow as-of bootstrapping beginning");
2148 let dataflow_read_holds = self.bootstrap_dataflow_as_ofs().await;
2149 info!(
2150 "startup: coordinator init: bootstrap: dataflow as-of bootstrapping complete in {:?}",
2151 bootstrap_as_ofs_start.elapsed()
2152 );
2153
2154 let postamble_start = Instant::now();
2155 info!("startup: coordinator init: bootstrap: postamble beginning");
2156
2157 let logs: BTreeSet<_> = BUILTINS::logs()
2158 .map(|log| self.catalog().resolve_builtin_log(log))
2159 .flat_map(|item_id| self.catalog().get_global_ids(&item_id))
2160 .collect();
2161
2162 let mut privatelink_connections = BTreeMap::new();
2163
2164 for entry in &entries {
2165 debug!(
2166 "coordinator init: installing {} {}",
2167 entry.item().typ(),
2168 entry.id()
2169 );
2170 let mut policy = entry.item().initial_logical_compaction_window();
2171 match entry.item() {
2172 CatalogItem::Source(source) => {
2178 if source.custom_logical_compaction_window.is_none() {
2180 if let DataSourceDesc::IngestionExport { ingestion_id, .. } =
2181 source.data_source
2182 {
2183 policy = Some(
2184 self.catalog()
2185 .get_entry(&ingestion_id)
2186 .source()
2187 .expect("must be source")
2188 .custom_logical_compaction_window
2189 .unwrap_or_default(),
2190 );
2191 }
2192 }
2193 policies_to_set
2194 .entry(policy.expect("sources have a compaction window"))
2195 .or_insert_with(Default::default)
2196 .storage_ids
2197 .insert(source.global_id());
2198 }
2199 CatalogItem::Table(table) => {
2200 policies_to_set
2201 .entry(policy.expect("tables have a compaction window"))
2202 .or_insert_with(Default::default)
2203 .storage_ids
2204 .extend(table.global_ids());
2205 }
2206 CatalogItem::Index(idx) => {
2207 let policy_entry = policies_to_set
2208 .entry(policy.expect("indexes have a compaction window"))
2209 .or_insert_with(Default::default);
2210
2211 if logs.contains(&idx.on) {
2212 policy_entry
2213 .compute_ids
2214 .entry(idx.cluster_id)
2215 .or_insert_with(BTreeSet::new)
2216 .insert(idx.global_id());
2217 } else {
2218 let df_desc = self
2219 .catalog()
2220 .try_get_physical_plan(&idx.global_id())
2221 .expect("added in `bootstrap_dataflow_plans`")
2222 .clone();
2223
2224 let df_meta = self
2225 .catalog()
2226 .try_get_dataflow_metainfo(&idx.global_id())
2227 .expect("added in `bootstrap_dataflow_plans`");
2228
2229 if self.catalog().state().system_config().enable_mz_notices() {
2230 self.catalog().state().pack_optimizer_notices(
2232 &mut builtin_table_updates,
2233 df_meta.optimizer_notices.iter(),
2234 Diff::ONE,
2235 );
2236 }
2237
2238 policy_entry
2241 .compute_ids
2242 .entry(idx.cluster_id)
2243 .or_insert_with(Default::default)
2244 .extend(df_desc.export_ids());
2245
2246 self.controller
2247 .compute
2248 .create_dataflow(idx.cluster_id, df_desc, None)
2249 .unwrap_or_terminate("cannot fail to create dataflows");
2250 }
2251 }
2252 CatalogItem::View(_) => (),
2253 CatalogItem::MaterializedView(mview) => {
2254 policies_to_set
2255 .entry(policy.expect("materialized views have a compaction window"))
2256 .or_insert_with(Default::default)
2257 .storage_ids
2258 .insert(mview.global_id_writes());
2259
2260 let mut df_desc = self
2261 .catalog()
2262 .try_get_physical_plan(&mview.global_id_writes())
2263 .expect("added in `bootstrap_dataflow_plans`")
2264 .clone();
2265
2266 if let Some(initial_as_of) = mview.initial_as_of.clone() {
2267 df_desc.set_initial_as_of(initial_as_of);
2268 }
2269
2270 let until = mview
2272 .refresh_schedule
2273 .as_ref()
2274 .and_then(|s| s.last_refresh())
2275 .and_then(|r| r.try_step_forward());
2276 if let Some(until) = until {
2277 df_desc.until.meet_assign(&Antichain::from_elem(until));
2278 }
2279
2280 let df_meta = self
2281 .catalog()
2282 .try_get_dataflow_metainfo(&mview.global_id_writes())
2283 .expect("added in `bootstrap_dataflow_plans`");
2284
2285 if self.catalog().state().system_config().enable_mz_notices() {
2286 self.catalog().state().pack_optimizer_notices(
2288 &mut builtin_table_updates,
2289 df_meta.optimizer_notices.iter(),
2290 Diff::ONE,
2291 );
2292 }
2293
2294 self.ship_dataflow(df_desc, mview.cluster_id, mview.target_replica)
2295 .await;
2296
2297 if mview.replacement_target.is_none() {
2300 self.allow_writes(mview.cluster_id, mview.global_id_writes());
2301 }
2302 }
2303 CatalogItem::Sink(sink) => {
2304 policies_to_set
2305 .entry(CompactionWindow::Default)
2306 .or_insert_with(Default::default)
2307 .storage_ids
2308 .insert(sink.global_id());
2309 }
2310 CatalogItem::Connection(catalog_connection) => {
2311 if let ConnectionDetails::AwsPrivatelink(conn) = &catalog_connection.details {
2312 privatelink_connections.insert(
2313 entry.id(),
2314 VpcEndpointConfig {
2315 aws_service_name: conn.service_name.clone(),
2316 availability_zone_ids: conn.availability_zones.clone(),
2317 },
2318 );
2319 }
2320 }
2321 CatalogItem::ContinualTask(ct) => {
2322 policies_to_set
2323 .entry(policy.expect("continual tasks have a compaction window"))
2324 .or_insert_with(Default::default)
2325 .storage_ids
2326 .insert(ct.global_id());
2327
2328 let mut df_desc = self
2329 .catalog()
2330 .try_get_physical_plan(&ct.global_id())
2331 .expect("added in `bootstrap_dataflow_plans`")
2332 .clone();
2333
2334 if let Some(initial_as_of) = ct.initial_as_of.clone() {
2335 df_desc.set_initial_as_of(initial_as_of);
2336 }
2337
2338 let df_meta = self
2339 .catalog()
2340 .try_get_dataflow_metainfo(&ct.global_id())
2341 .expect("added in `bootstrap_dataflow_plans`");
2342
2343 if self.catalog().state().system_config().enable_mz_notices() {
2344 self.catalog().state().pack_optimizer_notices(
2346 &mut builtin_table_updates,
2347 df_meta.optimizer_notices.iter(),
2348 Diff::ONE,
2349 );
2350 }
2351
2352 self.ship_dataflow(df_desc, ct.cluster_id, None).await;
2353 self.allow_writes(ct.cluster_id, ct.global_id());
2354 }
2355 CatalogItem::Log(_)
2357 | CatalogItem::Type(_)
2358 | CatalogItem::Func(_)
2359 | CatalogItem::Secret(_) => {}
2360 }
2361 }
2362
2363 if let Some(cloud_resource_controller) = &self.cloud_resource_controller {
2364 let existing_vpc_endpoints = cloud_resource_controller
2366 .list_vpc_endpoints()
2367 .await
2368 .context("list vpc endpoints")?;
2369 let existing_vpc_endpoints = BTreeSet::from_iter(existing_vpc_endpoints.into_keys());
2370 let desired_vpc_endpoints = privatelink_connections.keys().cloned().collect();
2371 let vpc_endpoints_to_remove = existing_vpc_endpoints.difference(&desired_vpc_endpoints);
2372 for id in vpc_endpoints_to_remove {
2373 cloud_resource_controller
2374 .delete_vpc_endpoint(*id)
2375 .await
2376 .context("deleting extraneous vpc endpoint")?;
2377 }
2378
2379 for (id, spec) in privatelink_connections {
2381 cloud_resource_controller
2382 .ensure_vpc_endpoint(id, spec)
2383 .await
2384 .context("ensuring vpc endpoint")?;
2385 }
2386 }
2387
2388 drop(dataflow_read_holds);
2391 for (cw, policies) in policies_to_set {
2393 self.initialize_read_policies(&policies, cw).await;
2394 }
2395
2396 builtin_table_updates.extend(
2398 self.catalog().state().resolve_builtin_table_updates(
2399 self.catalog().state().pack_all_replica_size_updates(),
2400 ),
2401 );
2402
2403 debug!("startup: coordinator init: bootstrap: initializing migrated builtin tables");
2404 let migrated_updates_fut = if self.controller.read_only() {
2410 let min_timestamp = Timestamp::minimum();
2411 let migrated_builtin_table_updates: Vec<_> = builtin_table_updates
2412 .extract_if(.., |update| {
2413 let gid = self.catalog().get_entry(&update.id).latest_global_id();
2414 migrated_storage_collections_0dt.contains(&update.id)
2415 && self
2416 .controller
2417 .storage_collections
2418 .collection_frontiers(gid)
2419 .expect("all tables are registered")
2420 .write_frontier
2421 .elements()
2422 == &[min_timestamp]
2423 })
2424 .collect();
2425 if migrated_builtin_table_updates.is_empty() {
2426 futures::future::ready(()).boxed()
2427 } else {
2428 let mut grouped_appends: BTreeMap<GlobalId, Vec<TableData>> = BTreeMap::new();
2430 for update in migrated_builtin_table_updates {
2431 let gid = self.catalog().get_entry(&update.id).latest_global_id();
2432 grouped_appends.entry(gid).or_default().push(update.data);
2433 }
2434 info!(
2435 "coordinator init: rehydrating migrated builtin tables in read-only mode: {:?}",
2436 grouped_appends.keys().collect::<Vec<_>>()
2437 );
2438
2439 let mut all_appends = Vec::with_capacity(grouped_appends.len());
2441 for (item_id, table_data) in grouped_appends.into_iter() {
2442 let mut all_rows = Vec::new();
2443 let mut all_data = Vec::new();
2444 for data in table_data {
2445 match data {
2446 TableData::Rows(rows) => all_rows.extend(rows),
2447 TableData::Batches(_) => all_data.push(data),
2448 }
2449 }
2450 differential_dataflow::consolidation::consolidate(&mut all_rows);
2451 all_data.push(TableData::Rows(all_rows));
2452
2453 all_appends.push((item_id, all_data));
2455 }
2456
2457 let fut = self
2458 .controller
2459 .storage
2460 .append_table(min_timestamp, boot_ts.step_forward(), all_appends)
2461 .expect("cannot fail to append");
2462 async {
2463 fut.await
2464 .expect("One-shot shouldn't be dropped during bootstrap")
2465 .unwrap_or_terminate("cannot fail to append")
2466 }
2467 .boxed()
2468 }
2469 } else {
2470 futures::future::ready(()).boxed()
2471 };
2472
2473 info!(
2474 "startup: coordinator init: bootstrap: postamble complete in {:?}",
2475 postamble_start.elapsed()
2476 );
2477
2478 let builtin_update_start = Instant::now();
2479 info!("startup: coordinator init: bootstrap: generate builtin updates beginning");
2480
2481 if self.controller.read_only() {
2482 info!(
2483 "coordinator init: bootstrap: stashing builtin table updates while in read-only mode"
2484 );
2485
2486 let audit_join_start = Instant::now();
2488 info!("startup: coordinator init: bootstrap: audit log deserialization beginning");
2489 let audit_log_updates: Vec<_> = audit_logs_iterator
2490 .map(|(audit_log, ts)| StateUpdate {
2491 kind: StateUpdateKind::AuditLog(audit_log),
2492 ts,
2493 diff: StateDiff::Addition,
2494 })
2495 .collect();
2496 let audit_log_builtin_table_updates = self
2497 .catalog()
2498 .state()
2499 .generate_builtin_table_updates(audit_log_updates);
2500 builtin_table_updates.extend(audit_log_builtin_table_updates);
2501 info!(
2502 "startup: coordinator init: bootstrap: audit log deserialization complete in {:?}",
2503 audit_join_start.elapsed()
2504 );
2505 self.buffered_builtin_table_updates
2506 .as_mut()
2507 .expect("in read-only mode")
2508 .append(&mut builtin_table_updates);
2509 } else {
2510 self.bootstrap_tables(&entries, builtin_table_updates, audit_logs_iterator)
2511 .await;
2512 };
2513 info!(
2514 "startup: coordinator init: bootstrap: generate builtin updates complete in {:?}",
2515 builtin_update_start.elapsed()
2516 );
2517
2518 let cleanup_secrets_start = Instant::now();
2519 info!("startup: coordinator init: bootstrap: generate secret cleanup beginning");
2520 {
2524 let Self {
2527 secrets_controller,
2528 catalog,
2529 ..
2530 } = self;
2531
2532 let next_user_item_id = catalog.get_next_user_item_id().await?;
2533 let next_system_item_id = catalog.get_next_system_item_id().await?;
2534 let read_only = self.controller.read_only();
2535 let catalog_ids: BTreeSet<CatalogItemId> =
2540 catalog.entries().map(|entry| entry.id()).collect();
2541 let secrets_controller = Arc::clone(secrets_controller);
2542
2543 spawn(|| "cleanup-orphaned-secrets", async move {
2544 if read_only {
2545 info!(
2546 "coordinator init: not cleaning up orphaned secrets while in read-only mode"
2547 );
2548 return;
2549 }
2550 info!("coordinator init: cleaning up orphaned secrets");
2551
2552 match secrets_controller.list().await {
2553 Ok(controller_secrets) => {
2554 let controller_secrets: BTreeSet<CatalogItemId> =
2555 controller_secrets.into_iter().collect();
2556 let orphaned = controller_secrets.difference(&catalog_ids);
2557 for id in orphaned {
2558 let id_too_large = match id {
2559 CatalogItemId::System(id) => *id >= next_system_item_id,
2560 CatalogItemId::User(id) => *id >= next_user_item_id,
2561 CatalogItemId::IntrospectionSourceIndex(_)
2562 | CatalogItemId::Transient(_) => false,
2563 };
2564 if id_too_large {
2565 info!(
2566 %next_user_item_id, %next_system_item_id,
2567 "coordinator init: not deleting orphaned secret {id} that was likely created by a newer deploy generation"
2568 );
2569 } else {
2570 info!("coordinator init: deleting orphaned secret {id}");
2571 fail_point!("orphan_secrets");
2572 if let Err(e) = secrets_controller.delete(*id).await {
2573 warn!(
2574 "Dropping orphaned secret has encountered an error: {}",
2575 e
2576 );
2577 }
2578 }
2579 }
2580 }
2581 Err(e) => warn!("Failed to list secrets during orphan cleanup: {:?}", e),
2582 }
2583 });
2584 }
2585 info!(
2586 "startup: coordinator init: bootstrap: generate secret cleanup complete in {:?}",
2587 cleanup_secrets_start.elapsed()
2588 );
2589
2590 let final_steps_start = Instant::now();
2592 info!(
2593 "startup: coordinator init: bootstrap: migrate builtin tables in read-only mode beginning"
2594 );
2595 migrated_updates_fut
2596 .instrument(info_span!("coord::bootstrap::final"))
2597 .await;
2598
2599 debug!(
2600 "startup: coordinator init: bootstrap: announcing completion of initialization to controller"
2601 );
2602 self.controller.initialization_complete();
2604
2605 self.bootstrap_introspection_subscribes().await;
2607
2608 info!(
2609 "startup: coordinator init: bootstrap: migrate builtin tables in read-only mode complete in {:?}",
2610 final_steps_start.elapsed()
2611 );
2612
2613 info!(
2614 "startup: coordinator init: bootstrap complete in {:?}",
2615 bootstrap_start.elapsed()
2616 );
2617 Ok(())
2618 }
2619
2620 #[allow(clippy::async_yields_async)]
2625 #[instrument]
2626 async fn bootstrap_tables(
2627 &mut self,
2628 entries: &[CatalogEntry],
2629 mut builtin_table_updates: Vec<BuiltinTableUpdate>,
2630 audit_logs_iterator: AuditLogIterator,
2631 ) {
2632 struct TableMetadata<'a> {
2634 id: CatalogItemId,
2635 name: &'a QualifiedItemName,
2636 table: &'a Table,
2637 }
2638
2639 let table_metas: Vec<_> = entries
2641 .into_iter()
2642 .filter_map(|entry| {
2643 entry.table().map(|table| TableMetadata {
2644 id: entry.id(),
2645 name: entry.name(),
2646 table,
2647 })
2648 })
2649 .collect();
2650
2651 debug!("coordinator init: advancing all tables to current timestamp");
2653 let WriteTimestamp {
2654 timestamp: write_ts,
2655 advance_to,
2656 } = self.get_local_write_ts().await;
2657 let appends = table_metas
2658 .iter()
2659 .map(|meta| (meta.table.global_id_writes(), Vec::new()))
2660 .collect();
2661 let table_fence_rx = self
2665 .controller
2666 .storage
2667 .append_table(write_ts.clone(), advance_to, appends)
2668 .expect("invalid updates");
2669
2670 self.apply_local_write(write_ts).await;
2671
2672 debug!("coordinator init: resetting system tables");
2674 let read_ts = self.get_local_read_ts().await;
2675
2676 let mz_storage_usage_by_shard_schema: SchemaSpecifier = self
2679 .catalog()
2680 .resolve_system_schema(MZ_STORAGE_USAGE_BY_SHARD.schema)
2681 .into();
2682 let is_storage_usage_by_shard = |meta: &TableMetadata| -> bool {
2683 meta.name.item == MZ_STORAGE_USAGE_BY_SHARD.name
2684 && meta.name.qualifiers.schema_spec == mz_storage_usage_by_shard_schema
2685 };
2686
2687 let mut retraction_tasks = Vec::new();
2688 let mut system_tables: Vec<_> = table_metas
2689 .iter()
2690 .filter(|meta| meta.id.is_system() && !is_storage_usage_by_shard(meta))
2691 .collect();
2692
2693 let (audit_events_idx, _) = system_tables
2695 .iter()
2696 .find_position(|table| {
2697 table.id == self.catalog().resolve_builtin_table(&MZ_AUDIT_EVENTS)
2698 })
2699 .expect("mz_audit_events must exist");
2700 let audit_events = system_tables.remove(audit_events_idx);
2701 let audit_log_task = self.bootstrap_audit_log_table(
2702 audit_events.id,
2703 audit_events.name,
2704 audit_events.table,
2705 audit_logs_iterator,
2706 read_ts,
2707 );
2708
2709 for system_table in system_tables {
2710 let table_id = system_table.id;
2711 let full_name = self.catalog().resolve_full_name(system_table.name, None);
2712 debug!("coordinator init: resetting system table {full_name} ({table_id})");
2713
2714 let snapshot_fut = self
2716 .controller
2717 .storage_collections
2718 .snapshot_cursor(system_table.table.global_id_writes(), read_ts);
2719 let batch_fut = self
2720 .controller
2721 .storage_collections
2722 .create_update_builder(system_table.table.global_id_writes());
2723
2724 let task = spawn(|| format!("snapshot-{table_id}"), async move {
2725 let mut batch = batch_fut
2727 .await
2728 .unwrap_or_terminate("cannot fail to create a batch for a BuiltinTable");
2729 tracing::info!(?table_id, "starting snapshot");
2730 let mut snapshot_cursor = snapshot_fut
2732 .await
2733 .unwrap_or_terminate("cannot fail to snapshot");
2734
2735 while let Some(values) = snapshot_cursor.next().await {
2737 for (key, _t, d) in values {
2738 let d_invert = d.neg();
2739 batch.add(&key, &(), &d_invert).await;
2740 }
2741 }
2742 tracing::info!(?table_id, "finished snapshot");
2743
2744 let batch = batch.finish().await;
2745 BuiltinTableUpdate::batch(table_id, batch)
2746 });
2747 retraction_tasks.push(task);
2748 }
2749
2750 let retractions_res = futures::future::join_all(retraction_tasks).await;
2751 for retractions in retractions_res {
2752 builtin_table_updates.push(retractions);
2753 }
2754
2755 let audit_join_start = Instant::now();
2756 info!("startup: coordinator init: bootstrap: join audit log deserialization beginning");
2757 let audit_log_updates = audit_log_task.await;
2758 let audit_log_builtin_table_updates = self
2759 .catalog()
2760 .state()
2761 .generate_builtin_table_updates(audit_log_updates);
2762 builtin_table_updates.extend(audit_log_builtin_table_updates);
2763 info!(
2764 "startup: coordinator init: bootstrap: join audit log deserialization complete in {:?}",
2765 audit_join_start.elapsed()
2766 );
2767
2768 table_fence_rx
2770 .await
2771 .expect("One-shot shouldn't be dropped during bootstrap")
2772 .unwrap_or_terminate("cannot fail to append");
2773
2774 info!("coordinator init: sending builtin table updates");
2775 let (_builtin_updates_fut, write_ts) = self
2776 .builtin_table_update()
2777 .execute(builtin_table_updates)
2778 .await;
2779 info!(?write_ts, "our write ts");
2780 if let Some(write_ts) = write_ts {
2781 self.apply_local_write(write_ts).await;
2782 }
2783 }
2784
2785 #[instrument]
2789 fn bootstrap_audit_log_table<'a>(
2790 &self,
2791 table_id: CatalogItemId,
2792 name: &'a QualifiedItemName,
2793 table: &'a Table,
2794 audit_logs_iterator: AuditLogIterator,
2795 read_ts: Timestamp,
2796 ) -> JoinHandle<Vec<StateUpdate>> {
2797 let full_name = self.catalog().resolve_full_name(name, None);
2798 debug!("coordinator init: reconciling audit log: {full_name} ({table_id})");
2799 let current_contents_fut = self
2800 .controller
2801 .storage_collections
2802 .snapshot(table.global_id_writes(), read_ts);
2803 spawn(|| format!("snapshot-audit-log-{table_id}"), async move {
2804 let current_contents = current_contents_fut
2805 .await
2806 .unwrap_or_terminate("cannot fail to fetch snapshot");
2807 let contents_len = current_contents.len();
2808 debug!("coordinator init: audit log table ({table_id}) size {contents_len}");
2809
2810 let max_table_id = current_contents
2812 .into_iter()
2813 .filter(|(_, diff)| *diff == 1)
2814 .map(|(row, _diff)| row.unpack_first().unwrap_uint64())
2815 .sorted()
2816 .rev()
2817 .next();
2818
2819 audit_logs_iterator
2821 .take_while(|(audit_log, _)| match max_table_id {
2822 Some(id) => audit_log.event.sortable_id() > id,
2823 None => true,
2824 })
2825 .map(|(audit_log, ts)| StateUpdate {
2826 kind: StateUpdateKind::AuditLog(audit_log),
2827 ts,
2828 diff: StateDiff::Addition,
2829 })
2830 .collect::<Vec<_>>()
2831 })
2832 }
2833
2834 #[instrument]
2847 async fn bootstrap_storage_collections(
2848 &mut self,
2849 migrated_storage_collections: &BTreeSet<CatalogItemId>,
2850 ) {
2851 let catalog = self.catalog();
2852
2853 let source_desc = |object_id: GlobalId,
2854 data_source: &DataSourceDesc,
2855 desc: &RelationDesc,
2856 timeline: &Timeline| {
2857 let data_source = match data_source.clone() {
2858 DataSourceDesc::Ingestion { desc, cluster_id } => {
2860 let desc = desc.into_inline_connection(catalog.state());
2861 let ingestion = IngestionDescription::new(desc, cluster_id, object_id);
2862 DataSource::Ingestion(ingestion)
2863 }
2864 DataSourceDesc::OldSyntaxIngestion {
2865 desc,
2866 progress_subsource,
2867 data_config,
2868 details,
2869 cluster_id,
2870 } => {
2871 let desc = desc.into_inline_connection(catalog.state());
2872 let data_config = data_config.into_inline_connection(catalog.state());
2873 let progress_subsource =
2876 catalog.get_entry(&progress_subsource).latest_global_id();
2877 let mut ingestion =
2878 IngestionDescription::new(desc, cluster_id, progress_subsource);
2879 let legacy_export = SourceExport {
2880 storage_metadata: (),
2881 data_config,
2882 details,
2883 };
2884 ingestion.source_exports.insert(object_id, legacy_export);
2885
2886 DataSource::Ingestion(ingestion)
2887 }
2888 DataSourceDesc::IngestionExport {
2889 ingestion_id,
2890 external_reference: _,
2891 details,
2892 data_config,
2893 } => {
2894 let ingestion_id = catalog.get_entry(&ingestion_id).latest_global_id();
2897
2898 DataSource::IngestionExport {
2899 ingestion_id,
2900 details,
2901 data_config: data_config.into_inline_connection(catalog.state()),
2902 }
2903 }
2904 DataSourceDesc::Webhook { .. } => DataSource::Webhook,
2905 DataSourceDesc::Progress => DataSource::Progress,
2906 DataSourceDesc::Introspection(introspection) => {
2907 DataSource::Introspection(introspection)
2908 }
2909 DataSourceDesc::Catalog => DataSource::Other,
2910 };
2911 CollectionDescription {
2912 desc: desc.clone(),
2913 data_source,
2914 since: None,
2915 timeline: Some(timeline.clone()),
2916 primary: None,
2917 }
2918 };
2919
2920 let mut compute_collections = vec![];
2921 let mut collections = vec![];
2922 for entry in catalog.entries() {
2923 match entry.item() {
2924 CatalogItem::Source(source) => {
2925 collections.push((
2926 source.global_id(),
2927 source_desc(
2928 source.global_id(),
2929 &source.data_source,
2930 &source.desc,
2931 &source.timeline,
2932 ),
2933 ));
2934 }
2935 CatalogItem::Table(table) => {
2936 match &table.data_source {
2937 TableDataSource::TableWrites { defaults: _ } => {
2938 let versions: BTreeMap<_, _> = table
2939 .collection_descs()
2940 .map(|(gid, version, desc)| (version, (gid, desc)))
2941 .collect();
2942 let collection_descs = versions.iter().map(|(version, (gid, desc))| {
2943 let next_version = version.bump();
2944 let primary_collection =
2945 versions.get(&next_version).map(|(gid, _desc)| gid).copied();
2946 let mut collection_desc =
2947 CollectionDescription::for_table(desc.clone());
2948 collection_desc.primary = primary_collection;
2949
2950 (*gid, collection_desc)
2951 });
2952 collections.extend(collection_descs);
2953 }
2954 TableDataSource::DataSource {
2955 desc: data_source_desc,
2956 timeline,
2957 } => {
2958 soft_assert_eq_or_log!(table.collections.len(), 1);
2960 let collection_descs =
2961 table.collection_descs().map(|(gid, _version, desc)| {
2962 (
2963 gid,
2964 source_desc(
2965 entry.latest_global_id(),
2966 data_source_desc,
2967 &desc,
2968 timeline,
2969 ),
2970 )
2971 });
2972 collections.extend(collection_descs);
2973 }
2974 };
2975 }
2976 CatalogItem::MaterializedView(mv) => {
2977 let collection_descs = mv.collection_descs().map(|(gid, _version, desc)| {
2978 let collection_desc =
2979 CollectionDescription::for_other(desc, mv.initial_as_of.clone());
2980 (gid, collection_desc)
2981 });
2982
2983 collections.extend(collection_descs);
2984 compute_collections.push((mv.global_id_writes(), mv.desc.latest()));
2985 }
2986 CatalogItem::ContinualTask(ct) => {
2987 let collection_desc =
2988 CollectionDescription::for_other(ct.desc.clone(), ct.initial_as_of.clone());
2989 compute_collections.push((ct.global_id(), ct.desc.clone()));
2990 collections.push((ct.global_id(), collection_desc));
2991 }
2992 CatalogItem::Sink(sink) => {
2993 let storage_sink_from_entry = self.catalog().get_entry_by_global_id(&sink.from);
2994 let from_desc = storage_sink_from_entry
2995 .relation_desc()
2996 .expect("sinks can only be built on items with descs")
2997 .into_owned();
2998 let collection_desc = CollectionDescription {
2999 desc: KAFKA_PROGRESS_DESC.clone(),
3001 data_source: DataSource::Sink {
3002 desc: ExportDescription {
3003 sink: StorageSinkDesc {
3004 from: sink.from,
3005 from_desc,
3006 connection: sink
3007 .connection
3008 .clone()
3009 .into_inline_connection(self.catalog().state()),
3010 envelope: sink.envelope,
3011 as_of: Antichain::from_elem(Timestamp::minimum()),
3012 with_snapshot: sink.with_snapshot,
3013 version: sink.version,
3014 from_storage_metadata: (),
3015 to_storage_metadata: (),
3016 commit_interval: sink.commit_interval,
3017 },
3018 instance_id: sink.cluster_id,
3019 },
3020 },
3021 since: None,
3022 timeline: None,
3023 primary: None,
3024 };
3025 collections.push((sink.global_id, collection_desc));
3026 }
3027 CatalogItem::Log(_)
3028 | CatalogItem::View(_)
3029 | CatalogItem::Index(_)
3030 | CatalogItem::Type(_)
3031 | CatalogItem::Func(_)
3032 | CatalogItem::Secret(_)
3033 | CatalogItem::Connection(_) => (),
3034 }
3035 }
3036
3037 let register_ts = if self.controller.read_only() {
3038 self.get_local_read_ts().await
3039 } else {
3040 self.get_local_write_ts().await.timestamp
3043 };
3044
3045 let storage_metadata = self.catalog.state().storage_metadata();
3046 let migrated_storage_collections = migrated_storage_collections
3047 .into_iter()
3048 .flat_map(|item_id| self.catalog.get_entry(item_id).global_ids())
3049 .collect();
3050
3051 self.controller
3056 .storage
3057 .evolve_nullability_for_bootstrap(storage_metadata, compute_collections)
3058 .await
3059 .unwrap_or_terminate("cannot fail to evolve collections");
3060
3061 let mut pending: BTreeMap<_, _> = collections.into_iter().collect();
3074
3075 let transitive_dep_gids: BTreeMap<_, _> = pending
3077 .keys()
3078 .map(|gid| {
3079 let entry = self.catalog.get_entry_by_global_id(gid);
3080 let item_id = entry.id();
3081 let deps = self.catalog.state().transitive_uses(item_id);
3082 let dep_gids: BTreeSet<_> = deps
3083 .filter(|dep_id| *dep_id != item_id)
3086 .map(|dep_id| self.catalog.get_entry(&dep_id).latest_global_id())
3087 .filter(|dep_gid| pending.contains_key(dep_gid))
3089 .collect();
3090 (*gid, dep_gids)
3091 })
3092 .collect();
3093
3094 while !pending.is_empty() {
3095 let ready_gids: BTreeSet<_> = pending
3098 .keys()
3099 .filter(|gid| {
3100 let mut deps = transitive_dep_gids[gid].iter();
3101 !deps.any(|dep_gid| pending.contains_key(dep_gid))
3102 })
3103 .copied()
3104 .collect();
3105 let mut ready: Vec<_> = pending
3106 .extract_if(.., |gid, _| ready_gids.contains(gid))
3107 .collect();
3108
3109 for (gid, collection) in &mut ready {
3111 if !gid.is_system() || collection.since.is_some() {
3113 continue;
3114 }
3115
3116 let mut derived_since = Antichain::from_elem(Timestamp::MIN);
3117 for dep_gid in &transitive_dep_gids[gid] {
3118 let (since, _) = self
3119 .controller
3120 .storage
3121 .collection_frontiers(*dep_gid)
3122 .expect("previously registered");
3123 derived_since.join_assign(&since);
3124 }
3125 collection.since = Some(derived_since);
3126 }
3127
3128 if ready.is_empty() {
3129 soft_panic_or_log!(
3130 "cycle in storage collections: {:?}",
3131 pending.keys().collect::<Vec<_>>(),
3132 );
3133 ready = mem::take(&mut pending).into_iter().collect();
3137 }
3138
3139 self.controller
3140 .storage
3141 .create_collections_for_bootstrap(
3142 storage_metadata,
3143 Some(register_ts),
3144 ready,
3145 &migrated_storage_collections,
3146 )
3147 .await
3148 .unwrap_or_terminate("cannot fail to create collections");
3149 }
3150
3151 if !self.controller.read_only() {
3152 self.apply_local_write(register_ts).await;
3153 }
3154 }
3155
3156 fn bootstrap_sort_catalog_entries(&self) -> Vec<CatalogEntry> {
3163 let mut indexes_on = BTreeMap::<_, Vec<_>>::new();
3164 let mut non_indexes = Vec::new();
3165 for entry in self.catalog().entries().cloned() {
3166 if let Some(index) = entry.index() {
3167 let on = self.catalog().get_entry_by_global_id(&index.on);
3168 indexes_on.entry(on.id()).or_default().push(entry);
3169 } else {
3170 non_indexes.push(entry);
3171 }
3172 }
3173
3174 let key_fn = |entry: &CatalogEntry| entry.id;
3175 let dependencies_fn = |entry: &CatalogEntry| entry.uses();
3176 sort_topological(&mut non_indexes, key_fn, dependencies_fn);
3177
3178 let mut result = Vec::new();
3179 for entry in non_indexes {
3180 let id = entry.id();
3181 result.push(entry);
3182 if let Some(mut indexes) = indexes_on.remove(&id) {
3183 result.append(&mut indexes);
3184 }
3185 }
3186
3187 soft_assert_or_log!(
3188 indexes_on.is_empty(),
3189 "indexes with missing dependencies: {indexes_on:?}",
3190 );
3191
3192 result
3193 }
3194
3195 #[instrument]
3206 fn bootstrap_dataflow_plans(
3207 &mut self,
3208 ordered_catalog_entries: &[CatalogEntry],
3209 mut cached_global_exprs: BTreeMap<GlobalId, GlobalExpressions>,
3210 ) -> Result<BTreeMap<GlobalId, GlobalExpressions>, AdapterError> {
3211 let mut instance_snapshots = BTreeMap::new();
3217 let mut uncached_expressions = BTreeMap::new();
3218
3219 let optimizer_config = |catalog: &Catalog, cluster_id| {
3220 let system_config = catalog.system_config();
3221 let overrides = catalog.get_cluster(cluster_id).config.features();
3222 OptimizerConfig::from(system_config).override_from(&overrides)
3223 };
3224
3225 for entry in ordered_catalog_entries {
3226 match entry.item() {
3227 CatalogItem::Index(idx) => {
3228 let compute_instance =
3230 instance_snapshots.entry(idx.cluster_id).or_insert_with(|| {
3231 self.instance_snapshot(idx.cluster_id)
3232 .expect("compute instance exists")
3233 });
3234 let global_id = idx.global_id();
3235
3236 if compute_instance.contains_collection(&global_id) {
3239 continue;
3240 }
3241
3242 let optimizer_config = optimizer_config(&self.catalog, idx.cluster_id);
3243
3244 let (optimized_plan, physical_plan, metainfo) =
3245 match cached_global_exprs.remove(&global_id) {
3246 Some(global_expressions)
3247 if global_expressions.optimizer_features
3248 == optimizer_config.features =>
3249 {
3250 debug!("global expression cache hit for {global_id:?}");
3251 (
3252 global_expressions.global_mir,
3253 global_expressions.physical_plan,
3254 global_expressions.dataflow_metainfos,
3255 )
3256 }
3257 Some(_) | None => {
3258 let (optimized_plan, global_lir_plan) = {
3259 let mut optimizer = optimize::index::Optimizer::new(
3261 self.owned_catalog(),
3262 compute_instance.clone(),
3263 global_id,
3264 optimizer_config.clone(),
3265 self.optimizer_metrics(),
3266 );
3267
3268 let index_plan = optimize::index::Index::new(
3270 entry.name().clone(),
3271 idx.on,
3272 idx.keys.to_vec(),
3273 );
3274 let global_mir_plan = optimizer.optimize(index_plan)?;
3275 let optimized_plan = global_mir_plan.df_desc().clone();
3276
3277 let global_lir_plan = optimizer.optimize(global_mir_plan)?;
3279
3280 (optimized_plan, global_lir_plan)
3281 };
3282
3283 let (physical_plan, metainfo) = global_lir_plan.unapply();
3284 let metainfo = {
3285 let notice_ids =
3287 std::iter::repeat_with(|| self.allocate_transient_id())
3288 .map(|(_item_id, gid)| gid)
3289 .take(metainfo.optimizer_notices.len())
3290 .collect::<Vec<_>>();
3291 self.catalog().render_notices(
3293 metainfo,
3294 notice_ids,
3295 Some(idx.global_id()),
3296 )
3297 };
3298 uncached_expressions.insert(
3299 global_id,
3300 GlobalExpressions {
3301 global_mir: optimized_plan.clone(),
3302 physical_plan: physical_plan.clone(),
3303 dataflow_metainfos: metainfo.clone(),
3304 optimizer_features: optimizer_config.features.clone(),
3305 },
3306 );
3307 (optimized_plan, physical_plan, metainfo)
3308 }
3309 };
3310
3311 let catalog = self.catalog_mut();
3312 catalog.set_optimized_plan(idx.global_id(), optimized_plan);
3313 catalog.set_physical_plan(idx.global_id(), physical_plan);
3314 catalog.set_dataflow_metainfo(idx.global_id(), metainfo);
3315
3316 compute_instance.insert_collection(idx.global_id());
3317 }
3318 CatalogItem::MaterializedView(mv) => {
3319 let compute_instance =
3321 instance_snapshots.entry(mv.cluster_id).or_insert_with(|| {
3322 self.instance_snapshot(mv.cluster_id)
3323 .expect("compute instance exists")
3324 });
3325 let global_id = mv.global_id_writes();
3326
3327 let optimizer_config = optimizer_config(&self.catalog, mv.cluster_id);
3328
3329 let (optimized_plan, physical_plan, metainfo) = match cached_global_exprs
3330 .remove(&global_id)
3331 {
3332 Some(global_expressions)
3333 if global_expressions.optimizer_features
3334 == optimizer_config.features =>
3335 {
3336 debug!("global expression cache hit for {global_id:?}");
3337 (
3338 global_expressions.global_mir,
3339 global_expressions.physical_plan,
3340 global_expressions.dataflow_metainfos,
3341 )
3342 }
3343 Some(_) | None => {
3344 let (_, internal_view_id) = self.allocate_transient_id();
3345 let debug_name = self
3346 .catalog()
3347 .resolve_full_name(entry.name(), None)
3348 .to_string();
3349 let force_non_monotonic = Default::default();
3350
3351 let (optimized_plan, global_lir_plan) = {
3352 let mut optimizer = optimize::materialized_view::Optimizer::new(
3354 self.owned_catalog().as_optimizer_catalog(),
3355 compute_instance.clone(),
3356 global_id,
3357 internal_view_id,
3358 mv.desc.latest().iter_names().cloned().collect(),
3359 mv.non_null_assertions.clone(),
3360 mv.refresh_schedule.clone(),
3361 debug_name,
3362 optimizer_config.clone(),
3363 self.optimizer_metrics(),
3364 force_non_monotonic,
3365 );
3366
3367 let typ = infer_sql_type_for_catalog(
3370 &mv.raw_expr,
3371 &mv.locally_optimized_expr.as_ref().clone(),
3372 );
3373 let global_mir_plan = optimizer
3374 .optimize((mv.locally_optimized_expr.as_ref().clone(), typ))?;
3375 let optimized_plan = global_mir_plan.df_desc().clone();
3376
3377 let global_lir_plan = optimizer.optimize(global_mir_plan)?;
3379
3380 (optimized_plan, global_lir_plan)
3381 };
3382
3383 let (physical_plan, metainfo) = global_lir_plan.unapply();
3384 let metainfo = {
3385 let notice_ids =
3387 std::iter::repeat_with(|| self.allocate_transient_id())
3388 .map(|(_item_id, global_id)| global_id)
3389 .take(metainfo.optimizer_notices.len())
3390 .collect::<Vec<_>>();
3391 self.catalog().render_notices(
3393 metainfo,
3394 notice_ids,
3395 Some(mv.global_id_writes()),
3396 )
3397 };
3398 uncached_expressions.insert(
3399 global_id,
3400 GlobalExpressions {
3401 global_mir: optimized_plan.clone(),
3402 physical_plan: physical_plan.clone(),
3403 dataflow_metainfos: metainfo.clone(),
3404 optimizer_features: optimizer_config.features.clone(),
3405 },
3406 );
3407 (optimized_plan, physical_plan, metainfo)
3408 }
3409 };
3410
3411 let catalog = self.catalog_mut();
3412 catalog.set_optimized_plan(mv.global_id_writes(), optimized_plan);
3413 catalog.set_physical_plan(mv.global_id_writes(), physical_plan);
3414 catalog.set_dataflow_metainfo(mv.global_id_writes(), metainfo);
3415
3416 compute_instance.insert_collection(mv.global_id_writes());
3417 }
3418 CatalogItem::ContinualTask(ct) => {
3419 let compute_instance =
3420 instance_snapshots.entry(ct.cluster_id).or_insert_with(|| {
3421 self.instance_snapshot(ct.cluster_id)
3422 .expect("compute instance exists")
3423 });
3424 let global_id = ct.global_id();
3425
3426 let optimizer_config = optimizer_config(&self.catalog, ct.cluster_id);
3427
3428 let (optimized_plan, physical_plan, metainfo) =
3429 match cached_global_exprs.remove(&global_id) {
3430 Some(global_expressions)
3431 if global_expressions.optimizer_features
3432 == optimizer_config.features =>
3433 {
3434 debug!("global expression cache hit for {global_id:?}");
3435 (
3436 global_expressions.global_mir,
3437 global_expressions.physical_plan,
3438 global_expressions.dataflow_metainfos,
3439 )
3440 }
3441 Some(_) | None => {
3442 let debug_name = self
3443 .catalog()
3444 .resolve_full_name(entry.name(), None)
3445 .to_string();
3446 let (optimized_plan, physical_plan, metainfo, optimizer_features) =
3447 self.optimize_create_continual_task(
3448 ct,
3449 global_id,
3450 self.owned_catalog(),
3451 debug_name,
3452 )?;
3453 uncached_expressions.insert(
3454 global_id,
3455 GlobalExpressions {
3456 global_mir: optimized_plan.clone(),
3457 physical_plan: physical_plan.clone(),
3458 dataflow_metainfos: metainfo.clone(),
3459 optimizer_features,
3460 },
3461 );
3462 (optimized_plan, physical_plan, metainfo)
3463 }
3464 };
3465
3466 let catalog = self.catalog_mut();
3467 catalog.set_optimized_plan(ct.global_id(), optimized_plan);
3468 catalog.set_physical_plan(ct.global_id(), physical_plan);
3469 catalog.set_dataflow_metainfo(ct.global_id(), metainfo);
3470
3471 compute_instance.insert_collection(ct.global_id());
3472 }
3473 CatalogItem::Table(_)
3474 | CatalogItem::Source(_)
3475 | CatalogItem::Log(_)
3476 | CatalogItem::View(_)
3477 | CatalogItem::Sink(_)
3478 | CatalogItem::Type(_)
3479 | CatalogItem::Func(_)
3480 | CatalogItem::Secret(_)
3481 | CatalogItem::Connection(_) => (),
3482 }
3483 }
3484
3485 Ok(uncached_expressions)
3486 }
3487
3488 async fn bootstrap_dataflow_as_ofs(&mut self) -> BTreeMap<GlobalId, ReadHold> {
3498 let mut catalog_ids = Vec::new();
3499 let mut dataflows = Vec::new();
3500 let mut read_policies = BTreeMap::new();
3501 for entry in self.catalog.entries() {
3502 let gid = match entry.item() {
3503 CatalogItem::Index(idx) => idx.global_id(),
3504 CatalogItem::MaterializedView(mv) => mv.global_id_writes(),
3505 CatalogItem::ContinualTask(ct) => ct.global_id(),
3506 CatalogItem::Table(_)
3507 | CatalogItem::Source(_)
3508 | CatalogItem::Log(_)
3509 | CatalogItem::View(_)
3510 | CatalogItem::Sink(_)
3511 | CatalogItem::Type(_)
3512 | CatalogItem::Func(_)
3513 | CatalogItem::Secret(_)
3514 | CatalogItem::Connection(_) => continue,
3515 };
3516 if let Some(plan) = self.catalog.try_get_physical_plan(&gid) {
3517 catalog_ids.push(gid);
3518 dataflows.push(plan.clone());
3519
3520 if let Some(compaction_window) = entry.item().initial_logical_compaction_window() {
3521 read_policies.insert(gid, compaction_window.into());
3522 }
3523 }
3524 }
3525
3526 let read_ts = self.get_local_read_ts().await;
3527 let read_holds = as_of_selection::run(
3528 &mut dataflows,
3529 &read_policies,
3530 &*self.controller.storage_collections,
3531 read_ts,
3532 self.controller.read_only(),
3533 );
3534
3535 let catalog = self.catalog_mut();
3536 for (id, plan) in catalog_ids.into_iter().zip_eq(dataflows) {
3537 catalog.set_physical_plan(id, plan);
3538 }
3539
3540 read_holds
3541 }
3542
3543 fn serve(
3552 mut self,
3553 mut internal_cmd_rx: mpsc::UnboundedReceiver<Message>,
3554 mut strict_serializable_reads_rx: mpsc::UnboundedReceiver<(ConnectionId, PendingReadTxn)>,
3555 mut cmd_rx: mpsc::UnboundedReceiver<(OpenTelemetryContext, Command)>,
3556 group_commit_rx: appends::GroupCommitWaiter,
3557 ) -> LocalBoxFuture<'static, ()> {
3558 async move {
3559 let mut cluster_events = self.controller.events_stream();
3561 let last_message = Arc::new(Mutex::new(LastMessage {
3562 kind: "none",
3563 stmt: None,
3564 }));
3565
3566 let (idle_tx, mut idle_rx) = tokio::sync::mpsc::channel(1);
3567 let idle_metric = self.metrics.queue_busy_seconds.clone();
3568 let last_message_watchdog = Arc::clone(&last_message);
3569
3570 spawn(|| "coord watchdog", async move {
3571 let mut interval = tokio::time::interval(Duration::from_secs(5));
3576 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
3580
3581 let mut coord_stuck = false;
3583
3584 loop {
3585 interval.tick().await;
3586
3587 let duration = tokio::time::Duration::from_secs(30);
3589 let timeout = tokio::time::timeout(duration, idle_tx.reserve()).await;
3590 let Ok(maybe_permit) = timeout else {
3591 if !coord_stuck {
3593 let last_message = last_message_watchdog.lock().expect("poisoned");
3594 tracing::warn!(
3595 last_message_kind = %last_message.kind,
3596 last_message_sql = %last_message.stmt_to_string(),
3597 "coordinator stuck for {duration:?}",
3598 );
3599 }
3600 coord_stuck = true;
3601
3602 continue;
3603 };
3604
3605 if coord_stuck {
3607 tracing::info!("Coordinator became unstuck");
3608 }
3609 coord_stuck = false;
3610
3611 let Ok(permit) = maybe_permit else {
3613 break;
3614 };
3615
3616 permit.send(idle_metric.start_timer());
3617 }
3618 });
3619
3620 self.schedule_storage_usage_collection().await;
3621 self.spawn_privatelink_vpc_endpoints_watch_task();
3622 self.spawn_statement_logging_task();
3623 flags::tracing_config(self.catalog.system_config()).apply(&self.tracing_handle);
3624
3625 let warn_threshold = self
3627 .catalog()
3628 .system_config()
3629 .coord_slow_message_warn_threshold();
3630
3631 const MESSAGE_BATCH: usize = 64;
3633 let mut messages = Vec::with_capacity(MESSAGE_BATCH);
3634 let mut cmd_messages = Vec::with_capacity(MESSAGE_BATCH);
3635
3636 let message_batch = self.metrics.message_batch.clone();
3637
3638 loop {
3639 select! {
3643 biased;
3648
3649 _ = internal_cmd_rx.recv_many(&mut messages, MESSAGE_BATCH) => {},
3653 Some(event) = cluster_events.next() => {
3657 messages.push(Message::ClusterEvent(event))
3658 },
3659 () = self.controller.ready() => {
3663 let controller = match self.controller.get_readiness() {
3667 Readiness::Storage => ControllerReadiness::Storage,
3668 Readiness::Compute => ControllerReadiness::Compute,
3669 Readiness::Metrics(_) => ControllerReadiness::Metrics,
3670 Readiness::Internal(_) => ControllerReadiness::Internal,
3671 Readiness::NotReady => unreachable!("just signaled as ready"),
3672 };
3673 messages.push(Message::ControllerReady { controller });
3674 }
3675 permit = group_commit_rx.ready() => {
3678 let user_write_spans = self.pending_writes.iter().flat_map(|x| match x {
3684 PendingWriteTxn::User{span, ..} => Some(span),
3685 PendingWriteTxn::System{..} => None,
3686 });
3687 let span = match user_write_spans.exactly_one() {
3688 Ok(span) => span.clone(),
3689 Err(user_write_spans) => {
3690 let span = info_span!(parent: None, "group_commit_notify");
3691 for s in user_write_spans {
3692 span.follows_from(s);
3693 }
3694 span
3695 }
3696 };
3697 messages.push(Message::GroupCommitInitiate(span, Some(permit)));
3698 },
3699 count = cmd_rx.recv_many(&mut cmd_messages, MESSAGE_BATCH) => {
3703 if count == 0 {
3704 break;
3705 } else {
3706 messages.extend(cmd_messages.drain(..).map(
3707 |(otel_ctx, cmd)| Message::Command(otel_ctx, cmd),
3708 ));
3709 }
3710 },
3711 Some(pending_read_txn) = strict_serializable_reads_rx.recv() => {
3715 let mut pending_read_txns = vec![pending_read_txn];
3716 while let Ok(pending_read_txn) = strict_serializable_reads_rx.try_recv() {
3717 pending_read_txns.push(pending_read_txn);
3718 }
3719 for (conn_id, pending_read_txn) in pending_read_txns {
3720 let prev = self
3721 .pending_linearize_read_txns
3722 .insert(conn_id, pending_read_txn);
3723 soft_assert_or_log!(
3724 prev.is_none(),
3725 "connections can not have multiple concurrent reads, prev: {prev:?}"
3726 )
3727 }
3728 messages.push(Message::LinearizeReads);
3729 }
3730 _ = self.advance_timelines_interval.tick() => {
3734 let span = info_span!(parent: None, "coord::advance_timelines_interval");
3735 span.follows_from(Span::current());
3736
3737 if self.controller.read_only() {
3742 messages.push(Message::AdvanceTimelines);
3743 } else {
3744 messages.push(Message::GroupCommitInitiate(span, None));
3745 }
3746 },
3747 _ = self.check_cluster_scheduling_policies_interval.tick() => {
3751 messages.push(Message::CheckSchedulingPolicies);
3752 },
3753
3754 _ = self.caught_up_check_interval.tick() => {
3758 self.maybe_check_caught_up().await;
3763
3764 continue;
3765 },
3766
3767 timer = idle_rx.recv() => {
3772 timer.expect("does not drop").observe_duration();
3773 self.metrics
3774 .message_handling
3775 .with_label_values(&["watchdog"])
3776 .observe(0.0);
3777 continue;
3778 }
3779 };
3780
3781 message_batch.observe(f64::cast_lossy(messages.len()));
3783
3784 for msg in messages.drain(..) {
3785 let msg_kind = msg.kind();
3788 let span = span!(
3789 target: "mz_adapter::coord::handle_message_loop",
3790 Level::INFO,
3791 "coord::handle_message",
3792 kind = msg_kind
3793 );
3794 let otel_context = span.context().span().span_context().clone();
3795
3796 *last_message.lock().expect("poisoned") = LastMessage {
3800 kind: msg_kind,
3801 stmt: match &msg {
3802 Message::Command(
3803 _,
3804 Command::Execute {
3805 portal_name,
3806 session,
3807 ..
3808 },
3809 ) => session
3810 .get_portal_unverified(portal_name)
3811 .and_then(|p| p.stmt.as_ref().map(Arc::clone)),
3812 _ => None,
3813 },
3814 };
3815
3816 let start = Instant::now();
3817 self.handle_message(msg).instrument(span).await;
3818 let duration = start.elapsed();
3819
3820 self.metrics
3821 .message_handling
3822 .with_label_values(&[msg_kind])
3823 .observe(duration.as_secs_f64());
3824
3825 if duration > warn_threshold {
3827 let trace_id = otel_context.is_valid().then(|| otel_context.trace_id());
3828 tracing::error!(
3829 ?msg_kind,
3830 ?trace_id,
3831 ?duration,
3832 "very slow coordinator message"
3833 );
3834 }
3835 }
3836 }
3837 if let Some(catalog) = Arc::into_inner(self.catalog) {
3840 catalog.expire().await;
3841 }
3842 }
3843 .boxed_local()
3844 }
3845
3846 fn catalog(&self) -> &Catalog {
3848 &self.catalog
3849 }
3850
3851 fn owned_catalog(&self) -> Arc<Catalog> {
3854 Arc::clone(&self.catalog)
3855 }
3856
3857 fn optimizer_metrics(&self) -> OptimizerMetrics {
3860 self.optimizer_metrics.clone()
3861 }
3862
3863 fn catalog_mut(&mut self) -> &mut Catalog {
3865 Arc::make_mut(&mut self.catalog)
3873 }
3874
3875 async fn refill_user_id_pool(&mut self, min_count: u64) -> Result<(), AdapterError> {
3880 let batch_size = USER_ID_POOL_BATCH_SIZE.get(self.catalog().system_config().dyncfgs());
3881 let to_allocate = min_count.max(u64::from(batch_size));
3882 let id_ts = self.get_catalog_write_ts().await;
3883 let ids = self.catalog().allocate_user_ids(to_allocate, id_ts).await?;
3884 if let (Some((first_id, _)), Some((last_id, _))) = (ids.first(), ids.last()) {
3885 let start = match first_id {
3886 CatalogItemId::User(id) => *id,
3887 other => {
3888 return Err(AdapterError::Internal(format!(
3889 "expected User CatalogItemId, got {other:?}"
3890 )));
3891 }
3892 };
3893 let end = match last_id {
3894 CatalogItemId::User(id) => *id + 1, other => {
3896 return Err(AdapterError::Internal(format!(
3897 "expected User CatalogItemId, got {other:?}"
3898 )));
3899 }
3900 };
3901 self.user_id_pool.refill(start, end);
3902 } else {
3903 return Err(AdapterError::Internal(
3904 "catalog returned no user IDs".into(),
3905 ));
3906 }
3907 Ok(())
3908 }
3909
3910 async fn allocate_user_id(&mut self) -> Result<(CatalogItemId, GlobalId), AdapterError> {
3912 if let Some(id) = self.user_id_pool.allocate() {
3913 return Ok((CatalogItemId::User(id), GlobalId::User(id)));
3914 }
3915 self.refill_user_id_pool(1).await?;
3916 let id = self.user_id_pool.allocate().expect("ID pool just refilled");
3917 Ok((CatalogItemId::User(id), GlobalId::User(id)))
3918 }
3919
3920 async fn allocate_user_ids(
3922 &mut self,
3923 count: u64,
3924 ) -> Result<Vec<(CatalogItemId, GlobalId)>, AdapterError> {
3925 if self.user_id_pool.remaining() < count {
3926 self.refill_user_id_pool(count).await?;
3927 }
3928 let raw_ids = self
3929 .user_id_pool
3930 .allocate_many(count)
3931 .expect("pool has enough IDs after refill");
3932 Ok(raw_ids
3933 .into_iter()
3934 .map(|id| (CatalogItemId::User(id), GlobalId::User(id)))
3935 .collect())
3936 }
3937
3938 fn connection_context(&self) -> &ConnectionContext {
3940 self.controller.connection_context()
3941 }
3942
3943 fn secrets_reader(&self) -> &Arc<dyn SecretsReader> {
3945 &self.connection_context().secrets_reader
3946 }
3947
3948 #[allow(dead_code)]
3953 pub(crate) fn broadcast_notice(&self, notice: AdapterNotice) {
3954 for meta in self.active_conns.values() {
3955 let _ = meta.notice_tx.send(notice.clone());
3956 }
3957 }
3958
3959 pub(crate) fn broadcast_notice_tx(
3962 &self,
3963 ) -> Box<dyn FnOnce(AdapterNotice) -> () + Send + 'static> {
3964 let senders: Vec<_> = self
3965 .active_conns
3966 .values()
3967 .map(|meta| meta.notice_tx.clone())
3968 .collect();
3969 Box::new(move |notice| {
3970 for tx in senders {
3971 let _ = tx.send(notice.clone());
3972 }
3973 })
3974 }
3975
3976 pub(crate) fn active_conns(&self) -> &BTreeMap<ConnectionId, ConnMeta> {
3977 &self.active_conns
3978 }
3979
3980 #[instrument(level = "debug")]
3981 pub(crate) fn retire_execution(
3982 &mut self,
3983 reason: StatementEndedExecutionReason,
3984 ctx_extra: ExecuteContextExtra,
3985 ) {
3986 if let Some(uuid) = ctx_extra.retire() {
3987 self.end_statement_execution(uuid, reason);
3988 }
3989 }
3990
3991 #[instrument(level = "debug")]
3993 pub fn dataflow_builder(&self, instance: ComputeInstanceId) -> DataflowBuilder<'_> {
3994 let compute = self
3995 .instance_snapshot(instance)
3996 .expect("compute instance does not exist");
3997 DataflowBuilder::new(self.catalog().state(), compute)
3998 }
3999
4000 pub fn instance_snapshot(
4002 &self,
4003 id: ComputeInstanceId,
4004 ) -> Result<ComputeInstanceSnapshot, InstanceMissing> {
4005 ComputeInstanceSnapshot::new(&self.controller, id)
4006 }
4007
4008 pub(crate) async fn ship_dataflow(
4015 &mut self,
4016 dataflow: DataflowDescription<Plan>,
4017 instance: ComputeInstanceId,
4018 target_replica: Option<ReplicaId>,
4019 ) {
4020 self.try_ship_dataflow(dataflow, instance, target_replica)
4021 .await
4022 .unwrap_or_terminate("dataflow creation cannot fail");
4023 }
4024
4025 pub(crate) async fn try_ship_dataflow(
4028 &mut self,
4029 dataflow: DataflowDescription<Plan>,
4030 instance: ComputeInstanceId,
4031 target_replica: Option<ReplicaId>,
4032 ) -> Result<(), DataflowCreationError> {
4033 let export_ids = dataflow.exported_index_ids().collect();
4036
4037 self.controller
4038 .compute
4039 .create_dataflow(instance, dataflow, target_replica)?;
4040
4041 self.initialize_compute_read_policies(export_ids, instance, CompactionWindow::Default)
4042 .await;
4043
4044 Ok(())
4045 }
4046
4047 pub(crate) fn allow_writes(&mut self, instance: ComputeInstanceId, id: GlobalId) {
4051 self.controller
4052 .compute
4053 .allow_writes(instance, id)
4054 .unwrap_or_terminate("allow_writes cannot fail");
4055 }
4056
4057 pub(crate) async fn ship_dataflow_and_notice_builtin_table_updates(
4059 &mut self,
4060 dataflow: DataflowDescription<Plan>,
4061 instance: ComputeInstanceId,
4062 notice_builtin_updates_fut: Option<BuiltinTableAppendNotify>,
4063 target_replica: Option<ReplicaId>,
4064 ) {
4065 if let Some(notice_builtin_updates_fut) = notice_builtin_updates_fut {
4066 let ship_dataflow_fut = self.ship_dataflow(dataflow, instance, target_replica);
4067 let ((), ()) =
4068 futures::future::join(notice_builtin_updates_fut, ship_dataflow_fut).await;
4069 } else {
4070 self.ship_dataflow(dataflow, instance, target_replica).await;
4071 }
4072 }
4073
4074 pub fn install_compute_watch_set(
4078 &mut self,
4079 conn_id: ConnectionId,
4080 objects: BTreeSet<GlobalId>,
4081 t: Timestamp,
4082 state: WatchSetResponse,
4083 ) -> Result<(), CollectionLookupError> {
4084 let ws_id = self.controller.install_compute_watch_set(objects, t)?;
4085 self.connection_watch_sets
4086 .entry(conn_id.clone())
4087 .or_default()
4088 .insert(ws_id);
4089 self.installed_watch_sets.insert(ws_id, (conn_id, state));
4090 Ok(())
4091 }
4092
4093 pub fn install_storage_watch_set(
4097 &mut self,
4098 conn_id: ConnectionId,
4099 objects: BTreeSet<GlobalId>,
4100 t: Timestamp,
4101 state: WatchSetResponse,
4102 ) -> Result<(), CollectionMissing> {
4103 let ws_id = self.controller.install_storage_watch_set(objects, t)?;
4104 self.connection_watch_sets
4105 .entry(conn_id.clone())
4106 .or_default()
4107 .insert(ws_id);
4108 self.installed_watch_sets.insert(ws_id, (conn_id, state));
4109 Ok(())
4110 }
4111
4112 pub fn cancel_pending_watchsets(&mut self, conn_id: &ConnectionId) {
4114 if let Some(ws_ids) = self.connection_watch_sets.remove(conn_id) {
4115 for ws_id in ws_ids {
4116 self.installed_watch_sets.remove(&ws_id);
4117 }
4118 }
4119 }
4120
4121 pub async fn dump(&self) -> Result<serde_json::Value, anyhow::Error> {
4125 let global_timelines: BTreeMap<_, _> = self
4131 .global_timelines
4132 .iter()
4133 .map(|(timeline, state)| (timeline.to_string(), format!("{state:?}")))
4134 .collect();
4135 let active_conns: BTreeMap<_, _> = self
4136 .active_conns
4137 .iter()
4138 .map(|(id, meta)| (id.unhandled().to_string(), format!("{meta:?}")))
4139 .collect();
4140 let txn_read_holds: BTreeMap<_, _> = self
4141 .txn_read_holds
4142 .iter()
4143 .map(|(id, capability)| (id.unhandled().to_string(), format!("{capability:?}")))
4144 .collect();
4145 let pending_peeks: BTreeMap<_, _> = self
4146 .pending_peeks
4147 .iter()
4148 .map(|(id, peek)| (id.to_string(), format!("{peek:?}")))
4149 .collect();
4150 let client_pending_peeks: BTreeMap<_, _> = self
4151 .client_pending_peeks
4152 .iter()
4153 .map(|(id, peek)| {
4154 let peek: BTreeMap<_, _> = peek
4155 .iter()
4156 .map(|(uuid, storage_id)| (uuid.to_string(), storage_id))
4157 .collect();
4158 (id.to_string(), peek)
4159 })
4160 .collect();
4161 let pending_linearize_read_txns: BTreeMap<_, _> = self
4162 .pending_linearize_read_txns
4163 .iter()
4164 .map(|(id, read_txn)| (id.unhandled().to_string(), format!("{read_txn:?}")))
4165 .collect();
4166
4167 Ok(serde_json::json!({
4168 "global_timelines": global_timelines,
4169 "active_conns": active_conns,
4170 "txn_read_holds": txn_read_holds,
4171 "pending_peeks": pending_peeks,
4172 "client_pending_peeks": client_pending_peeks,
4173 "pending_linearize_read_txns": pending_linearize_read_txns,
4174 "controller": self.controller.dump().await?,
4175 }))
4176 }
4177
4178 async fn prune_storage_usage_events_on_startup(&self, retention_period: Duration) {
4192 let item_id = self
4193 .catalog()
4194 .resolve_builtin_table(&MZ_STORAGE_USAGE_BY_SHARD);
4195 let global_id = self.catalog.get_entry(&item_id).latest_global_id();
4196 let read_ts = self.get_local_read_ts().await;
4197 let current_contents_fut = self
4198 .controller
4199 .storage_collections
4200 .snapshot(global_id, read_ts);
4201 let internal_cmd_tx = self.internal_cmd_tx.clone();
4202 spawn(|| "storage_usage_prune", async move {
4203 let mut current_contents = current_contents_fut
4204 .await
4205 .unwrap_or_terminate("cannot fail to fetch snapshot");
4206 differential_dataflow::consolidation::consolidate(&mut current_contents);
4207
4208 let cutoff_ts = u128::from(read_ts).saturating_sub(retention_period.as_millis());
4209 let mut expired = Vec::new();
4210 for (row, diff) in current_contents {
4211 assert_eq!(
4212 diff, 1,
4213 "consolidated contents should not contain retractions: ({row:#?}, {diff:#?})"
4214 );
4215 let collection_timestamp = row
4217 .unpack()
4218 .get(3)
4219 .expect("definition of mz_storage_by_shard changed")
4220 .unwrap_timestamptz();
4221 let collection_timestamp = collection_timestamp.timestamp_millis();
4222 let collection_timestamp: u128 = collection_timestamp
4223 .try_into()
4224 .expect("all collections happen after Jan 1 1970");
4225 if collection_timestamp < cutoff_ts {
4226 debug!("pruning storage event {row:?}");
4227 let builtin_update = BuiltinTableUpdate::row(item_id, row, Diff::MINUS_ONE);
4228 expired.push(builtin_update);
4229 }
4230 }
4231
4232 let _ = internal_cmd_tx.send(Message::StorageUsagePrune(expired));
4234 });
4235 }
4236
4237 fn current_credit_consumption_rate(&self) -> Numeric {
4238 self.catalog()
4239 .user_cluster_replicas()
4240 .filter_map(|replica| match &replica.config.location {
4241 ReplicaLocation::Managed(location) => Some(location.size_for_billing()),
4242 ReplicaLocation::Unmanaged(_) => None,
4243 })
4244 .map(|size| {
4245 self.catalog()
4246 .cluster_replica_sizes()
4247 .0
4248 .get(size)
4249 .expect("location size is validated against the cluster replica sizes")
4250 .credits_per_hour
4251 })
4252 .sum()
4253 }
4254}
4255
4256#[cfg(test)]
4257impl Coordinator {
4258 #[allow(dead_code)]
4259 async fn verify_ship_dataflow_no_error(&mut self, dataflow: DataflowDescription<Plan>) {
4260 let compute_instance = ComputeInstanceId::user(1).expect("1 is a valid ID");
4268
4269 let _: () = self.ship_dataflow(dataflow, compute_instance, None).await;
4270 }
4271}
4272
4273struct LastMessage {
4275 kind: &'static str,
4276 stmt: Option<Arc<Statement<Raw>>>,
4277}
4278
4279impl LastMessage {
4280 fn stmt_to_string(&self) -> Cow<'static, str> {
4282 self.stmt
4283 .as_ref()
4284 .map(|stmt| stmt.to_ast_string_redacted().into())
4285 .unwrap_or(Cow::Borrowed("<none>"))
4286 }
4287}
4288
4289impl fmt::Debug for LastMessage {
4290 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4291 f.debug_struct("LastMessage")
4292 .field("kind", &self.kind)
4293 .field("stmt", &self.stmt_to_string())
4294 .finish()
4295 }
4296}
4297
4298impl Drop for LastMessage {
4299 fn drop(&mut self) {
4300 if std::thread::panicking() {
4302 eprintln!("Coordinator panicking, dumping last message\n{self:?}",);
4304 }
4305 }
4306}
4307
4308pub fn serve(
4320 Config {
4321 controller_config,
4322 controller_envd_epoch,
4323 mut storage,
4324 audit_logs_iterator,
4325 timestamp_oracle_url,
4326 unsafe_mode,
4327 all_features,
4328 build_info,
4329 environment_id,
4330 metrics_registry,
4331 now,
4332 secrets_controller,
4333 cloud_resource_controller,
4334 cluster_replica_sizes,
4335 builtin_system_cluster_config,
4336 builtin_catalog_server_cluster_config,
4337 builtin_probe_cluster_config,
4338 builtin_support_cluster_config,
4339 builtin_analytics_cluster_config,
4340 system_parameter_defaults,
4341 availability_zones,
4342 storage_usage_client,
4343 storage_usage_collection_interval,
4344 storage_usage_retention_period,
4345 segment_client,
4346 egress_addresses,
4347 aws_account_id,
4348 aws_privatelink_availability_zones,
4349 connection_context,
4350 connection_limit_callback,
4351 remote_system_parameters,
4352 webhook_concurrency_limit,
4353 http_host_name,
4354 tracing_handle,
4355 read_only_controllers,
4356 caught_up_trigger: clusters_caught_up_trigger,
4357 helm_chart_version,
4358 license_key,
4359 external_login_password_mz_system,
4360 force_builtin_schema_migration,
4361 }: Config,
4362) -> BoxFuture<'static, Result<(Handle, Client), AdapterError>> {
4363 async move {
4364 let coord_start = Instant::now();
4365 info!("startup: coordinator init: beginning");
4366 info!("startup: coordinator init: preamble beginning");
4367
4368 let _builtins = LazyLock::force(&BUILTINS_STATIC);
4372
4373 let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
4374 let (internal_cmd_tx, internal_cmd_rx) = mpsc::unbounded_channel();
4375 let (strict_serializable_reads_tx, strict_serializable_reads_rx) =
4376 mpsc::unbounded_channel();
4377
4378 if !availability_zones.iter().all_unique() {
4380 coord_bail!("availability zones must be unique");
4381 }
4382
4383 let aws_principal_context = match (
4384 aws_account_id,
4385 connection_context.aws_external_id_prefix.clone(),
4386 ) {
4387 (Some(aws_account_id), Some(aws_external_id_prefix)) => Some(AwsPrincipalContext {
4388 aws_account_id,
4389 aws_external_id_prefix,
4390 }),
4391 _ => None,
4392 };
4393
4394 let aws_privatelink_availability_zones = aws_privatelink_availability_zones
4395 .map(|azs_vec| BTreeSet::from_iter(azs_vec.iter().cloned()));
4396
4397 info!(
4398 "startup: coordinator init: preamble complete in {:?}",
4399 coord_start.elapsed()
4400 );
4401 let oracle_init_start = Instant::now();
4402 info!("startup: coordinator init: timestamp oracle init beginning");
4403
4404 let timestamp_oracle_config = timestamp_oracle_url
4405 .map(|url| TimestampOracleConfig::from_url(&url, &metrics_registry))
4406 .transpose()?;
4407 let mut initial_timestamps =
4408 get_initial_oracle_timestamps(×tamp_oracle_config).await?;
4409
4410 initial_timestamps
4414 .entry(Timeline::EpochMilliseconds)
4415 .or_insert_with(mz_repr::Timestamp::minimum);
4416 let mut timestamp_oracles = BTreeMap::new();
4417 for (timeline, initial_timestamp) in initial_timestamps {
4418 Coordinator::ensure_timeline_state_with_initial_time(
4419 &timeline,
4420 initial_timestamp,
4421 now.clone(),
4422 timestamp_oracle_config.clone(),
4423 &mut timestamp_oracles,
4424 read_only_controllers,
4425 )
4426 .await;
4427 }
4428
4429 let catalog_upper = storage.current_upper().await;
4433 let epoch_millis_oracle = ×tamp_oracles
4439 .get(&Timeline::EpochMilliseconds)
4440 .expect("inserted above")
4441 .oracle;
4442
4443 let mut boot_ts = if read_only_controllers {
4444 let read_ts = epoch_millis_oracle.read_ts().await;
4445 std::cmp::max(read_ts, catalog_upper)
4446 } else {
4447 epoch_millis_oracle.apply_write(catalog_upper).await;
4450 epoch_millis_oracle.write_ts().await.timestamp
4451 };
4452
4453 info!(
4454 "startup: coordinator init: timestamp oracle init complete in {:?}",
4455 oracle_init_start.elapsed()
4456 );
4457
4458 let catalog_open_start = Instant::now();
4459 info!("startup: coordinator init: catalog open beginning");
4460 let persist_client = controller_config
4461 .persist_clients
4462 .open(controller_config.persist_location.clone())
4463 .await
4464 .context("opening persist client")?;
4465 let builtin_item_migration_config =
4466 BuiltinItemMigrationConfig {
4467 persist_client: persist_client.clone(),
4468 read_only: read_only_controllers,
4469 force_migration: force_builtin_schema_migration,
4470 }
4471 ;
4472 let OpenCatalogResult {
4473 mut catalog,
4474 migrated_storage_collections_0dt,
4475 new_builtin_collections,
4476 builtin_table_updates,
4477 cached_global_exprs,
4478 uncached_local_exprs,
4479 } = Catalog::open(mz_catalog::config::Config {
4480 storage,
4481 metrics_registry: &metrics_registry,
4482 state: mz_catalog::config::StateConfig {
4483 unsafe_mode,
4484 all_features,
4485 build_info,
4486 environment_id: environment_id.clone(),
4487 read_only: read_only_controllers,
4488 now: now.clone(),
4489 boot_ts: boot_ts.clone(),
4490 skip_migrations: false,
4491 cluster_replica_sizes,
4492 builtin_system_cluster_config,
4493 builtin_catalog_server_cluster_config,
4494 builtin_probe_cluster_config,
4495 builtin_support_cluster_config,
4496 builtin_analytics_cluster_config,
4497 system_parameter_defaults,
4498 remote_system_parameters,
4499 availability_zones,
4500 egress_addresses,
4501 aws_principal_context,
4502 aws_privatelink_availability_zones,
4503 connection_context,
4504 http_host_name,
4505 builtin_item_migration_config,
4506 persist_client: persist_client.clone(),
4507 enable_expression_cache_override: None,
4508 helm_chart_version,
4509 external_login_password_mz_system,
4510 license_key: license_key.clone(),
4511 },
4512 })
4513 .await?;
4514
4515 let catalog_upper = catalog.current_upper().await;
4518 boot_ts = std::cmp::max(boot_ts, catalog_upper);
4519
4520 if !read_only_controllers {
4521 epoch_millis_oracle.apply_write(boot_ts).await;
4522 }
4523
4524 info!(
4525 "startup: coordinator init: catalog open complete in {:?}",
4526 catalog_open_start.elapsed()
4527 );
4528
4529 let coord_thread_start = Instant::now();
4530 info!("startup: coordinator init: coordinator thread start beginning");
4531
4532 let session_id = catalog.config().session_id;
4533 let start_instant = catalog.config().start_instant;
4534
4535 let (bootstrap_tx, bootstrap_rx) = oneshot::channel();
4539 let handle = TokioHandle::current();
4540
4541 let metrics = Metrics::register_into(&metrics_registry);
4542 let metrics_clone = metrics.clone();
4543 let optimizer_metrics = OptimizerMetrics::register_into(
4544 &metrics_registry,
4545 catalog.system_config().optimizer_e2e_latency_warning_threshold(),
4546 );
4547 let segment_client_clone = segment_client.clone();
4548 let coord_now = now.clone();
4549 let advance_timelines_interval =
4550 tokio::time::interval(catalog.system_config().default_timestamp_interval());
4551 let mut check_scheduling_policies_interval = tokio::time::interval(
4552 catalog
4553 .system_config()
4554 .cluster_check_scheduling_policies_interval(),
4555 );
4556 check_scheduling_policies_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
4557
4558 let clusters_caught_up_check_interval = if read_only_controllers {
4559 let dyncfgs = catalog.system_config().dyncfgs();
4560 let interval = WITH_0DT_DEPLOYMENT_CAUGHT_UP_CHECK_INTERVAL.get(dyncfgs);
4561
4562 let mut interval = tokio::time::interval(interval);
4563 interval.set_missed_tick_behavior(MissedTickBehavior::Skip);
4564 interval
4565 } else {
4566 let mut interval = tokio::time::interval(Duration::from_secs(60 * 60));
4574 interval.set_missed_tick_behavior(MissedTickBehavior::Skip);
4575 interval
4576 };
4577
4578 let clusters_caught_up_check =
4579 clusters_caught_up_trigger.map(|trigger| {
4580 let mut exclude_collections: BTreeSet<GlobalId> =
4581 new_builtin_collections.into_iter().collect();
4582
4583 let mut todo: Vec<_> = migrated_storage_collections_0dt
4593 .iter()
4594 .filter(|id| {
4595 catalog.state().get_entry(id).is_materialized_view()
4596 })
4597 .copied()
4598 .collect();
4599 while let Some(item_id) = todo.pop() {
4600 let entry = catalog.state().get_entry(&item_id);
4601 exclude_collections.extend(entry.global_ids());
4602 todo.extend_from_slice(entry.used_by());
4603 }
4604
4605 CaughtUpCheckContext {
4606 trigger,
4607 exclude_collections,
4608 }
4609 });
4610
4611 if let Some(TimestampOracleConfig::Postgres(pg_config)) =
4612 timestamp_oracle_config.as_ref()
4613 {
4614 let pg_timestamp_oracle_params =
4617 flags::timestamp_oracle_config(catalog.system_config());
4618 pg_timestamp_oracle_params.apply(pg_config);
4619 }
4620
4621 let connection_limit_callback: Arc<dyn Fn(&SystemVars) + Send + Sync> =
4624 Arc::new(move |system_vars: &SystemVars| {
4625 let limit: u64 = system_vars.max_connections().cast_into();
4626 let superuser_reserved: u64 =
4627 system_vars.superuser_reserved_connections().cast_into();
4628
4629 let superuser_reserved = if superuser_reserved >= limit {
4634 tracing::warn!(
4635 "superuser_reserved ({superuser_reserved}) is greater than max connections ({limit})!"
4636 );
4637 limit
4638 } else {
4639 superuser_reserved
4640 };
4641
4642 (connection_limit_callback)(limit, superuser_reserved);
4643 });
4644 catalog.system_config_mut().register_callback(
4645 &mz_sql::session::vars::MAX_CONNECTIONS,
4646 Arc::clone(&connection_limit_callback),
4647 );
4648 catalog.system_config_mut().register_callback(
4649 &mz_sql::session::vars::SUPERUSER_RESERVED_CONNECTIONS,
4650 connection_limit_callback,
4651 );
4652
4653 let (group_commit_tx, group_commit_rx) = appends::notifier();
4654
4655 let parent_span = tracing::Span::current();
4656 let thread = thread::Builder::new()
4657 .stack_size(3 * stack::STACK_SIZE)
4661 .name("coordinator".to_string())
4662 .spawn(move || {
4663 let span = info_span!(parent: parent_span, "coord::coordinator").entered();
4664
4665 let controller = handle
4666 .block_on({
4667 catalog.initialize_controller(
4668 controller_config,
4669 controller_envd_epoch,
4670 read_only_controllers,
4671 )
4672 })
4673 .unwrap_or_terminate("failed to initialize storage_controller");
4674 let catalog_upper = handle.block_on(catalog.current_upper());
4677 boot_ts = std::cmp::max(boot_ts, catalog_upper);
4678 if !read_only_controllers {
4679 let epoch_millis_oracle = ×tamp_oracles
4680 .get(&Timeline::EpochMilliseconds)
4681 .expect("inserted above")
4682 .oracle;
4683 handle.block_on(epoch_millis_oracle.apply_write(boot_ts));
4684 }
4685
4686 let catalog = Arc::new(catalog);
4687
4688 let caching_secrets_reader = CachingSecretsReader::new(secrets_controller.reader());
4689 let mut coord = Coordinator {
4690 controller,
4691 catalog,
4692 internal_cmd_tx,
4693 group_commit_tx,
4694 strict_serializable_reads_tx,
4695 global_timelines: timestamp_oracles,
4696 transient_id_gen: Arc::new(TransientIdGen::new()),
4697 active_conns: BTreeMap::new(),
4698 txn_read_holds: Default::default(),
4699 pending_peeks: BTreeMap::new(),
4700 client_pending_peeks: BTreeMap::new(),
4701 pending_linearize_read_txns: BTreeMap::new(),
4702 serialized_ddl: LockedVecDeque::new(),
4703 active_compute_sinks: BTreeMap::new(),
4704 active_webhooks: BTreeMap::new(),
4705 active_copies: BTreeMap::new(),
4706 staged_cancellation: BTreeMap::new(),
4707 introspection_subscribes: BTreeMap::new(),
4708 write_locks: BTreeMap::new(),
4709 deferred_write_ops: BTreeMap::new(),
4710 pending_writes: Vec::new(),
4711 advance_timelines_interval,
4712 secrets_controller,
4713 caching_secrets_reader,
4714 cloud_resource_controller,
4715 storage_usage_client,
4716 storage_usage_collection_interval,
4717 segment_client,
4718 metrics,
4719 optimizer_metrics,
4720 tracing_handle,
4721 statement_logging: StatementLogging::new(coord_now.clone()),
4722 webhook_concurrency_limit,
4723 timestamp_oracle_config,
4724 check_cluster_scheduling_policies_interval: check_scheduling_policies_interval,
4725 cluster_scheduling_decisions: BTreeMap::new(),
4726 caught_up_check_interval: clusters_caught_up_check_interval,
4727 caught_up_check: clusters_caught_up_check,
4728 installed_watch_sets: BTreeMap::new(),
4729 connection_watch_sets: BTreeMap::new(),
4730 cluster_replica_statuses: ClusterReplicaStatuses::new(),
4731 read_only_controllers,
4732 buffered_builtin_table_updates: Some(Vec::new()),
4733 license_key,
4734 user_id_pool: IdPool::empty(),
4735 persist_client,
4736 };
4737 let bootstrap = handle.block_on(async {
4738 coord
4739 .bootstrap(
4740 boot_ts,
4741 migrated_storage_collections_0dt,
4742 builtin_table_updates,
4743 cached_global_exprs,
4744 uncached_local_exprs,
4745 audit_logs_iterator,
4746 )
4747 .await?;
4748 coord
4749 .controller
4750 .remove_orphaned_replicas(
4751 coord.catalog().get_next_user_replica_id().await?,
4752 coord.catalog().get_next_system_replica_id().await?,
4753 )
4754 .await
4755 .map_err(AdapterError::Orchestrator)?;
4756
4757 if let Some(retention_period) = storage_usage_retention_period {
4758 coord
4759 .prune_storage_usage_events_on_startup(retention_period)
4760 .await;
4761 }
4762
4763 Ok(())
4764 });
4765 let ok = bootstrap.is_ok();
4766 drop(span);
4767 bootstrap_tx
4768 .send(bootstrap)
4769 .expect("bootstrap_rx is not dropped until it receives this message");
4770 if ok {
4771 handle.block_on(coord.serve(
4772 internal_cmd_rx,
4773 strict_serializable_reads_rx,
4774 cmd_rx,
4775 group_commit_rx,
4776 ));
4777 }
4778 })
4779 .expect("failed to create coordinator thread");
4780 match bootstrap_rx
4781 .await
4782 .expect("bootstrap_tx always sends a message or panics/halts")
4783 {
4784 Ok(()) => {
4785 info!(
4786 "startup: coordinator init: coordinator thread start complete in {:?}",
4787 coord_thread_start.elapsed()
4788 );
4789 info!(
4790 "startup: coordinator init: complete in {:?}",
4791 coord_start.elapsed()
4792 );
4793 let handle = Handle {
4794 session_id,
4795 start_instant,
4796 _thread: thread.join_on_drop(),
4797 };
4798 let client = Client::new(
4799 build_info,
4800 cmd_tx,
4801 metrics_clone,
4802 now,
4803 environment_id,
4804 segment_client_clone,
4805 );
4806 Ok((handle, client))
4807 }
4808 Err(e) => Err(e),
4809 }
4810 }
4811 .boxed()
4812}
4813
4814async fn get_initial_oracle_timestamps(
4828 timestamp_oracle_config: &Option<TimestampOracleConfig>,
4829) -> Result<BTreeMap<Timeline, Timestamp>, AdapterError> {
4830 let mut initial_timestamps = BTreeMap::new();
4831
4832 if let Some(config) = timestamp_oracle_config {
4833 let oracle_timestamps = config.get_all_timelines().await?;
4834
4835 let debug_msg = || {
4836 oracle_timestamps
4837 .iter()
4838 .map(|(timeline, ts)| format!("{:?} -> {}", timeline, ts))
4839 .join(", ")
4840 };
4841 info!(
4842 "current timestamps from the timestamp oracle: {}",
4843 debug_msg()
4844 );
4845
4846 for (timeline, ts) in oracle_timestamps {
4847 let entry = initial_timestamps
4848 .entry(Timeline::from_str(&timeline).expect("could not parse timeline"));
4849
4850 entry
4851 .and_modify(|current_ts| *current_ts = std::cmp::max(*current_ts, ts))
4852 .or_insert(ts);
4853 }
4854 } else {
4855 info!("no timestamp oracle configured!");
4856 };
4857
4858 let debug_msg = || {
4859 initial_timestamps
4860 .iter()
4861 .map(|(timeline, ts)| format!("{:?}: {}", timeline, ts))
4862 .join(", ")
4863 };
4864 info!("initial oracle timestamps: {}", debug_msg());
4865
4866 Ok(initial_timestamps)
4867}
4868
4869#[instrument]
4870pub async fn load_remote_system_parameters(
4871 storage: &mut Box<dyn OpenableDurableCatalogState>,
4872 system_parameter_sync_config: Option<SystemParameterSyncConfig>,
4873 system_parameter_sync_timeout: Duration,
4874) -> Result<Option<BTreeMap<String, String>>, AdapterError> {
4875 if let Some(system_parameter_sync_config) = system_parameter_sync_config {
4876 tracing::info!("parameter sync on boot: start sync");
4877
4878 let mut params = SynchronizedParameters::new(SystemVars::default());
4918 let frontend_sync = async {
4919 let frontend = SystemParameterFrontend::from(&system_parameter_sync_config).await?;
4920 frontend.pull(&mut params);
4921 let ops = params
4922 .modified()
4923 .into_iter()
4924 .map(|param| {
4925 let name = param.name;
4926 let value = param.value;
4927 tracing::info!(name, value, initial = true, "sync parameter");
4928 (name, value)
4929 })
4930 .collect();
4931 tracing::info!("parameter sync on boot: end sync");
4932 Ok(Some(ops))
4933 };
4934 if !storage.has_system_config_synced_once().await? {
4935 frontend_sync.await
4936 } else {
4937 match mz_ore::future::timeout(system_parameter_sync_timeout, frontend_sync).await {
4938 Ok(ops) => Ok(ops),
4939 Err(TimeoutError::Inner(e)) => Err(e),
4940 Err(TimeoutError::DeadlineElapsed) => {
4941 tracing::info!("parameter sync on boot: sync has timed out");
4942 Ok(None)
4943 }
4944 }
4945 }
4946 } else {
4947 Ok(None)
4948 }
4949}
4950
4951#[derive(Debug)]
4952pub enum WatchSetResponse {
4953 StatementDependenciesReady(StatementLoggingId, StatementLifecycleEvent),
4954 AlterSinkReady(AlterSinkReadyContext),
4955 AlterMaterializedViewReady(AlterMaterializedViewReadyContext),
4956}
4957
4958#[derive(Debug)]
4959pub struct AlterSinkReadyContext {
4960 ctx: Option<ExecuteContext>,
4961 otel_ctx: OpenTelemetryContext,
4962 plan: AlterSinkPlan,
4963 plan_validity: PlanValidity,
4964 read_hold: ReadHolds,
4965}
4966
4967impl AlterSinkReadyContext {
4968 fn ctx(&mut self) -> &mut ExecuteContext {
4969 self.ctx.as_mut().expect("only cleared on drop")
4970 }
4971
4972 fn retire(mut self, result: Result<ExecuteResponse, AdapterError>) {
4973 self.ctx
4974 .take()
4975 .expect("only cleared on drop")
4976 .retire(result);
4977 }
4978}
4979
4980impl Drop for AlterSinkReadyContext {
4981 fn drop(&mut self) {
4982 if let Some(ctx) = self.ctx.take() {
4983 ctx.retire(Err(AdapterError::Canceled));
4984 }
4985 }
4986}
4987
4988#[derive(Debug)]
4989pub struct AlterMaterializedViewReadyContext {
4990 ctx: Option<ExecuteContext>,
4991 otel_ctx: OpenTelemetryContext,
4992 plan: plan::AlterMaterializedViewApplyReplacementPlan,
4993 plan_validity: PlanValidity,
4994}
4995
4996impl AlterMaterializedViewReadyContext {
4997 fn ctx(&mut self) -> &mut ExecuteContext {
4998 self.ctx.as_mut().expect("only cleared on drop")
4999 }
5000
5001 fn retire(mut self, result: Result<ExecuteResponse, AdapterError>) {
5002 self.ctx
5003 .take()
5004 .expect("only cleared on drop")
5005 .retire(result);
5006 }
5007}
5008
5009impl Drop for AlterMaterializedViewReadyContext {
5010 fn drop(&mut self) {
5011 if let Some(ctx) = self.ctx.take() {
5012 ctx.retire(Err(AdapterError::Canceled));
5013 }
5014 }
5015}
5016
5017#[derive(Debug)]
5020struct LockedVecDeque<T> {
5021 items: VecDeque<T>,
5022 lock: Arc<tokio::sync::Mutex<()>>,
5023}
5024
5025impl<T> LockedVecDeque<T> {
5026 pub fn new() -> Self {
5027 Self {
5028 items: VecDeque::new(),
5029 lock: Arc::new(tokio::sync::Mutex::new(())),
5030 }
5031 }
5032
5033 pub fn try_lock_owned(&self) -> Result<OwnedMutexGuard<()>, tokio::sync::TryLockError> {
5034 Arc::clone(&self.lock).try_lock_owned()
5035 }
5036
5037 pub fn is_empty(&self) -> bool {
5038 self.items.is_empty()
5039 }
5040
5041 pub fn push_back(&mut self, value: T) {
5042 self.items.push_back(value)
5043 }
5044
5045 pub fn pop_front(&mut self) -> Option<T> {
5046 self.items.pop_front()
5047 }
5048
5049 pub fn remove(&mut self, index: usize) -> Option<T> {
5050 self.items.remove(index)
5051 }
5052
5053 pub fn iter(&self) -> std::collections::vec_deque::Iter<'_, T> {
5054 self.items.iter()
5055 }
5056}
5057
5058#[derive(Debug)]
5059struct DeferredPlanStatement {
5060 ctx: ExecuteContext,
5061 ps: PlanStatement,
5062}
5063
5064#[derive(Debug)]
5065enum PlanStatement {
5066 Statement {
5067 stmt: Arc<Statement<Raw>>,
5068 params: Params,
5069 },
5070 Plan {
5071 plan: mz_sql::plan::Plan,
5072 resolved_ids: ResolvedIds,
5073 },
5074}
5075
5076#[derive(Debug, Error)]
5077pub enum NetworkPolicyError {
5078 #[error("Access denied for address {0}")]
5079 AddressDenied(IpAddr),
5080 #[error("Access denied missing IP address")]
5081 MissingIp,
5082}
5083
5084pub(crate) fn validate_ip_with_policy_rules(
5085 ip: &IpAddr,
5086 rules: &Vec<NetworkPolicyRule>,
5087) -> Result<(), NetworkPolicyError> {
5088 if rules.iter().any(|r| r.address.0.contains(ip)) {
5091 Ok(())
5092 } else {
5093 Err(NetworkPolicyError::AddressDenied(ip.clone()))
5094 }
5095}
5096
5097pub(crate) fn infer_sql_type_for_catalog(
5098 hir_expr: &HirRelationExpr,
5099 mir_expr: &MirRelationExpr,
5100) -> SqlRelationType {
5101 let mut typ = hir_expr.top_level_typ();
5102 typ.backport_nullability_and_keys(&mir_expr.typ());
5103 typ
5104}
5105
5106#[cfg(test)]
5107mod id_pool_tests {
5108 use super::IdPool;
5109
5110 #[mz_ore::test]
5111 fn test_empty_pool() {
5112 let mut pool = IdPool::empty();
5113 assert_eq!(pool.remaining(), 0);
5114 assert_eq!(pool.allocate(), None);
5115 assert_eq!(pool.allocate_many(1), None);
5116 }
5117
5118 #[mz_ore::test]
5119 fn test_allocate_single() {
5120 let mut pool = IdPool::empty();
5121 pool.refill(10, 13);
5122 assert_eq!(pool.remaining(), 3);
5123 assert_eq!(pool.allocate(), Some(10));
5124 assert_eq!(pool.allocate(), Some(11));
5125 assert_eq!(pool.allocate(), Some(12));
5126 assert_eq!(pool.remaining(), 0);
5127 assert_eq!(pool.allocate(), None);
5128 }
5129
5130 #[mz_ore::test]
5131 fn test_allocate_many() {
5132 let mut pool = IdPool::empty();
5133 pool.refill(100, 105);
5134 assert_eq!(pool.allocate_many(3), Some(vec![100, 101, 102]));
5135 assert_eq!(pool.remaining(), 2);
5136 assert_eq!(pool.allocate_many(3), None);
5138 assert_eq!(pool.allocate_many(2), Some(vec![103, 104]));
5140 assert_eq!(pool.remaining(), 0);
5141 }
5142
5143 #[mz_ore::test]
5144 fn test_allocate_many_zero() {
5145 let mut pool = IdPool::empty();
5146 pool.refill(1, 5);
5147 assert_eq!(pool.allocate_many(0), Some(vec![]));
5148 assert_eq!(pool.remaining(), 4);
5149 }
5150
5151 #[mz_ore::test]
5152 fn test_refill_resets_pool() {
5153 let mut pool = IdPool::empty();
5154 pool.refill(0, 2);
5155 assert_eq!(pool.allocate(), Some(0));
5156 pool.refill(50, 52);
5158 assert_eq!(pool.allocate(), Some(50));
5159 assert_eq!(pool.allocate(), Some(51));
5160 assert_eq!(pool.allocate(), None);
5161 }
5162
5163 #[mz_ore::test]
5164 fn test_mixed_allocate_and_allocate_many() {
5165 let mut pool = IdPool::empty();
5166 pool.refill(0, 10);
5167 assert_eq!(pool.allocate(), Some(0));
5168 assert_eq!(pool.allocate_many(3), Some(vec![1, 2, 3]));
5169 assert_eq!(pool.allocate(), Some(4));
5170 assert_eq!(pool.remaining(), 5);
5171 }
5172
5173 #[mz_ore::test]
5174 #[should_panic(expected = "invalid pool range")]
5175 fn test_refill_invalid_range_panics() {
5176 let mut pool = IdPool::empty();
5177 pool.refill(10, 5);
5178 }
5179}