mz_adapter/coord/
command_handler.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Logic for  processing client [`Command`]s. Each [`Command`] is initiated by a
11//! client via some external Materialize API (ex: HTTP and psql).
12
13use base64::prelude::*;
14use differential_dataflow::lattice::Lattice;
15use mz_adapter_types::dyncfgs::ALLOW_USER_SESSIONS;
16use mz_auth::password::Password;
17use mz_repr::namespaces::MZ_INTERNAL_SCHEMA;
18use mz_sql::session::metadata::SessionMetadata;
19use std::collections::{BTreeMap, BTreeSet};
20use std::net::IpAddr;
21use std::sync::Arc;
22
23use futures::FutureExt;
24use futures::future::LocalBoxFuture;
25use mz_adapter_types::connection::{ConnectionId, ConnectionIdType};
26use mz_catalog::SYSTEM_CONN_ID;
27use mz_catalog::memory::objects::{CatalogItem, DataSourceDesc, Source, Table, TableDataSource};
28use mz_ore::task;
29use mz_ore::tracing::OpenTelemetryContext;
30use mz_ore::{instrument, soft_panic_or_log};
31use mz_repr::role_id::RoleId;
32use mz_repr::{Diff, SqlScalarType, Timestamp};
33use mz_sql::ast::{
34    AlterConnectionAction, AlterConnectionStatement, AlterSinkAction, AlterSourceAction, AstInfo,
35    ConstantVisitor, CopyRelation, CopyStatement, CreateSourceOptionName, Raw, Statement,
36    SubscribeStatement,
37};
38use mz_sql::catalog::RoleAttributesRaw;
39use mz_sql::names::{Aug, PartialItemName, ResolvedIds};
40use mz_sql::plan::{
41    AbortTransactionPlan, CommitTransactionPlan, CreateRolePlan, Params, Plan,
42    StatementClassification, TransactionType,
43};
44use mz_sql::pure::{
45    materialized_view_option_contains_temporal, purify_create_materialized_view_options,
46};
47use mz_sql::rbac;
48use mz_sql::rbac::CREATE_ITEM_USAGE;
49use mz_sql::session::user::User;
50use mz_sql::session::vars::{
51    EndTransactionAction, NETWORK_POLICY, OwnedVarInput, STATEMENT_LOGGING_SAMPLE_RATE, Value, Var,
52};
53use mz_sql_parser::ast::display::AstDisplay;
54use mz_sql_parser::ast::{
55    CreateMaterializedViewStatement, ExplainPlanStatement, Explainee, InsertStatement,
56    WithOptionValue,
57};
58use mz_storage_types::sources::Timeline;
59use opentelemetry::trace::TraceContextExt;
60use tokio::sync::{mpsc, oneshot};
61use tracing::{Instrument, debug_span, info, warn};
62use tracing_opentelemetry::OpenTelemetrySpanExt;
63
64use crate::command::{
65    AuthResponse, CatalogSnapshot, Command, ExecuteResponse, SASLChallengeResponse,
66    SASLVerifyProofResponse, StartupResponse,
67};
68use crate::coord::appends::PendingWriteTxn;
69use crate::coord::{
70    ConnMeta, Coordinator, DeferredPlanStatement, Message, PendingTxn, PlanStatement, PlanValidity,
71    PurifiedStatementReady, validate_ip_with_policy_rules,
72};
73use crate::error::{AdapterError, AuthenticationError};
74use crate::notice::AdapterNotice;
75use crate::session::{Session, TransactionOps, TransactionStatus};
76use crate::util::{ClientTransmitter, ResultExt};
77use crate::webhook::{
78    AppendWebhookResponse, AppendWebhookValidator, WebhookAppender, WebhookAppenderInvalidator,
79};
80use crate::{AppendWebhookError, ExecuteContext, catalog, metrics};
81
82use super::ExecuteContextExtra;
83
84impl Coordinator {
85    /// BOXED FUTURE: As of Nov 2023 the returned Future from this function was 58KB. This would
86    /// get stored on the stack which is bad for runtime performance, and blow up our stack usage.
87    /// Because of that we purposefully move this Future onto the heap (i.e. Box it).
88    pub(crate) fn handle_command(&mut self, mut cmd: Command) -> LocalBoxFuture<'_, ()> {
89        async move {
90            if let Some(session) = cmd.session_mut() {
91                session.apply_external_metadata_updates();
92            }
93            match cmd {
94                Command::Startup {
95                    tx,
96                    user,
97                    conn_id,
98                    secret_key,
99                    uuid,
100                    client_ip,
101                    application_name,
102                    notice_tx,
103                } => {
104                    // Note: We purposefully do not use a ClientTransmitter here because startup
105                    // handles errors and cleanup of sessions itself.
106                    self.handle_startup(
107                        tx,
108                        user,
109                        conn_id,
110                        secret_key,
111                        uuid,
112                        client_ip,
113                        application_name,
114                        notice_tx,
115                    )
116                    .await;
117                }
118
119                Command::AuthenticatePassword {
120                    tx,
121                    role_name,
122                    password,
123                } => {
124                    self.handle_authenticate_password(tx, role_name, password)
125                        .await;
126                }
127
128                Command::AuthenticateGetSASLChallenge {
129                    tx,
130                    role_name,
131                    nonce,
132                } => {
133                    self.handle_generate_sasl_challenge(tx, role_name, nonce)
134                        .await;
135                }
136
137                Command::AuthenticateVerifySASLProof {
138                    tx,
139                    role_name,
140                    proof,
141                    mock_hash,
142                    auth_message,
143                } => {
144                    self.handle_authenticate_verify_sasl_proof(
145                        tx,
146                        role_name,
147                        proof,
148                        auth_message,
149                        mock_hash,
150                    );
151                }
152
153                Command::Execute {
154                    portal_name,
155                    session,
156                    tx,
157                    outer_ctx_extra,
158                } => {
159                    let tx = ClientTransmitter::new(tx, self.internal_cmd_tx.clone());
160
161                    self.handle_execute(portal_name, session, tx, outer_ctx_extra)
162                        .await;
163                }
164
165                Command::RetireExecute { data, reason } => self.retire_execution(reason, data),
166
167                Command::CancelRequest {
168                    conn_id,
169                    secret_key,
170                } => {
171                    self.handle_cancel(conn_id, secret_key).await;
172                }
173
174                Command::PrivilegedCancelRequest { conn_id } => {
175                    self.handle_privileged_cancel(conn_id).await;
176                }
177
178                Command::GetWebhook {
179                    database,
180                    schema,
181                    name,
182                    tx,
183                } => {
184                    self.handle_get_webhook(database, schema, name, tx);
185                }
186
187                Command::GetSystemVars { tx } => {
188                    let _ = tx.send(self.catalog.system_config().clone());
189                }
190
191                Command::SetSystemVars { vars, conn_id, tx } => {
192                    let mut ops = Vec::with_capacity(vars.len());
193                    let conn = &self.active_conns[&conn_id];
194
195                    for (name, value) in vars {
196                        if let Err(e) =
197                            self.catalog().system_config().get(&name).and_then(|var| {
198                                var.visible(conn.user(), self.catalog.system_config())
199                            })
200                        {
201                            let _ = tx.send(Err(e.into()));
202                            return;
203                        }
204
205                        ops.push(catalog::Op::UpdateSystemConfiguration {
206                            name,
207                            value: OwnedVarInput::Flat(value),
208                        });
209                    }
210
211                    let result = self
212                        .catalog_transact_with_context(Some(&conn_id), None, ops)
213                        .await;
214                    let _ = tx.send(result);
215                }
216
217                Command::Terminate { conn_id, tx } => {
218                    self.handle_terminate(conn_id).await;
219                    // Note: We purposefully do not use a ClientTransmitter here because we're already
220                    // terminating the provided session.
221                    if let Some(tx) = tx {
222                        let _ = tx.send(Ok(()));
223                    }
224                }
225
226                Command::Commit {
227                    action,
228                    session,
229                    tx,
230                } => {
231                    let tx = ClientTransmitter::new(tx, self.internal_cmd_tx.clone());
232                    // We reach here not through a statement execution, but from the
233                    // "commit" pgwire command. Thus, we just generate a default statement
234                    // execution context (once statement logging is implemented, this will cause nothing to be logged
235                    // when the execution finishes.)
236                    let ctx = ExecuteContext::from_parts(
237                        tx,
238                        self.internal_cmd_tx.clone(),
239                        session,
240                        Default::default(),
241                    );
242                    let plan = match action {
243                        EndTransactionAction::Commit => {
244                            Plan::CommitTransaction(CommitTransactionPlan {
245                                transaction_type: TransactionType::Implicit,
246                            })
247                        }
248                        EndTransactionAction::Rollback => {
249                            Plan::AbortTransaction(AbortTransactionPlan {
250                                transaction_type: TransactionType::Implicit,
251                            })
252                        }
253                    };
254
255                    let conn_id = ctx.session().conn_id().clone();
256                    self.sequence_plan(ctx, plan, ResolvedIds::empty()).await;
257                    // Part of the Command::Commit contract is that the Coordinator guarantees that
258                    // it has cleared its transaction state for the connection.
259                    self.clear_connection(&conn_id).await;
260                }
261
262                Command::CatalogSnapshot { tx } => {
263                    let _ = tx.send(CatalogSnapshot {
264                        catalog: self.owned_catalog(),
265                    });
266                }
267
268                Command::CheckConsistency { tx } => {
269                    let _ = tx.send(self.check_consistency());
270                }
271
272                Command::Dump { tx } => {
273                    let _ = tx.send(self.dump().await);
274                }
275
276                Command::GetComputeInstanceClient { instance_id, tx } => {
277                    let _ = tx.send(self.controller.compute.instance_client(instance_id));
278                }
279
280                Command::GetOracle { timeline, tx } => {
281                    let oracle = self
282                        .global_timelines
283                        .get(&timeline)
284                        .map(|timeline_state| Arc::clone(&timeline_state.oracle))
285                        .ok_or(AdapterError::ChangedPlan(
286                            "timeline has disappeared during planning".to_string(),
287                        ));
288                    let _ = tx.send(oracle);
289                }
290
291                Command::DetermineRealTimeRecentTimestamp {
292                    source_ids,
293                    real_time_recency_timeout,
294                    tx,
295                } => {
296                    let result = self
297                        .determine_real_time_recent_timestamp(
298                            source_ids.iter().copied(),
299                            real_time_recency_timeout,
300                        )
301                        .await;
302
303                    match result {
304                        Ok(Some(fut)) => {
305                            task::spawn(|| "determine real time recent timestamp", async move {
306                                let result = fut.await.map(Some).map_err(AdapterError::from);
307                                let _ = tx.send(result);
308                            });
309                        }
310                        Ok(None) => {
311                            let _ = tx.send(Ok(None));
312                        }
313                        Err(e) => {
314                            let _ = tx.send(Err(e));
315                        }
316                    }
317                }
318
319                Command::GetTransactionReadHoldsBundle { conn_id, tx } => {
320                    let read_holds = self.txn_read_holds.get(&conn_id).cloned();
321                    let _ = tx.send(read_holds);
322                }
323
324                Command::StoreTransactionReadHolds {
325                    conn_id,
326                    read_holds,
327                    tx,
328                } => {
329                    self.store_transaction_read_holds(conn_id, read_holds);
330                    let _ = tx.send(());
331                }
332
333                Command::ExecuteSlowPathPeek {
334                    dataflow_plan,
335                    determination,
336                    finishing,
337                    compute_instance,
338                    target_replica,
339                    intermediate_result_type,
340                    source_ids,
341                    conn_id,
342                    max_result_size,
343                    max_query_result_size,
344                    tx,
345                } => {
346                    let result = self
347                        .implement_slow_path_peek(
348                            *dataflow_plan,
349                            determination,
350                            finishing,
351                            compute_instance,
352                            target_replica,
353                            intermediate_result_type,
354                            source_ids,
355                            conn_id,
356                            max_result_size,
357                            max_query_result_size,
358                        )
359                        .await;
360
361                    let _ = tx.send(result);
362                }
363
364                Command::ExecuteCopyTo {
365                    df_desc,
366                    compute_instance,
367                    target_replica,
368                    source_ids,
369                    conn_id,
370                    tx,
371                } => {
372                    // implement_copy_to spawns a background task that sends the response
373                    // through tx when the COPY TO completes (or immediately if setup fails).
374                    // We just call it and let it handle all response sending.
375                    self.implement_copy_to(
376                        *df_desc,
377                        compute_instance,
378                        target_replica,
379                        source_ids,
380                        conn_id,
381                        tx,
382                    )
383                    .await;
384                }
385            }
386        }
387        .instrument(debug_span!("handle_command"))
388        .boxed_local()
389    }
390
391    fn handle_authenticate_verify_sasl_proof(
392        &self,
393        tx: oneshot::Sender<Result<SASLVerifyProofResponse, AdapterError>>,
394        role_name: String,
395        proof: String,
396        auth_message: String,
397        mock_hash: String,
398    ) {
399        let role = self.catalog().try_get_role_by_name(role_name.as_str());
400        let role_auth = role.and_then(|r| self.catalog().try_get_role_auth_by_id(&r.id));
401
402        let login = role
403            .as_ref()
404            .map(|r| r.attributes.login.unwrap_or(false))
405            .unwrap_or(false);
406
407        let real_hash = role_auth
408            .as_ref()
409            .and_then(|auth| auth.password_hash.as_ref());
410        let hash_ref = real_hash.map(|s| s.as_str()).unwrap_or(&mock_hash);
411
412        let role_present = role.is_some();
413        let make_auth_err = |role_present: bool, login: bool| {
414            AdapterError::AuthenticationError(if role_present && !login {
415                AuthenticationError::NonLogin
416            } else {
417                AuthenticationError::InvalidCredentials
418            })
419        };
420
421        match mz_auth::hash::sasl_verify(hash_ref, &proof, &auth_message) {
422            Ok(verifier) => {
423                // Success only if role exists, allows login, and a real password hash was used.
424                if login && real_hash.is_some() {
425                    let role = role.expect("login implies role exists");
426                    let _ = tx.send(Ok(SASLVerifyProofResponse {
427                        verifier,
428                        auth_resp: AuthResponse {
429                            role_id: role.id,
430                            superuser: role.attributes.superuser.unwrap_or(false),
431                        },
432                    }));
433                } else {
434                    let _ = tx.send(Err(make_auth_err(role_present, login)));
435                }
436            }
437            Err(_) => {
438                let _ = tx.send(Err(AdapterError::AuthenticationError(
439                    AuthenticationError::InvalidCredentials,
440                )));
441            }
442        }
443    }
444
445    #[mz_ore::instrument(level = "debug")]
446    async fn handle_generate_sasl_challenge(
447        &mut self,
448        tx: oneshot::Sender<Result<SASLChallengeResponse, AdapterError>>,
449        role_name: String,
450        client_nonce: String,
451    ) {
452        let role_auth = self
453            .catalog()
454            .try_get_role_by_name(&role_name)
455            .and_then(|role| self.catalog().try_get_role_auth_by_id(&role.id));
456
457        let nonce = match mz_auth::hash::generate_nonce(&client_nonce) {
458            Ok(n) => n,
459            Err(e) => {
460                let msg = format!(
461                    "failed to generate nonce for client nonce {}: {}",
462                    client_nonce, e
463                );
464                let _ = tx.send(Err(AdapterError::Internal(msg.clone())));
465                soft_panic_or_log!("{msg}");
466                return;
467            }
468        };
469
470        // It's important that the mock_nonce is deterministic per role, otherwise the purpose of
471        // doing mock authentication is defeated. We use a catalog-wide nonce, and combine that
472        // with the role name to get a per-role mock nonce.
473        let send_mock_challenge =
474            |role_name: String,
475             mock_nonce: String,
476             nonce: String,
477             tx: oneshot::Sender<Result<SASLChallengeResponse, AdapterError>>| {
478                let opts = mz_auth::hash::mock_sasl_challenge(
479                    &role_name,
480                    &mock_nonce,
481                    &self.catalog().system_config().scram_iterations(),
482                );
483                let _ = tx.send(Ok(SASLChallengeResponse {
484                    iteration_count: mz_ore::cast::u32_to_usize(opts.iterations.get()),
485                    salt: BASE64_STANDARD.encode(opts.salt),
486                    nonce,
487                }));
488            };
489
490        match role_auth {
491            Some(auth) if auth.password_hash.is_some() => {
492                let hash = auth.password_hash.as_ref().expect("checked above");
493                match mz_auth::hash::scram256_parse_opts(hash) {
494                    Ok(opts) => {
495                        let _ = tx.send(Ok(SASLChallengeResponse {
496                            iteration_count: mz_ore::cast::u32_to_usize(opts.iterations.get()),
497                            salt: BASE64_STANDARD.encode(opts.salt),
498                            nonce,
499                        }));
500                    }
501                    Err(_) => {
502                        send_mock_challenge(
503                            role_name,
504                            self.catalog().state().mock_authentication_nonce(),
505                            nonce,
506                            tx,
507                        );
508                    }
509                }
510            }
511            _ => {
512                send_mock_challenge(
513                    role_name,
514                    self.catalog().state().mock_authentication_nonce(),
515                    nonce,
516                    tx,
517                );
518            }
519        }
520    }
521
522    #[mz_ore::instrument(level = "debug")]
523    async fn handle_authenticate_password(
524        &mut self,
525        tx: oneshot::Sender<Result<AuthResponse, AdapterError>>,
526        role_name: String,
527        password: Option<Password>,
528    ) {
529        let Some(password) = password else {
530            // The user did not provide a password.
531            let _ = tx.send(Err(AdapterError::AuthenticationError(
532                AuthenticationError::PasswordRequired,
533            )));
534            return;
535        };
536
537        if let Some(role) = self.catalog().try_get_role_by_name(role_name.as_str()) {
538            if !role.attributes.login.unwrap_or(false) {
539                // The user is not allowed to login.
540                let _ = tx.send(Err(AdapterError::AuthenticationError(
541                    AuthenticationError::NonLogin,
542                )));
543                return;
544            }
545            if let Some(auth) = self.catalog().try_get_role_auth_by_id(&role.id) {
546                if let Some(hash) = &auth.password_hash {
547                    let _ = match mz_auth::hash::scram256_verify(&password, hash) {
548                        Ok(_) => tx.send(Ok(AuthResponse {
549                            role_id: role.id,
550                            superuser: role.attributes.superuser.unwrap_or(false),
551                        })),
552                        Err(_) => tx.send(Err(AdapterError::AuthenticationError(
553                            AuthenticationError::InvalidCredentials,
554                        ))),
555                    };
556                    return;
557                }
558            }
559            // Authentication failed due to incorrect password or missing password hash.
560            let _ = tx.send(Err(AdapterError::AuthenticationError(
561                AuthenticationError::InvalidCredentials,
562            )));
563        } else {
564            // The user does not exist.
565            let _ = tx.send(Err(AdapterError::AuthenticationError(
566                AuthenticationError::RoleNotFound,
567            )));
568        }
569    }
570
571    #[mz_ore::instrument(level = "debug")]
572    async fn handle_startup(
573        &mut self,
574        tx: oneshot::Sender<Result<StartupResponse, AdapterError>>,
575        user: User,
576        conn_id: ConnectionId,
577        secret_key: u32,
578        uuid: uuid::Uuid,
579        client_ip: Option<IpAddr>,
580        application_name: String,
581        notice_tx: mpsc::UnboundedSender<AdapterNotice>,
582    ) {
583        // Early return if successful, otherwise cleanup any possible state.
584        match self.handle_startup_inner(&user, &conn_id, &client_ip).await {
585            Ok((role_id, session_defaults)) => {
586                let session_type = metrics::session_type_label_value(&user);
587                self.metrics
588                    .active_sessions
589                    .with_label_values(&[session_type])
590                    .inc();
591                let conn = ConnMeta {
592                    secret_key,
593                    notice_tx,
594                    drop_sinks: BTreeSet::new(),
595                    pending_cluster_alters: BTreeSet::new(),
596                    connected_at: self.now(),
597                    user,
598                    application_name,
599                    uuid,
600                    client_ip,
601                    conn_id: conn_id.clone(),
602                    authenticated_role: role_id,
603                    deferred_lock: None,
604                };
605                let update = self.catalog().state().pack_session_update(&conn, Diff::ONE);
606                let update = self.catalog().state().resolve_builtin_table_update(update);
607                self.begin_session_for_statement_logging(&conn);
608                self.active_conns.insert(conn_id.clone(), conn);
609
610                // Note: Do NOT await the notify here, we pass this back to
611                // whatever requested the startup to prevent blocking startup
612                // and the Coordinator on a builtin table update.
613                let updates = vec![update];
614                // It's not a hard error if our list is missing a builtin table, but we want to
615                // make sure these two things stay in-sync.
616                if mz_ore::assert::soft_assertions_enabled() {
617                    let required_tables: BTreeSet<_> = super::appends::REQUIRED_BUILTIN_TABLES
618                        .iter()
619                        .map(|table| self.catalog().resolve_builtin_table(*table))
620                        .collect();
621                    let updates_tracked = updates
622                        .iter()
623                        .all(|update| required_tables.contains(&update.id));
624                    let all_mz_internal = super::appends::REQUIRED_BUILTIN_TABLES
625                        .iter()
626                        .all(|table| table.schema == MZ_INTERNAL_SCHEMA);
627                    mz_ore::soft_assert_or_log!(
628                        updates_tracked,
629                        "not tracking all required builtin table updates!"
630                    );
631                    // TODO(parkmycar): When checking if a query depends on these builtin table
632                    // writes we do not check the transitive dependencies of the query, because
633                    // we don't support creating views on mz_internal objects. If one of these
634                    // tables is promoted out of mz_internal then we'll need to add this check.
635                    mz_ore::soft_assert_or_log!(
636                        all_mz_internal,
637                        "not all builtin tables are in mz_internal! need to check transitive depends",
638                    )
639                }
640                let notify = self.builtin_table_update().background(updates);
641
642                let resp = Ok(StartupResponse {
643                    role_id,
644                    write_notify: notify,
645                    session_defaults,
646                    catalog: self.owned_catalog(),
647                    storage_collections: Arc::clone(&self.controller.storage_collections),
648                    transient_id_gen: Arc::clone(&self.transient_id_gen),
649                    optimizer_metrics: self.optimizer_metrics.clone(),
650                    persist_client: self.persist_client.clone(),
651                });
652                if tx.send(resp).is_err() {
653                    // Failed to send to adapter, but everything is setup so we can terminate
654                    // normally.
655                    self.handle_terminate(conn_id).await;
656                }
657            }
658            Err(e) => {
659                // Error during startup or sending to adapter, cleanup possible state created by
660                // handle_startup_inner. A user may have been created and it can stay; no need to
661                // delete it.
662                self.catalog_mut()
663                    .drop_temporary_schema(&conn_id)
664                    .unwrap_or_terminate("unable to drop temporary schema");
665
666                // Communicate the error back to the client. No need to
667                // handle failures to send the error back; we've already
668                // cleaned up all necessary state.
669                let _ = tx.send(Err(e));
670            }
671        }
672    }
673
674    // Failible startup work that needs to be cleaned up on error.
675    async fn handle_startup_inner(
676        &mut self,
677        user: &User,
678        conn_id: &ConnectionId,
679        client_ip: &Option<IpAddr>,
680    ) -> Result<(RoleId, BTreeMap<String, OwnedVarInput>), AdapterError> {
681        if self.catalog().try_get_role_by_name(&user.name).is_none() {
682            // If the user has made it to this point, that means they have been fully authenticated.
683            // This includes preventing any user, except a pre-defined set of system users, from
684            // connecting to an internal port. Therefore it's ok to always create a new role for the
685            // user.
686            let attributes = RoleAttributesRaw::new();
687            let plan = CreateRolePlan {
688                name: user.name.to_string(),
689                attributes,
690            };
691            self.sequence_create_role_for_startup(plan).await?;
692        }
693        let role_id = self
694            .catalog()
695            .try_get_role_by_name(&user.name)
696            .expect("created above")
697            .id;
698
699        if role_id.is_user() && !ALLOW_USER_SESSIONS.get(self.catalog().system_config().dyncfgs()) {
700            return Err(AdapterError::UserSessionsDisallowed);
701        }
702
703        // Initialize the default session variables for this role.
704        let mut session_defaults = BTreeMap::new();
705        let system_config = self.catalog().state().system_config();
706
707        // Override the session with any system defaults.
708        session_defaults.extend(
709            system_config
710                .iter_session()
711                .map(|v| (v.name().to_string(), OwnedVarInput::Flat(v.value()))),
712        );
713        // Special case.
714        let statement_logging_default = system_config
715            .statement_logging_default_sample_rate()
716            .format();
717        session_defaults.insert(
718            STATEMENT_LOGGING_SAMPLE_RATE.name().to_string(),
719            OwnedVarInput::Flat(statement_logging_default),
720        );
721        // Override system defaults with role defaults.
722        session_defaults.extend(
723            self.catalog()
724                .get_role(&role_id)
725                .vars()
726                .map(|(name, val)| (name.to_string(), val.clone())),
727        );
728
729        // Validate network policies for external users. Internal users can only connect on the
730        // internal interfaces (internal HTTP/ pgwire). It is up to the person deploying the system
731        // to ensure these internal interfaces are well secured.
732        //
733        // HACKY(parkmycar): We don't have a fully formed session yet for this role, but we want
734        // the default network policy for this role, so we read directly out of what the session
735        // will get initialized with.
736        if !user.is_internal() {
737            let network_policy_name = session_defaults
738                .get(NETWORK_POLICY.name())
739                .and_then(|value| match value {
740                    OwnedVarInput::Flat(name) => Some(name.clone()),
741                    OwnedVarInput::SqlSet(names) => {
742                        tracing::error!(?names, "found multiple network policies");
743                        None
744                    }
745                })
746                .unwrap_or_else(|| system_config.default_network_policy_name());
747            let maybe_network_policy = self
748                .catalog()
749                .get_network_policy_by_name(&network_policy_name);
750
751            let Some(network_policy) = maybe_network_policy else {
752                // We should prevent dropping the default network policy, or setting the policy
753                // to something that doesn't exist, so complain loudly if this occurs.
754                tracing::error!(
755                    network_policy_name,
756                    "default network policy does not exist. All user traffic will be blocked"
757                );
758                let reason = match client_ip {
759                    Some(ip) => super::NetworkPolicyError::AddressDenied(ip.clone()),
760                    None => super::NetworkPolicyError::MissingIp,
761                };
762                return Err(AdapterError::NetworkPolicyDenied(reason));
763            };
764
765            if let Some(ip) = client_ip {
766                match validate_ip_with_policy_rules(ip, &network_policy.rules) {
767                    Ok(_) => {}
768                    Err(e) => return Err(AdapterError::NetworkPolicyDenied(e)),
769                }
770            } else {
771                // Only temporary and internal representation of a session
772                // should be missing a client_ip. These sessions should not be
773                // making requests or going through handle_startup.
774                return Err(AdapterError::NetworkPolicyDenied(
775                    super::NetworkPolicyError::MissingIp,
776                ));
777            }
778        }
779
780        self.catalog_mut()
781            .create_temporary_schema(conn_id, role_id)?;
782
783        Ok((role_id, session_defaults))
784    }
785
786    /// Handles an execute command.
787    #[instrument(name = "coord::handle_execute", fields(session = session.uuid().to_string()))]
788    pub(crate) async fn handle_execute(
789        &mut self,
790        portal_name: String,
791        mut session: Session,
792        tx: ClientTransmitter<ExecuteResponse>,
793        // If this command was part of another execute command
794        // (for example, executing a `FETCH` statement causes an execute to be
795        //  issued for the cursor it references),
796        // then `outer_context` should be `Some`.
797        // This instructs the coordinator that the
798        // outer execute should be considered finished once the inner one is.
799        outer_context: Option<ExecuteContextExtra>,
800    ) {
801        if session.vars().emit_trace_id_notice() {
802            let span_context = tracing::Span::current()
803                .context()
804                .span()
805                .span_context()
806                .clone();
807            if span_context.is_valid() {
808                session.add_notice(AdapterNotice::QueryTrace {
809                    trace_id: span_context.trace_id(),
810                });
811            }
812        }
813
814        if let Err(err) = Self::verify_portal(self.catalog(), &mut session, &portal_name) {
815            // If statement logging hasn't started yet, we don't need
816            // to add any "end" event, so just make up a no-op
817            // `ExecuteContextExtra` here, via `Default::default`.
818            //
819            // It's a bit unfortunate because the edge case of failed
820            // portal verifications won't show up in statement
821            // logging, but there seems to be nothing else we can do,
822            // because we need access to the portal to begin logging.
823            //
824            // Another option would be to log a begin and end event, but just fill in NULLs
825            // for everything we get from the portal (prepared statement id, params).
826            let extra = outer_context.unwrap_or_else(Default::default);
827            let ctx = ExecuteContext::from_parts(tx, self.internal_cmd_tx.clone(), session, extra);
828            return ctx.retire(Err(err));
829        }
830
831        // The reference to `portal` can't outlive `session`, which we
832        // use to construct the context, so scope the reference to this block where we
833        // get everything we need from the portal for later.
834        let (stmt, ctx, params) = {
835            let portal = session
836                .get_portal_unverified(&portal_name)
837                .expect("known to exist");
838            let params = portal.parameters.clone();
839            let stmt = portal.stmt.clone();
840            let logging = Arc::clone(&portal.logging);
841            let lifecycle_timestamps = portal.lifecycle_timestamps.clone();
842
843            let extra = if let Some(extra) = outer_context {
844                // We are executing in the context of another SQL statement, so we don't
845                // want to begin statement logging anew. The context of the actual statement
846                // being executed is the one that should be retired once this finishes.
847                extra
848            } else {
849                // This is a new statement, log it and return the context
850                let maybe_uuid = self.begin_statement_execution(
851                    &mut session,
852                    &params,
853                    &logging,
854                    lifecycle_timestamps,
855                );
856
857                ExecuteContextExtra::new(maybe_uuid)
858            };
859            let ctx = ExecuteContext::from_parts(tx, self.internal_cmd_tx.clone(), session, extra);
860            (stmt, ctx, params)
861        };
862
863        let stmt = match stmt {
864            Some(stmt) => stmt,
865            None => return ctx.retire(Ok(ExecuteResponse::EmptyQuery)),
866        };
867
868        let session_type = metrics::session_type_label_value(ctx.session().user());
869        let stmt_type = metrics::statement_type_label_value(&stmt);
870        self.metrics
871            .query_total
872            .with_label_values(&[session_type, stmt_type])
873            .inc();
874        match &*stmt {
875            Statement::Subscribe(SubscribeStatement { output, .. })
876            | Statement::Copy(CopyStatement {
877                relation: CopyRelation::Subscribe(SubscribeStatement { output, .. }),
878                ..
879            }) => {
880                self.metrics
881                    .subscribe_outputs
882                    .with_label_values(&[
883                        session_type,
884                        metrics::subscribe_output_label_value(output),
885                    ])
886                    .inc();
887            }
888            _ => {}
889        }
890
891        self.handle_execute_inner(stmt, params, ctx).await
892    }
893
894    #[instrument(name = "coord::handle_execute_inner", fields(stmt = stmt.to_ast_string_redacted()))]
895    pub(crate) async fn handle_execute_inner(
896        &mut self,
897        stmt: Arc<Statement<Raw>>,
898        params: Params,
899        mut ctx: ExecuteContext,
900    ) {
901        // This comment describes the various ways DDL can execute (the ordered operations: name
902        // resolve, purify, plan, sequence), all of which are managed by this function. DDL has
903        // three notable properties that all partially interact.
904        //
905        // 1. Most DDL statements (and a few others) support single-statement transaction delayed
906        //    execution. This occurs when a session executes `BEGIN`, a single DDL, then `COMMIT`.
907        //    We announce success of the single DDL when it is executed, but do not attempt to plan
908        //    or sequence it until `COMMIT`, which is able to error if needed while sequencing the
909        //    DDL (this behavior is Postgres-compatible). The purpose of this is because some
910        //    drivers or tools wrap all statements in `BEGIN` and `COMMIT` and we would like them to
911        //    work. When the single DDL is announced as successful we also put the session's
912        //    transaction ops into `SingleStatement` which will produce an error if any other
913        //    statement is run in the transaction except `COMMIT`. Additionally, this will cause
914        //    `handle_execute_inner` to stop further processing (no planning, etc.) of the
915        //    statement.
916        // 2. A few other DDL statements (`ALTER .. RENAME/SWAP`) enter the `DDL` ops which allows
917        //    any number of only these DDL statements to be executed in a transaction. At sequencing
918        //    these generate the `Op::TransactionDryRun` catalog op. When applied with
919        //    `catalog_transact`, that op will always produce the `TransactionDryRun` error. The
920        //    `catalog_transact_with_ddl_transaction` function intercepts that error and reports
921        //    success to the user, but nothing is yet committed to the real catalog. At `COMMIT` all
922        //    of the ops but without dry run are applied. The purpose of this is to allow multiple,
923        //    atomic renames in the same transaction.
924        // 3. Some DDLs do off-thread work during purification or sequencing that is expensive or
925        //    makes network calls (interfacing with secrets, optimization of views/indexes, source
926        //    purification). These must guarantee correctness when they return to the main
927        //    coordinator thread because the catalog state could have changed while they were doing
928        //    the off-thread work. Previously we would use `PlanValidity::Checks` to specify a bunch
929        //    of IDs that we needed to exist. We discovered the way we were doing that was not
930        //    always correct. Instead of attempting to get that completely right, we have opted to
931        //    serialize DDL. Getting this right is difficult because catalog changes can affect name
932        //    resolution, planning, sequencing, and optimization. Correctly writing logic that is
933        //    aware of all possible catalog changes that would affect any of those parts is not
934        //    something our current code has been designed to be helpful at. Even if a DDL statement
935        //    is doing off-thread work, another DDL must not yet execute at all. Executing these
936        //    serially will guarantee that no off-thread work has affected the state of the catalog.
937        //    This is done by adding a VecDeque of deferred statements and a lock to the
938        //    Coordinator. When a DDL is run in `handle_execute_inner` (after applying whatever
939        //    transaction ops are needed to the session as described above), it attempts to own the
940        //    lock (a tokio Mutex). If acquired, it stashes the lock in the connection`s `ConnMeta`
941        //    struct in `active_conns` and proceeds. The lock is dropped at transaction end in
942        //    `clear_transaction` and a message sent to the Coordinator to execute the next queued
943        //    DDL. If the lock could not be acquired, the DDL is put into the VecDeque where it
944        //    awaits dequeuing caused by the lock being released.
945
946        // Verify that this statement type can be executed in the current
947        // transaction state.
948        match ctx.session().transaction() {
949            // By this point we should be in a running transaction.
950            TransactionStatus::Default => unreachable!(),
951
952            // Failed transactions have already been checked in pgwire for a safe statement
953            // (COMMIT, ROLLBACK, etc.) and can proceed.
954            TransactionStatus::Failed(_) => {}
955
956            // Started is a deceptive name, and means different things depending on which
957            // protocol was used. It's either exactly one statement (known because this
958            // is the simple protocol and the parser parsed the entire string, and it had
959            // one statement). Or from the extended protocol, it means *some* query is
960            // being executed, but there might be others after it before the Sync (commit)
961            // message. Postgres handles this by teaching Started to eagerly commit certain
962            // statements that can't be run in a transaction block.
963            TransactionStatus::Started(_) => {
964                if let Statement::Declare(_) = &*stmt {
965                    // Declare is an exception. Although it's not against any spec to execute
966                    // it, it will always result in nothing happening, since all portals will be
967                    // immediately closed. Users don't know this detail, so this error helps them
968                    // understand what's going wrong. Postgres does this too.
969                    return ctx.retire(Err(AdapterError::OperationRequiresTransaction(
970                        "DECLARE CURSOR".into(),
971                    )));
972                }
973            }
974
975            // Implicit or explicit transactions.
976            //
977            // Implicit transactions happen when a multi-statement query is executed
978            // (a "simple query"). However if a "BEGIN" appears somewhere in there,
979            // then the existing implicit transaction will be upgraded to an explicit
980            // transaction. Thus, we should not separate what implicit and explicit
981            // transactions can do unless there's some additional checking to make sure
982            // something disallowed in explicit transactions did not previously take place
983            // in the implicit portion.
984            TransactionStatus::InTransactionImplicit(_) | TransactionStatus::InTransaction(_) => {
985                match &*stmt {
986                    // Statements that are safe in a transaction. We still need to verify that we
987                    // don't interleave reads and writes since we can't perform those serializably.
988                    Statement::Close(_)
989                    | Statement::Commit(_)
990                    | Statement::Copy(_)
991                    | Statement::Deallocate(_)
992                    | Statement::Declare(_)
993                    | Statement::Discard(_)
994                    | Statement::Execute(_)
995                    | Statement::ExplainPlan(_)
996                    | Statement::ExplainPushdown(_)
997                    | Statement::ExplainAnalyzeObject(_)
998                    | Statement::ExplainAnalyzeCluster(_)
999                    | Statement::ExplainTimestamp(_)
1000                    | Statement::ExplainSinkSchema(_)
1001                    | Statement::Fetch(_)
1002                    | Statement::Prepare(_)
1003                    | Statement::Rollback(_)
1004                    | Statement::Select(_)
1005                    | Statement::SetTransaction(_)
1006                    | Statement::Show(_)
1007                    | Statement::SetVariable(_)
1008                    | Statement::ResetVariable(_)
1009                    | Statement::StartTransaction(_)
1010                    | Statement::Subscribe(_)
1011                    | Statement::Raise(_) => {
1012                        // Always safe.
1013                    }
1014
1015                    Statement::Insert(InsertStatement {
1016                        source, returning, ..
1017                    }) if returning.is_empty() && ConstantVisitor::insert_source(source) => {
1018                        // Inserting from constant values statements that do not need to execute on
1019                        // any cluster (no RETURNING) is always safe.
1020                    }
1021
1022                    // These statements must be kept in-sync with `must_serialize_ddl()`.
1023                    Statement::AlterObjectRename(_)
1024                    | Statement::AlterObjectSwap(_)
1025                    | Statement::CreateTableFromSource(_)
1026                    | Statement::CreateSource(_) => {
1027                        let state = self.catalog().for_session(ctx.session()).state().clone();
1028                        let revision = self.catalog().transient_revision();
1029
1030                        // Initialize our transaction with a set of empty ops, or return an error
1031                        // if we can't run a DDL transaction
1032                        let txn_status = ctx.session_mut().transaction_mut();
1033                        if let Err(err) = txn_status.add_ops(TransactionOps::DDL {
1034                            ops: vec![],
1035                            state,
1036                            revision,
1037                            side_effects: vec![],
1038                        }) {
1039                            return ctx.retire(Err(err));
1040                        }
1041                    }
1042
1043                    // Statements below must by run singly (in Started).
1044                    Statement::AlterCluster(_)
1045                    | Statement::AlterConnection(_)
1046                    | Statement::AlterDefaultPrivileges(_)
1047                    | Statement::AlterIndex(_)
1048                    | Statement::AlterMaterializedViewApplyReplacement(_)
1049                    | Statement::AlterSetCluster(_)
1050                    | Statement::AlterOwner(_)
1051                    | Statement::AlterRetainHistory(_)
1052                    | Statement::AlterRole(_)
1053                    | Statement::AlterSecret(_)
1054                    | Statement::AlterSink(_)
1055                    | Statement::AlterSource(_)
1056                    | Statement::AlterSystemReset(_)
1057                    | Statement::AlterSystemResetAll(_)
1058                    | Statement::AlterSystemSet(_)
1059                    | Statement::AlterTableAddColumn(_)
1060                    | Statement::AlterNetworkPolicy(_)
1061                    | Statement::CreateCluster(_)
1062                    | Statement::CreateClusterReplica(_)
1063                    | Statement::CreateConnection(_)
1064                    | Statement::CreateDatabase(_)
1065                    | Statement::CreateIndex(_)
1066                    | Statement::CreateMaterializedView(_)
1067                    | Statement::CreateContinualTask(_)
1068                    | Statement::CreateRole(_)
1069                    | Statement::CreateSchema(_)
1070                    | Statement::CreateSecret(_)
1071                    | Statement::CreateSink(_)
1072                    | Statement::CreateSubsource(_)
1073                    | Statement::CreateTable(_)
1074                    | Statement::CreateType(_)
1075                    | Statement::CreateView(_)
1076                    | Statement::CreateWebhookSource(_)
1077                    | Statement::CreateNetworkPolicy(_)
1078                    | Statement::Delete(_)
1079                    | Statement::DropObjects(_)
1080                    | Statement::DropOwned(_)
1081                    | Statement::GrantPrivileges(_)
1082                    | Statement::GrantRole(_)
1083                    | Statement::Insert(_)
1084                    | Statement::ReassignOwned(_)
1085                    | Statement::RevokePrivileges(_)
1086                    | Statement::RevokeRole(_)
1087                    | Statement::Update(_)
1088                    | Statement::ValidateConnection(_)
1089                    | Statement::Comment(_) => {
1090                        let txn_status = ctx.session_mut().transaction_mut();
1091
1092                        // If we're not in an implicit transaction and we could generate exactly one
1093                        // valid ExecuteResponse, we can delay execution until commit.
1094                        if !txn_status.is_implicit() {
1095                            // Statements whose tag is trivial (known only from an unexecuted statement) can
1096                            // be run in a special single-statement explicit mode. In this mode (`BEGIN;
1097                            // <stmt>; COMMIT`), we generate the expected tag from a successful <stmt>, but
1098                            // delay execution until `COMMIT`.
1099                            if let Ok(resp) = ExecuteResponse::try_from(&*stmt) {
1100                                if let Err(err) = txn_status
1101                                    .add_ops(TransactionOps::SingleStatement { stmt, params })
1102                                {
1103                                    ctx.retire(Err(err));
1104                                    return;
1105                                }
1106                                ctx.retire(Ok(resp));
1107                                return;
1108                            }
1109                        }
1110
1111                        return ctx.retire(Err(AdapterError::OperationProhibitsTransaction(
1112                            stmt.to_string(),
1113                        )));
1114                    }
1115                }
1116            }
1117        }
1118
1119        // DDLs must be planned and sequenced serially. We do not rely on PlanValidity checking
1120        // various IDs because we have incorrectly done that in the past. Attempt to acquire the
1121        // ddl lock. The lock is stashed in the ConnMeta which is dropped at transaction end. If
1122        // acquired, proceed with sequencing. If not, enqueue and return. This logic assumes that
1123        // Coordinator::clear_transaction is correctly called when session transactions are ended
1124        // because that function will release the held lock from active_conns.
1125        if Self::must_serialize_ddl(&stmt, &ctx) {
1126            if let Ok(guard) = self.serialized_ddl.try_lock_owned() {
1127                let prev = self
1128                    .active_conns
1129                    .get_mut(ctx.session().conn_id())
1130                    .expect("connection must exist")
1131                    .deferred_lock
1132                    .replace(guard);
1133                assert!(
1134                    prev.is_none(),
1135                    "connections should have at most one lock guard"
1136                );
1137            } else {
1138                if self
1139                    .active_conns
1140                    .get(ctx.session().conn_id())
1141                    .expect("connection must exist")
1142                    .deferred_lock
1143                    .is_some()
1144                {
1145                    // This session *already* has the lock, and incorrectly tried to execute another
1146                    // DDL while still holding the lock, violating the assumption documented above.
1147                    // This is an internal error, probably in some AdapterClient user (pgwire or
1148                    // http). Because the session is now in some unexpected state, return an error
1149                    // which should cause the AdapterClient user to fail the transaction.
1150                    // (Terminating the connection is maybe what we would prefer to do, but is not
1151                    // currently a thing we can do from the coordinator: calling handle_terminate
1152                    // cleans up Coordinator state for the session but doesn't inform the
1153                    // AdapterClient that the session should terminate.)
1154                    soft_panic_or_log!(
1155                        "session {} attempted to get ddl lock while already owning it",
1156                        ctx.session().conn_id()
1157                    );
1158                    ctx.retire(Err(AdapterError::Internal(
1159                        "session attempted to get ddl lock while already owning it".to_string(),
1160                    )));
1161                    return;
1162                }
1163                self.serialized_ddl.push_back(DeferredPlanStatement {
1164                    ctx,
1165                    ps: PlanStatement::Statement { stmt, params },
1166                });
1167                return;
1168            }
1169        }
1170
1171        let catalog = self.catalog();
1172        let catalog = catalog.for_session(ctx.session());
1173        let original_stmt = Arc::clone(&stmt);
1174        // `resolved_ids` should be derivable from `stmt`. If `stmt` is transformed to remove/add
1175        // IDs, then `resolved_ids` should be updated to also remove/add those IDs.
1176        let (stmt, mut resolved_ids) = match mz_sql::names::resolve(&catalog, (*stmt).clone()) {
1177            Ok(resolved) => resolved,
1178            Err(e) => return ctx.retire(Err(e.into())),
1179        };
1180        // N.B. The catalog can change during purification so we must validate that the dependencies still exist after
1181        // purification.  This should be done back on the main thread.
1182        // We do the validation:
1183        //   - In the handler for `Message::PurifiedStatementReady`, before we handle the purified statement.
1184        // If we add special handling for more types of `Statement`s, we'll need to ensure similar verification
1185        // occurs.
1186        let (stmt, resolved_ids) = match stmt {
1187            // Various statements must be purified off the main coordinator thread of control.
1188            stmt if Self::must_spawn_purification(&stmt) => {
1189                let internal_cmd_tx = self.internal_cmd_tx.clone();
1190                let conn_id = ctx.session().conn_id().clone();
1191                let catalog = self.owned_catalog();
1192                let now = self.now();
1193                let otel_ctx = OpenTelemetryContext::obtain();
1194                let current_storage_configuration = self.controller.storage.config().clone();
1195                task::spawn(|| format!("purify:{conn_id}"), async move {
1196                    let transient_revision = catalog.transient_revision();
1197                    let catalog = catalog.for_session(ctx.session());
1198
1199                    // Checks if the session is authorized to purify a statement. Usually
1200                    // authorization is checked after planning, however purification happens before
1201                    // planning, which may require the use of some connections and secrets.
1202                    if let Err(e) = rbac::check_usage(
1203                        &catalog,
1204                        ctx.session(),
1205                        &resolved_ids,
1206                        &CREATE_ITEM_USAGE,
1207                    ) {
1208                        return ctx.retire(Err(e.into()));
1209                    }
1210
1211                    let (result, cluster_id) = mz_sql::pure::purify_statement(
1212                        catalog,
1213                        now,
1214                        stmt,
1215                        &current_storage_configuration,
1216                    )
1217                    .await;
1218                    let result = result.map_err(|e| e.into());
1219                    let dependency_ids = resolved_ids.items().copied().collect();
1220                    let plan_validity = PlanValidity::new(
1221                        transient_revision,
1222                        dependency_ids,
1223                        cluster_id,
1224                        None,
1225                        ctx.session().role_metadata().clone(),
1226                    );
1227                    // It is not an error for purification to complete after `internal_cmd_rx` is dropped.
1228                    let result = internal_cmd_tx.send(Message::PurifiedStatementReady(
1229                        PurifiedStatementReady {
1230                            ctx,
1231                            result,
1232                            params,
1233                            plan_validity,
1234                            original_stmt,
1235                            otel_ctx,
1236                        },
1237                    ));
1238                    if let Err(e) = result {
1239                        tracing::warn!("internal_cmd_rx dropped before we could send: {:?}", e);
1240                    }
1241                });
1242                return;
1243            }
1244
1245            // `CREATE SUBSOURCE` statements are disallowed for users and are only generated
1246            // automatically as part of purification
1247            Statement::CreateSubsource(_) => {
1248                ctx.retire(Err(AdapterError::Unsupported(
1249                    "CREATE SUBSOURCE statements",
1250                )));
1251                return;
1252            }
1253
1254            Statement::CreateMaterializedView(mut cmvs) => {
1255                // `CREATE MATERIALIZED VIEW ... AS OF ...` syntax is disallowed for users and is
1256                // only used for storing initial frontiers in the catalog.
1257                if cmvs.as_of.is_some() {
1258                    return ctx.retire(Err(AdapterError::Unsupported(
1259                        "CREATE MATERIALIZED VIEW ... AS OF statements",
1260                    )));
1261                }
1262
1263                let mz_now = match self
1264                    .resolve_mz_now_for_create_materialized_view(
1265                        &cmvs,
1266                        &resolved_ids,
1267                        ctx.session_mut(),
1268                        true,
1269                    )
1270                    .await
1271                {
1272                    Ok(mz_now) => mz_now,
1273                    Err(e) => return ctx.retire(Err(e)),
1274                };
1275
1276                let catalog = self.catalog().for_session(ctx.session());
1277
1278                purify_create_materialized_view_options(
1279                    catalog,
1280                    mz_now,
1281                    &mut cmvs,
1282                    &mut resolved_ids,
1283                );
1284
1285                let purified_stmt =
1286                    Statement::CreateMaterializedView(CreateMaterializedViewStatement::<Aug> {
1287                        if_exists: cmvs.if_exists,
1288                        name: cmvs.name,
1289                        columns: cmvs.columns,
1290                        replacing: cmvs.replacing,
1291                        in_cluster: cmvs.in_cluster,
1292                        query: cmvs.query,
1293                        with_options: cmvs.with_options,
1294                        as_of: None,
1295                    });
1296
1297                // (Purifying CreateMaterializedView doesn't happen async, so no need to send
1298                // `Message::PurifiedStatementReady` here.)
1299                (purified_stmt, resolved_ids)
1300            }
1301
1302            Statement::ExplainPlan(ExplainPlanStatement {
1303                stage,
1304                with_options,
1305                format,
1306                explainee: Explainee::CreateMaterializedView(box_cmvs, broken),
1307            }) => {
1308                let mut cmvs = *box_cmvs;
1309                let mz_now = match self
1310                    .resolve_mz_now_for_create_materialized_view(
1311                        &cmvs,
1312                        &resolved_ids,
1313                        ctx.session_mut(),
1314                        false,
1315                    )
1316                    .await
1317                {
1318                    Ok(mz_now) => mz_now,
1319                    Err(e) => return ctx.retire(Err(e)),
1320                };
1321
1322                let catalog = self.catalog().for_session(ctx.session());
1323
1324                purify_create_materialized_view_options(
1325                    catalog,
1326                    mz_now,
1327                    &mut cmvs,
1328                    &mut resolved_ids,
1329                );
1330
1331                let purified_stmt = Statement::ExplainPlan(ExplainPlanStatement {
1332                    stage,
1333                    with_options,
1334                    format,
1335                    explainee: Explainee::CreateMaterializedView(Box::new(cmvs), broken),
1336                });
1337
1338                (purified_stmt, resolved_ids)
1339            }
1340
1341            // All other statements are handled immediately.
1342            _ => (stmt, resolved_ids),
1343        };
1344
1345        match self.plan_statement(ctx.session(), stmt, &params, &resolved_ids) {
1346            Ok(plan) => self.sequence_plan(ctx, plan, resolved_ids).await,
1347            Err(e) => ctx.retire(Err(e)),
1348        }
1349    }
1350
1351    /// Whether the statement must be serialized and is DDL.
1352    fn must_serialize_ddl(stmt: &Statement<Raw>, ctx: &ExecuteContext) -> bool {
1353        // Non-DDL is not serialized here.
1354        if !StatementClassification::from(&*stmt).is_ddl() {
1355            return false;
1356        }
1357        // Off-thread, pre-planning purification can perform arbitrarily slow network calls so must
1358        // not be serialized. These all use PlanValidity for their checking, and we must ensure
1359        // those checks are sufficient.
1360        if Self::must_spawn_purification(stmt) {
1361            return false;
1362        }
1363
1364        // Statements that support multiple DDLs in a single transaction aren't serialized here.
1365        // Their operations are serialized when applied to the catalog, guaranteeing that any
1366        // off-thread DDLs concurrent with a multiple DDL transaction will have a serial order.
1367        if ctx.session.transaction().is_ddl() {
1368            return false;
1369        }
1370
1371        // Some DDL is exempt. It is not great that we are matching on Statements here because
1372        // different plans can be produced from the same top-level statement type (i.e., `ALTER
1373        // CONNECTION ROTATE KEYS`). But the whole point of this is to prevent things from being
1374        // planned in the first place, so we accept the abstraction leak.
1375        match stmt {
1376            // Secrets have a small and understood set of dependencies, and their off-thread work
1377            // interacts with k8s.
1378            Statement::AlterSecret(_) => false,
1379            Statement::CreateSecret(_) => false,
1380            Statement::AlterConnection(AlterConnectionStatement { actions, .. })
1381                if actions
1382                    .iter()
1383                    .all(|action| matches!(action, AlterConnectionAction::RotateKeys)) =>
1384            {
1385                false
1386            }
1387
1388            // The off-thread work that altering a cluster may do (waiting for replicas to spin-up),
1389            // does not affect its catalog names or ids and so is safe to not serialize. This could
1390            // change the set of replicas that exist. For queries that name replicas or use the
1391            // current_replica session var, the `replica_id` field of `PlanValidity` serves to
1392            // ensure that those replicas exist during the query finish stage. Additionally, that
1393            // work can take hours (configured by the user), so would also be a bad experience for
1394            // users.
1395            Statement::AlterCluster(_) => false,
1396
1397            // `ALTER SINK SET FROM` waits for the old relation to make enough progress for a clean
1398            // cutover. If the old collection is stalled, it may block forever. Checks in
1399            // sequencing ensure that the operation fails if any one of these happens concurrently:
1400            //   * the sink is dropped
1401            //   * the new source relation is dropped
1402            //   * another `ALTER SINK` for the same sink is applied first
1403            Statement::AlterSink(stmt)
1404                if matches!(stmt.action, AlterSinkAction::ChangeRelation(_)) =>
1405            {
1406                false
1407            }
1408
1409            // Everything else must be serialized.
1410            _ => true,
1411        }
1412    }
1413
1414    /// Whether the statement must be purified off of the Coordinator thread.
1415    fn must_spawn_purification<A: AstInfo>(stmt: &Statement<A>) -> bool {
1416        // `CREATE` and `ALTER` `SOURCE` and `SINK` statements must be purified off the main
1417        // coordinator thread.
1418        if !matches!(
1419            stmt,
1420            Statement::CreateSource(_)
1421                | Statement::AlterSource(_)
1422                | Statement::CreateSink(_)
1423                | Statement::CreateTableFromSource(_)
1424        ) {
1425            return false;
1426        }
1427
1428        // However `ALTER SOURCE RETAIN HISTORY` should be excluded from off-thread purification.
1429        if let Statement::AlterSource(stmt) = stmt {
1430            let names: Vec<CreateSourceOptionName> = match &stmt.action {
1431                AlterSourceAction::SetOptions(options) => {
1432                    options.iter().map(|o| o.name.clone()).collect()
1433                }
1434                AlterSourceAction::ResetOptions(names) => names.clone(),
1435                _ => vec![],
1436            };
1437            if !names.is_empty()
1438                && names
1439                    .iter()
1440                    .all(|n| matches!(n, CreateSourceOptionName::RetainHistory))
1441            {
1442                return false;
1443            }
1444        }
1445
1446        true
1447    }
1448
1449    /// Chooses a timestamp for `mz_now()`, if `mz_now()` occurs in a REFRESH option of the
1450    /// materialized view. Additionally, if `acquire_read_holds` is true and the MV has any REFRESH
1451    /// option, this function grabs read holds at the earliest possible time on input collections
1452    /// that might be involved in the MV.
1453    ///
1454    /// Note that this is NOT what handles `mz_now()` in the query part of the MV. (handles it only
1455    /// in `with_options`).
1456    ///
1457    /// (Note that the chosen timestamp won't be the same timestamp as the system table inserts,
1458    /// unfortunately.)
1459    async fn resolve_mz_now_for_create_materialized_view(
1460        &mut self,
1461        cmvs: &CreateMaterializedViewStatement<Aug>,
1462        resolved_ids: &ResolvedIds,
1463        session: &Session,
1464        acquire_read_holds: bool,
1465    ) -> Result<Option<Timestamp>, AdapterError> {
1466        if cmvs
1467            .with_options
1468            .iter()
1469            .any(|wo| matches!(wo.value, Some(WithOptionValue::Refresh(..))))
1470        {
1471            let catalog = self.catalog().for_session(session);
1472            let cluster = mz_sql::plan::resolve_cluster_for_materialized_view(&catalog, cmvs)?;
1473            let ids = self
1474                .index_oracle(cluster)
1475                .sufficient_collections(resolved_ids.collections().copied());
1476
1477            // If there is any REFRESH option, then acquire read holds. (Strictly speaking, we'd
1478            // need this only if there is a `REFRESH AT`, not for `REFRESH EVERY`, because later
1479            // we want to check the AT times against the read holds that we acquire here. But
1480            // we do it for any REFRESH option, to avoid having so many code paths doing different
1481            // things.)
1482            //
1483            // It's important that we acquire read holds _before_ we determine the least valid read.
1484            // Otherwise, we're not guaranteed that the since frontier doesn't
1485            // advance forward from underneath us.
1486            let read_holds = self.acquire_read_holds(&ids);
1487
1488            // Does `mz_now()` occur?
1489            let mz_now_ts = if cmvs
1490                .with_options
1491                .iter()
1492                .any(materialized_view_option_contains_temporal)
1493            {
1494                let timeline_context = self
1495                    .catalog()
1496                    .validate_timeline_context(resolved_ids.collections().copied())?;
1497
1498                // We default to EpochMilliseconds, similarly to `determine_timestamp_for`,
1499                // but even in the TimestampIndependent case.
1500                // Note that we didn't accurately decide whether we are TimestampDependent
1501                // or TimestampIndependent, because for this we'd need to also check whether
1502                // `query.contains_temporal()`, similarly to how `peek_stage_validate` does.
1503                // However, this doesn't matter here, as we are just going to default to
1504                // EpochMilliseconds in both cases.
1505                let timeline = timeline_context
1506                    .timeline()
1507                    .unwrap_or(&Timeline::EpochMilliseconds);
1508
1509                // Let's start with the timestamp oracle read timestamp.
1510                let mut timestamp = self.get_timestamp_oracle(timeline).read_ts().await;
1511
1512                // If `least_valid_read` is later than the oracle, then advance to that time.
1513                // If we didn't do this, then there would be a danger of missing the first refresh,
1514                // which might cause the materialized view to be unreadable for hours. This might
1515                // be what was happening here:
1516                // https://github.com/MaterializeInc/database-issues/issues/7265#issuecomment-1931856361
1517                //
1518                // In the long term, it would be good to actually block the MV creation statement
1519                // until `least_valid_read`. https://github.com/MaterializeInc/database-issues/issues/7504
1520                // Without blocking, we have the problem that a REFRESH AT CREATION is not linearized
1521                // with the CREATE MATERIALIZED VIEW statement, in the sense that a query from the MV
1522                // after its creation might see input changes that happened after the CRATE MATERIALIZED
1523                // VIEW statement returned.
1524                let oracle_timestamp = timestamp;
1525                let least_valid_read = read_holds.least_valid_read();
1526                timestamp.advance_by(least_valid_read.borrow());
1527
1528                if oracle_timestamp != timestamp {
1529                    warn!(%cmvs.name, %oracle_timestamp, %timestamp, "REFRESH MV's inputs are not readable at the oracle read ts");
1530                }
1531
1532                info!("Resolved `mz_now()` to {timestamp} for REFRESH MV");
1533                Ok(Some(timestamp))
1534            } else {
1535                Ok(None)
1536            };
1537
1538            // NOTE: The Drop impl of ReadHolds makes sure that the hold is
1539            // released when we don't use it.
1540            if acquire_read_holds {
1541                self.store_transaction_read_holds(session.conn_id().clone(), read_holds);
1542            }
1543
1544            mz_now_ts
1545        } else {
1546            Ok(None)
1547        }
1548    }
1549
1550    /// Instruct the dataflow layer to cancel any ongoing, interactive work for
1551    /// the named `conn_id` if the correct secret key is specified.
1552    ///
1553    /// Note: Here we take a [`ConnectionIdType`] as opposed to an owned
1554    /// `ConnectionId` because this method gets called by external clients when
1555    /// they request to cancel a request.
1556    #[mz_ore::instrument(level = "debug")]
1557    async fn handle_cancel(&mut self, conn_id: ConnectionIdType, secret_key: u32) {
1558        if let Some((id_handle, conn_meta)) = self.active_conns.get_key_value(&conn_id) {
1559            // If the secret key specified by the client doesn't match the
1560            // actual secret key for the target connection, we treat this as a
1561            // rogue cancellation request and ignore it.
1562            if conn_meta.secret_key != secret_key {
1563                return;
1564            }
1565
1566            // Now that we've verified the secret key, this is a privileged
1567            // cancellation request. We can upgrade the raw connection ID to a
1568            // proper `IdHandle`.
1569            self.handle_privileged_cancel(id_handle.clone()).await;
1570        }
1571    }
1572
1573    /// Unconditionally instructs the dataflow layer to cancel any ongoing,
1574    /// interactive work for the named `conn_id`.
1575    #[mz_ore::instrument(level = "debug")]
1576    pub(crate) async fn handle_privileged_cancel(&mut self, conn_id: ConnectionId) {
1577        let mut maybe_ctx = None;
1578
1579        // Cancel pending writes. There is at most one pending write per session.
1580        if let Some(idx) = self.pending_writes.iter().position(|pending_write_txn| {
1581            matches!(pending_write_txn, PendingWriteTxn::User {
1582                pending_txn: PendingTxn { ctx, .. },
1583                ..
1584            } if *ctx.session().conn_id() == conn_id)
1585        }) {
1586            if let PendingWriteTxn::User {
1587                pending_txn: PendingTxn { ctx, .. },
1588                ..
1589            } = self.pending_writes.remove(idx)
1590            {
1591                maybe_ctx = Some(ctx);
1592            }
1593        }
1594
1595        // Cancel deferred writes.
1596        if let Some(write_op) = self.deferred_write_ops.remove(&conn_id) {
1597            maybe_ctx = Some(write_op.into_ctx());
1598        }
1599
1600        // Cancel deferred statements.
1601        if let Some(idx) = self
1602            .serialized_ddl
1603            .iter()
1604            .position(|deferred| *deferred.ctx.session().conn_id() == conn_id)
1605        {
1606            let deferred = self
1607                .serialized_ddl
1608                .remove(idx)
1609                .expect("known to exist from call to `position` above");
1610            maybe_ctx = Some(deferred.ctx);
1611        }
1612
1613        // Cancel reads waiting on being linearized. There is at most one linearized read per
1614        // session.
1615        if let Some(pending_read_txn) = self.pending_linearize_read_txns.remove(&conn_id) {
1616            let ctx = pending_read_txn.take_context();
1617            maybe_ctx = Some(ctx);
1618        }
1619
1620        if let Some(ctx) = maybe_ctx {
1621            ctx.retire(Err(AdapterError::Canceled));
1622        }
1623
1624        self.cancel_pending_peeks(&conn_id);
1625        self.cancel_pending_watchsets(&conn_id);
1626        self.cancel_compute_sinks_for_conn(&conn_id).await;
1627        self.cancel_cluster_reconfigurations_for_conn(&conn_id)
1628            .await;
1629        self.cancel_pending_copy(&conn_id);
1630        if let Some((tx, _rx)) = self.staged_cancellation.get_mut(&conn_id) {
1631            let _ = tx.send(true);
1632        }
1633    }
1634
1635    /// Handle termination of a client session.
1636    ///
1637    /// This cleans up any state in the coordinator associated with the session.
1638    #[mz_ore::instrument(level = "debug")]
1639    async fn handle_terminate(&mut self, conn_id: ConnectionId) {
1640        if !self.active_conns.contains_key(&conn_id) {
1641            // If the session doesn't exist in `active_conns`, then this method will panic later on.
1642            // Instead we explicitly panic here while dumping the entire Coord to the logs to help
1643            // debug. This panic is very infrequent so we want as much information as possible.
1644            // See https://github.com/MaterializeInc/database-issues/issues/5627.
1645            panic!("unknown connection: {conn_id:?}\n\n{self:?}")
1646        }
1647
1648        // We do not need to call clear_transaction here because there are no side effects to run
1649        // based on any session transaction state.
1650        self.clear_connection(&conn_id).await;
1651
1652        self.drop_temp_items(&conn_id).await;
1653        self.catalog_mut()
1654            .drop_temporary_schema(&conn_id)
1655            .unwrap_or_terminate("unable to drop temporary schema");
1656        let conn = self.active_conns.remove(&conn_id).expect("conn must exist");
1657        let session_type = metrics::session_type_label_value(conn.user());
1658        self.metrics
1659            .active_sessions
1660            .with_label_values(&[session_type])
1661            .dec();
1662        self.cancel_pending_peeks(conn.conn_id());
1663        self.cancel_pending_watchsets(&conn_id);
1664        self.cancel_pending_copy(&conn_id);
1665        self.end_session_for_statement_logging(conn.uuid());
1666
1667        // Queue the builtin table update, but do not wait for it to complete. We explicitly do
1668        // this to prevent blocking the Coordinator in the case that a lot of connections are
1669        // closed at once, which occurs regularly in some workflows.
1670        let update = self
1671            .catalog()
1672            .state()
1673            .pack_session_update(&conn, Diff::MINUS_ONE);
1674        let update = self.catalog().state().resolve_builtin_table_update(update);
1675
1676        let _builtin_update_notify = self.builtin_table_update().defer(vec![update]);
1677    }
1678
1679    /// Returns the necessary metadata for appending to a webhook source, and a channel to send
1680    /// rows.
1681    #[mz_ore::instrument(level = "debug")]
1682    fn handle_get_webhook(
1683        &mut self,
1684        database: String,
1685        schema: String,
1686        name: String,
1687        tx: oneshot::Sender<Result<AppendWebhookResponse, AppendWebhookError>>,
1688    ) {
1689        /// Attempts to resolve a Webhook source from a provided `database.schema.name` path.
1690        ///
1691        /// Returns a struct that can be used to append data to the underlying storate collection, and the
1692        /// types we should cast the request to.
1693        fn resolve(
1694            coord: &mut Coordinator,
1695            database: String,
1696            schema: String,
1697            name: String,
1698        ) -> Result<AppendWebhookResponse, PartialItemName> {
1699            // Resolve our collection.
1700            let name = PartialItemName {
1701                database: Some(database),
1702                schema: Some(schema),
1703                item: name,
1704            };
1705            let Ok(entry) = coord
1706                .catalog()
1707                .resolve_entry(None, &vec![], &name, &SYSTEM_CONN_ID)
1708            else {
1709                return Err(name);
1710            };
1711
1712            // Webhooks can be created with `CREATE SOURCE` or `CREATE TABLE`.
1713            let (data_source, desc, global_id) = match entry.item() {
1714                CatalogItem::Source(Source {
1715                    data_source: data_source @ DataSourceDesc::Webhook { .. },
1716                    desc,
1717                    global_id,
1718                    ..
1719                }) => (data_source, desc.clone(), *global_id),
1720                CatalogItem::Table(
1721                    table @ Table {
1722                        desc,
1723                        data_source:
1724                            TableDataSource::DataSource {
1725                                desc: data_source @ DataSourceDesc::Webhook { .. },
1726                                ..
1727                            },
1728                        ..
1729                    },
1730                ) => (data_source, desc.latest(), table.global_id_writes()),
1731                _ => return Err(name),
1732            };
1733
1734            let DataSourceDesc::Webhook {
1735                validate_using,
1736                body_format,
1737                headers,
1738                ..
1739            } = data_source
1740            else {
1741                mz_ore::soft_panic_or_log!("programming error! checked above for webhook");
1742                return Err(name);
1743            };
1744            let body_format = body_format.clone();
1745            let header_tys = headers.clone();
1746
1747            // Assert we have one column for the body, and how ever many are required for
1748            // the headers.
1749            let num_columns = headers.num_columns() + 1;
1750            mz_ore::soft_assert_or_log!(
1751                desc.arity() <= num_columns,
1752                "expected at most {} columns, but got {}",
1753                num_columns,
1754                desc.arity()
1755            );
1756
1757            // Double check that the body column of the webhook source matches the type
1758            // we're about to deserialize as.
1759            let body_column = desc
1760                .get_by_name(&"body".into())
1761                .map(|(_idx, ty)| ty.clone())
1762                .ok_or_else(|| name.clone())?;
1763            assert!(!body_column.nullable, "webhook body column is nullable!?");
1764            assert_eq!(body_column.scalar_type, SqlScalarType::from(body_format));
1765
1766            // Create a validator that can be called to validate a webhook request.
1767            let validator = validate_using.as_ref().map(|v| {
1768                let validation = v.clone();
1769                AppendWebhookValidator::new(validation, coord.caching_secrets_reader.clone())
1770            });
1771
1772            // Get a channel so we can queue updates to be written.
1773            let row_tx = coord
1774                .controller
1775                .storage
1776                .monotonic_appender(global_id)
1777                .map_err(|_| name.clone())?;
1778            let stats = coord
1779                .controller
1780                .storage
1781                .webhook_statistics(global_id)
1782                .map_err(|_| name)?;
1783            let invalidator = coord
1784                .active_webhooks
1785                .entry(entry.id())
1786                .or_insert_with(WebhookAppenderInvalidator::new);
1787            let tx = WebhookAppender::new(row_tx, invalidator.guard(), stats);
1788
1789            Ok(AppendWebhookResponse {
1790                tx,
1791                body_format,
1792                header_tys,
1793                validator,
1794            })
1795        }
1796
1797        let response = resolve(self, database, schema, name).map_err(|name| {
1798            AppendWebhookError::UnknownWebhook {
1799                database: name.database.expect("provided"),
1800                schema: name.schema.expect("provided"),
1801                name: name.item,
1802            }
1803        });
1804        let _ = tx.send(response);
1805    }
1806}