Skip to main content

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::AuthenticatorKind;
17use mz_auth::password::Password;
18use mz_repr::namespaces::MZ_INTERNAL_SCHEMA;
19use mz_sql::catalog::AutoProvisionSource;
20use mz_sql::session::metadata::SessionMetadata;
21use std::collections::{BTreeMap, BTreeSet};
22use std::net::IpAddr;
23use std::sync::Arc;
24
25use futures::future::LocalBoxFuture;
26use mz_adapter_types::connection::{ConnectionId, ConnectionIdType};
27use mz_catalog::SYSTEM_CONN_ID;
28use mz_catalog::memory::objects::{
29    CatalogItem, DataSourceDesc, Role, Source, Table, TableDataSource,
30};
31use mz_ore::cast::CastFrom;
32use mz_ore::task;
33use mz_ore::tracing::OpenTelemetryContext;
34use mz_ore::{instrument, soft_panic_or_log};
35use mz_repr::role_id::RoleId;
36use mz_repr::{Diff, SqlScalarType, Timestamp};
37use mz_sql::ast::{
38    AlterConnectionAction, AlterConnectionStatement, AlterSourceAction, AstInfo,
39    CreateSourceOptionName, Raw, Statement, StatementKind,
40};
41use mz_sql::catalog::RoleAttributesRaw;
42use mz_sql::names::{Aug, PartialItemName, ResolvedIds};
43use mz_sql::plan::{
44    AbortTransactionPlan, CommitTransactionPlan, CreateRolePlan, Params, Plan,
45    StatementClassification, TransactionType,
46};
47use mz_sql::pure::{
48    materialized_view_option_contains_temporal, purify_create_materialized_view_options,
49};
50use mz_sql::rbac;
51use mz_sql::session::user::User;
52use mz_sql::session::vars::{
53    EndTransactionAction, NETWORK_POLICY, OwnedVarInput, STATEMENT_LOGGING_SAMPLE_RATE,
54    TRANSACTION_ISOLATION_VAR_NAME, Value, Var, check_transaction_isolation_feature_flag,
55};
56use mz_sql_parser::ast::display::AstDisplay;
57use mz_sql_parser::ast::{
58    CreateMaterializedViewStatement, ExplainPlanStatement, Explainee, WithOptionValue,
59};
60use mz_storage_types::sources::Timeline;
61use opentelemetry::trace::TraceContextExt;
62use tokio::sync::{mpsc, oneshot, watch};
63use tracing::{Instrument, debug_span, info, warn};
64use tracing_opentelemetry::OpenTelemetrySpanExt;
65
66use crate::client::truncate_sql_for_logging;
67use crate::command::{
68    CatalogSnapshot, Command, ExecuteResponse, Response, SASLChallengeResponse,
69    SASLVerifyProofResponse, StartupResponse, SuperuserAttribute,
70};
71use crate::coord::appends::{PendingWriteTxn, UserWriteResponder, WriteResult};
72use crate::coord::{
73    ConnMeta, Coordinator, DeferredDdl, Message, PendingTxn, PlanValidity, PurifiedStatementReady,
74    validate_ip_with_policy_rules,
75};
76use crate::error::{AdapterError, AuthenticationError};
77use crate::notice::AdapterNotice;
78use crate::session::{Session, TransactionOps, TransactionStatus};
79use crate::util::{ClientTransmitter, CompletedClientTransmitter};
80use crate::webhook::{
81    AppendWebhookResponse, AppendWebhookValidator, WebhookAppender, WebhookAppenderInvalidator,
82};
83use crate::{AppendWebhookError, ExecuteContext, catalog, metrics};
84
85use super::{ExecuteContextExtra, ExecuteContextGuard};
86
87/// The login status of a role, used by authentication handlers to check role
88/// existence and login permission before proceeding to credential verification.
89enum RoleLoginStatus {
90    /// The role does not exist in the catalog.
91    NotFound,
92    /// The role exists and has the LOGIN attribute.
93    CanLogin,
94    /// The role exists but does not have the LOGIN attribute.
95    NonLogin,
96}
97
98fn role_login_status(role: Option<&Role>) -> RoleLoginStatus {
99    match role {
100        None => RoleLoginStatus::NotFound,
101        Some(role) => match role.attributes.login {
102            Some(login) if login => RoleLoginStatus::CanLogin,
103            _ => RoleLoginStatus::NonLogin,
104        },
105    }
106}
107
108impl Coordinator {
109    /// Dispatches a command in a size-bounded, heap-allocated future.
110    pub(crate) fn handle_command(&mut self, mut cmd: Command) -> LocalBoxFuture<'_, ()> {
111        let future = async move {
112            if let Some(session) = cmd.session_mut() {
113                session.require_coordinator_completion();
114                session.apply_external_metadata_updates();
115            }
116            match cmd {
117                Command::Startup {
118                    tx,
119                    user,
120                    conn_id,
121                    secret_key,
122                    uuid,
123                    client_ip,
124                    application_name,
125                    notice_tx,
126                } => {
127                    // Note: A ClientTransmitter is not applicable here. Its purpose is to
128                    // rescue the Session from an undeliverable Response, and startup
129                    // responses carry no Session, the Session stays with the client. An
130                    // undeliverable startup response is instead handled by handle_startup's
131                    // failed-send path together with the cleanup guard in Client::startup.
132                    self.handle_startup(
133                        tx,
134                        user,
135                        conn_id,
136                        secret_key,
137                        uuid,
138                        client_ip,
139                        application_name,
140                        notice_tx,
141                    )
142                    .await;
143                }
144
145                Command::AuthenticatePassword {
146                    tx,
147                    role_name,
148                    password,
149                } => {
150                    self.handle_authenticate_password(tx, role_name, password)
151                        .await;
152                }
153
154                Command::AuthenticateGetSASLChallenge {
155                    tx,
156                    role_name,
157                    nonce,
158                } => {
159                    self.handle_generate_sasl_challenge(tx, role_name, nonce)
160                        .await;
161                }
162
163                Command::AuthenticateVerifySASLProof {
164                    tx,
165                    role_name,
166                    proof,
167                    mock_hash,
168                    auth_message,
169                } => {
170                    self.handle_authenticate_verify_sasl_proof(
171                        tx,
172                        role_name,
173                        proof,
174                        auth_message,
175                        mock_hash,
176                    );
177                }
178
179                Command::CheckRoleCanLogin { tx, role_name } => {
180                    self.handle_role_can_login(tx, role_name);
181                }
182
183                Command::Execute {
184                    portal_name,
185                    session,
186                    tx,
187                    outer_ctx_extra,
188                } => {
189                    let tx = ClientTransmitter::new(tx, self.internal_cmd_tx.clone());
190
191                    Box::pin(self.handle_execute(portal_name, session, tx, outer_ctx_extra)).await;
192                }
193
194                Command::StartCopyFromStdin {
195                    target_id,
196                    target_name,
197                    columns,
198                    row_desc,
199                    params,
200                    session,
201                    tx,
202                } => {
203                    let otel_ctx = OpenTelemetryContext::obtain();
204                    let result = self.setup_copy_from_stdin(
205                        &session,
206                        target_id,
207                        target_name,
208                        columns,
209                        row_desc,
210                        params,
211                    );
212                    let _ = tx.send(Response {
213                        result,
214                        session,
215                        otel_ctx,
216                    });
217                }
218
219                Command::RetireExecute { data, reason } => self.retire_execution(reason, data),
220
221                Command::CancelRequest {
222                    conn_id,
223                    secret_key,
224                } => {
225                    self.handle_cancel(conn_id, secret_key).await;
226                }
227
228                Command::PrivilegedCancelRequest { conn_id } => {
229                    self.handle_privileged_cancel(conn_id).await;
230                }
231
232                Command::GetWebhook {
233                    database,
234                    schema,
235                    name,
236                    tx,
237                } => {
238                    self.handle_get_webhook(database, schema, name, tx);
239                }
240
241                Command::GetSystemVars { tx } => {
242                    let _ = tx.send(self.catalog.system_config().clone());
243                }
244
245                Command::SetSystemVars { vars, conn_id, tx } => {
246                    let mut ops = Vec::with_capacity(vars.len());
247                    let conn = &self.active_conns[&conn_id];
248
249                    for (name, value) in vars {
250                        if let Err(e) =
251                            self.catalog().system_config().get(&name).and_then(|var| {
252                                var.visible(conn.user(), self.catalog.system_config())
253                            })
254                        {
255                            let _ = tx.send(Err(e.into()));
256                            return;
257                        }
258
259                        ops.push(catalog::Op::UpdateSystemConfiguration {
260                            name,
261                            value: OwnedVarInput::Flat(value),
262                        });
263                    }
264
265                    let result = self
266                        .catalog_transact_with_context(Some(&conn_id), None, ops)
267                        .await;
268                    let _ = tx.send(result);
269                }
270
271                Command::UpdateScopedSystemParameters {
272                    overrides,
273                    prune_scope,
274                    tx,
275                } => {
276                    // Store the new working copy, persist it durably, and
277                    // reconcile it into the per-scope resolution boundaries.
278                    self.reconcile_scoped_system_parameters(overrides, prune_scope)
279                        .await;
280                    let _ = tx.send(());
281                }
282
283                Command::InstallScopedSystemParameterFrontend { frontend } => {
284                    // Keep the shared frontend so create-cluster / create-replica
285                    // can resolve scoped overrides synchronously at create time.
286                    self.scoped_frontend = Some(frontend);
287                }
288
289                Command::InjectAuditEvents {
290                    events,
291                    conn_id,
292                    tx,
293                } => {
294                    let ops = vec![catalog::Op::InjectAuditEvents { events }];
295                    let result = self
296                        .catalog_transact_with_context(Some(&conn_id), None, ops)
297                        .await;
298                    let _ = tx.send(result);
299                }
300
301                Command::Terminate { conn_id, tx } => {
302                    self.handle_terminate(conn_id).await;
303                    // Note: We purposefully do not use a ClientTransmitter here because we're already
304                    // terminating the provided session.
305                    if let Some(tx) = tx {
306                        let _ = tx.send(Ok(()));
307                    }
308                }
309
310                Command::Commit {
311                    action,
312                    session,
313                    tx,
314                } => {
315                    let tx = ClientTransmitter::new(tx, self.internal_cmd_tx.clone());
316                    // We reach here not through a statement execution, but from the
317                    // "commit" pgwire command. Thus, we just generate a default statement
318                    // execution context (once statement logging is implemented, this will cause nothing to be logged
319                    // when the execution finishes.)
320                    let ctx = ExecuteContext::from_parts(
321                        tx,
322                        self.internal_cmd_tx.clone(),
323                        session,
324                        Default::default(),
325                    );
326                    let plan = match action {
327                        EndTransactionAction::Commit => {
328                            Plan::CommitTransaction(CommitTransactionPlan {
329                                transaction_type: TransactionType::Implicit,
330                            })
331                        }
332                        EndTransactionAction::Rollback => {
333                            Plan::AbortTransaction(AbortTransactionPlan {
334                                transaction_type: TransactionType::Implicit,
335                            })
336                        }
337                    };
338
339                    let conn_id = ctx.session().conn_id().clone();
340                    self.sequence_plan(ctx, plan, ResolvedIds::empty(), ResolvedIds::empty())
341                        .await;
342                    // Part of the Command::Commit contract is that the Coordinator guarantees that
343                    // it has cleared its transaction state for the connection.
344                    let retire_notify = self.clear_connection(&conn_id).await;
345                    // `sequence_plan` has already handled the client response.
346                    // This call only satisfies the internal cleanup contract.
347                    drop(retire_notify);
348                }
349
350                Command::CatalogSnapshot { tx } => {
351                    let _ = tx.send(CatalogSnapshot {
352                        catalog: self.owned_catalog(),
353                    });
354                }
355
356                Command::CheckConsistency { tx } => {
357                    let _ = tx.send(self.check_consistency());
358                }
359
360                Command::Dump { tx } => {
361                    let _ = tx.send(self.dump().await);
362                }
363
364                Command::GetComputeInstanceClient { instance_id, tx } => {
365                    let _ = tx.send(self.controller.compute.instance_client(instance_id));
366                }
367
368                Command::GetOracle { timeline, tx } => {
369                    let oracle = self
370                        .global_timelines
371                        .get(&timeline)
372                        .map(|timeline_state| Arc::clone(&timeline_state.oracle))
373                        .ok_or(AdapterError::ChangedPlan(
374                            "timeline has disappeared during planning".to_string(),
375                        ));
376                    let _ = tx.send(oracle);
377                }
378
379                Command::DetermineRealTimeRecentTimestamp {
380                    source_ids,
381                    real_time_recency_timeout,
382                    tx,
383                } => {
384                    let result = self
385                        .determine_real_time_recent_timestamp(
386                            source_ids.iter().copied(),
387                            real_time_recency_timeout,
388                        )
389                        .await;
390
391                    match result {
392                        Ok(Some(fut)) => {
393                            let catalog = Arc::clone(&self.catalog);
394                            task::spawn(|| "determine real time recent timestamp", async move {
395                                let result =
396                                    Coordinator::await_real_time_recent_timestamp(catalog, fut)
397                                        .await
398                                        .map(Some);
399                                let _ = tx.send(result);
400                            });
401                        }
402                        Ok(None) => {
403                            let _ = tx.send(Ok(None));
404                        }
405                        Err(e) => {
406                            let _ = tx.send(Err(e));
407                        }
408                    }
409                }
410
411                Command::GetTransactionReadHoldsBundle { conn_id, tx } => {
412                    let read_holds = self.txn_read_holds.get(&conn_id).cloned();
413                    let _ = tx.send(read_holds);
414                }
415
416                Command::StoreTransactionReadHolds {
417                    conn_id,
418                    read_holds,
419                    tx,
420                } => {
421                    self.store_transaction_read_holds(conn_id, read_holds);
422                    let _ = tx.send(());
423                }
424
425                Command::ExecuteSlowPathPeek {
426                    peek,
427                    dataflow_plan,
428                    determination,
429                    finishing,
430                    compute_instance,
431                    target_replica,
432                    intermediate_result_type,
433                    conn_id,
434                    max_result_size,
435                    max_query_result_size,
436                    watch_set,
437                    tx,
438                } => {
439                    let result = self.implement_slow_path_peek(
440                        peek,
441                        *dataflow_plan,
442                        determination,
443                        finishing,
444                        compute_instance,
445                        target_replica,
446                        intermediate_result_type,
447                        conn_id,
448                        max_result_size,
449                        max_query_result_size,
450                        watch_set,
451                    );
452                    let _ = tx.send(result);
453                }
454
455                Command::ExecuteSubscribe {
456                    df_desc,
457                    dependency_ids,
458                    cluster_id,
459                    replica_id,
460                    conn_id,
461                    session_uuid,
462                    read_holds,
463                    plan,
464                    statement_logging_id,
465                    tx,
466                } => {
467                    match self
468                        .implement_subscribe(
469                            statement_logging_id,
470                            df_desc,
471                            dependency_ids,
472                            cluster_id,
473                            replica_id,
474                            conn_id,
475                            session_uuid,
476                            read_holds,
477                            plan,
478                        )
479                        .await
480                    {
481                        Ok((resp, write_notify)) => {
482                            // Wait for the `mz_subscriptions` bookkeeping write off the
483                            // coordinator loop before returning the `SUBSCRIBE` response to
484                            // the subscribing session.
485                            task::spawn(|| "execute_subscribe::await_bookkeeping", async move {
486                                write_notify.await;
487                                let _ = tx.send(Ok(resp));
488                            });
489                        }
490                        Err(e) => {
491                            let _ = tx.send(Err(e));
492                        }
493                    }
494                }
495
496                Command::CopyToPreflight {
497                    s3_sink_connection,
498                    sink_id,
499                    tx,
500                } => {
501                    // Spawn a background task to perform the slow S3 preflight operations.
502                    // This avoids blocking the coordinator's main task.
503                    let connection_context = self.connection_context().clone();
504                    let enforce_external_addresses =
505                        mz_storage_types::dyncfgs::ENFORCE_EXTERNAL_ADDRESSES
506                            .get(self.controller.storage.config().config_set());
507                    task::spawn(|| "copy_to_preflight", async move {
508                        let result = mz_storage_types::sinks::s3_oneshot_sink::preflight(
509                            connection_context,
510                            &s3_sink_connection.aws_connection,
511                            &s3_sink_connection.upload_info,
512                            s3_sink_connection.connection_id,
513                            sink_id,
514                            enforce_external_addresses,
515                        )
516                        .await
517                        .map_err(AdapterError::from);
518                        let _ = tx.send(result);
519                    });
520                }
521
522                Command::ExecuteCopyTo {
523                    df_desc,
524                    compute_instance,
525                    target_replica,
526                    source_ids,
527                    conn_id,
528                    watch_set,
529                    tx,
530                } => {
531                    // implement_copy_to spawns a background task that sends the response
532                    // through tx when the COPY TO completes (or immediately if setup fails).
533                    // We just call it and let it handle all response sending.
534                    self.implement_copy_to(
535                        *df_desc,
536                        compute_instance,
537                        target_replica,
538                        source_ids,
539                        conn_id,
540                        watch_set,
541                        tx,
542                    )
543                    .await;
544                }
545
546                Command::ExecuteSideEffectingFunc { plan, conn_id, tx } => {
547                    let result = self.execute_side_effecting_func(plan, conn_id).await;
548                    let _ = tx.send(result);
549                }
550                Command::LookupConnection { connection_id, tx } => {
551                    let conn =
552                        self.active_conns
553                            .get_key_value(&connection_id)
554                            .map(|(id_handle, meta)| {
555                                (id_handle.clone(), *meta.authenticated_role_id())
556                            });
557                    let _ = tx.send(conn);
558                }
559                Command::InstallPeekWatchSets {
560                    conn_id,
561                    watch_set,
562                    tx,
563                } => {
564                    let result = self.install_peek_watch_sets(conn_id, watch_set).map_err(
565                        AdapterError::concurrent_dependency_drop_from_compute_lookup_error,
566                    );
567                    let _ = tx.send(result);
568                }
569                Command::ExplainTimestamp {
570                    conn_id,
571                    session_wall_time,
572                    cluster_id,
573                    id_bundle,
574                    determination,
575                    tx,
576                } => {
577                    let explanation = self.explain_timestamp(
578                        &conn_id,
579                        session_wall_time,
580                        cluster_id,
581                        &id_bundle,
582                        determination,
583                    );
584                    let _ = tx.send(explanation);
585                }
586                Command::RegisterConnectionCancelWatch { conn_id, tx } => {
587                    // Always replace any existing entry. Another code path
588                    // (e.g. `sequence_staged`) may have left a stale watch
589                    // here, possibly already signaled `true` from a prior
590                    // cancel. Reusing it via `or_insert_with` would hand out
591                    // a `Receiver` that already reads `true`, causing the new
592                    // operation to immediately return `Canceled` even though
593                    // it hasn't been cancelled.
594                    let (watch_tx, watch_rx) = watch::channel(false);
595                    self.connection_cancel_watches
596                        .insert(conn_id, (watch_tx, watch_rx.clone()));
597                    let _ = tx.send(watch_rx);
598                }
599                Command::CreateInternalSubscribe {
600                    df_desc,
601                    cluster_id,
602                    replica_id,
603                    depends_on,
604                    as_of,
605                    arity,
606                    sink_id,
607                    owner,
608                    start_time,
609                    read_holds,
610                    tx,
611                } => {
612                    self.handle_create_internal_subscribe(
613                        *df_desc, cluster_id, replica_id, depends_on, as_of, arity, sink_id, owner,
614                        start_time, read_holds, tx,
615                    )
616                    .await;
617                }
618                Command::AttemptWrite {
619                    attempt,
620                    target_id,
621                    target_global_id,
622                    diffs,
623                    tx,
624                } => {
625                    self.handle_attempt_write(attempt, target_id, target_global_id, diffs, tx);
626                }
627                Command::DropInternalSubscribe { sink_id } => {
628                    self.drop_internal_subscribe(sink_id).await;
629                }
630            }
631        }
632        .instrument(debug_span!("handle_command"));
633        crate::coord::box_dispatcher(future)
634    }
635
636    fn handle_role_can_login(
637        &self,
638        tx: oneshot::Sender<Result<(), AdapterError>>,
639        role_name: String,
640    ) {
641        let result =
642            match role_login_status(self.catalog().try_get_role_by_name(role_name.as_str())) {
643                RoleLoginStatus::NotFound => Err(AdapterError::AuthenticationError(
644                    AuthenticationError::RoleNotFound,
645                )),
646                RoleLoginStatus::NonLogin => Err(AdapterError::AuthenticationError(
647                    AuthenticationError::NonLogin,
648                )),
649                RoleLoginStatus::CanLogin => Ok(()),
650            };
651        let _ = tx.send(result);
652    }
653
654    fn handle_authenticate_verify_sasl_proof(
655        &self,
656        tx: oneshot::Sender<Result<SASLVerifyProofResponse, AdapterError>>,
657        role_name: String,
658        proof: String,
659        auth_message: String,
660        mock_hash: String,
661    ) {
662        let role = self.catalog().try_get_role_by_name(role_name.as_str());
663        let login_status = role_login_status(role);
664        let role_auth = role.and_then(|r| self.catalog().try_get_role_auth_by_id(&r.id));
665        let real_hash = role_auth
666            .as_ref()
667            .and_then(|auth| auth.password_hash.as_ref());
668        let hash_ref = real_hash.map(|s| s.as_str()).unwrap_or(&mock_hash);
669
670        match mz_auth::hash::sasl_verify(hash_ref, &proof, &auth_message) {
671            Ok(verifier) => {
672                // Success only if role exists, allows login, and a real password hash was used.
673                if matches!(login_status, RoleLoginStatus::CanLogin) && real_hash.is_some() {
674                    let _ = tx.send(Ok(SASLVerifyProofResponse { verifier }));
675                } else {
676                    let _ = tx.send(Err(AdapterError::AuthenticationError(match login_status {
677                        RoleLoginStatus::NonLogin => AuthenticationError::NonLogin,
678                        RoleLoginStatus::NotFound => AuthenticationError::RoleNotFound,
679                        RoleLoginStatus::CanLogin => AuthenticationError::InvalidCredentials,
680                    })));
681                }
682            }
683            Err(_) => {
684                let _ = tx.send(Err(AdapterError::AuthenticationError(
685                    AuthenticationError::InvalidCredentials,
686                )));
687            }
688        }
689    }
690
691    #[mz_ore::instrument(level = "debug")]
692    async fn handle_generate_sasl_challenge(
693        &self,
694        tx: oneshot::Sender<Result<SASLChallengeResponse, AdapterError>>,
695        role_name: String,
696        client_nonce: String,
697    ) {
698        let role_auth = self
699            .catalog()
700            .try_get_role_by_name(&role_name)
701            .and_then(|role| self.catalog().try_get_role_auth_by_id(&role.id));
702
703        let nonce = match mz_auth::hash::generate_nonce(&client_nonce) {
704            Ok(n) => n,
705            Err(e) => {
706                let msg = format!(
707                    "failed to generate nonce for client nonce {}: {}",
708                    client_nonce, e
709                );
710                let _ = tx.send(Err(AdapterError::Internal(msg.clone())));
711                soft_panic_or_log!("{msg}");
712                return;
713            }
714        };
715
716        // It's important that the mock_nonce is deterministic per role, otherwise the purpose of
717        // doing mock authentication is defeated. We use a catalog-wide nonce, and combine that
718        // with the role name to get a per-role mock nonce.
719        let send_mock_challenge =
720            |role_name: String,
721             mock_nonce: String,
722             nonce: String,
723             tx: oneshot::Sender<Result<SASLChallengeResponse, AdapterError>>| {
724                let opts = mz_auth::hash::mock_sasl_challenge(
725                    &role_name,
726                    &mock_nonce,
727                    &self.catalog().system_config().scram_iterations(),
728                );
729                let _ = tx.send(Ok(SASLChallengeResponse {
730                    iteration_count: mz_ore::cast::u32_to_usize(opts.iterations.get()),
731                    salt: BASE64_STANDARD.encode(opts.salt),
732                    nonce,
733                }));
734            };
735
736        match role_auth {
737            Some(auth) if auth.password_hash.is_some() => {
738                let hash = auth.password_hash.as_ref().expect("checked above");
739                match mz_auth::hash::scram256_parse_opts(hash) {
740                    Ok(opts) => {
741                        let _ = tx.send(Ok(SASLChallengeResponse {
742                            iteration_count: mz_ore::cast::u32_to_usize(opts.iterations.get()),
743                            salt: BASE64_STANDARD.encode(opts.salt),
744                            nonce,
745                        }));
746                    }
747                    Err(_) => {
748                        send_mock_challenge(
749                            role_name,
750                            self.catalog().state().mock_authentication_nonce(),
751                            nonce,
752                            tx,
753                        );
754                    }
755                }
756            }
757            _ => {
758                send_mock_challenge(
759                    role_name,
760                    self.catalog().state().mock_authentication_nonce(),
761                    nonce,
762                    tx,
763                );
764            }
765        }
766    }
767
768    #[mz_ore::instrument(level = "debug")]
769    async fn handle_authenticate_password(
770        &self,
771        tx: oneshot::Sender<Result<(), AdapterError>>,
772        role_name: String,
773        password: Option<Password>,
774    ) {
775        let Some(password) = password else {
776            // The user did not provide a password.
777            let _ = tx.send(Err(AdapterError::AuthenticationError(
778                AuthenticationError::PasswordRequired,
779            )));
780            return;
781        };
782        let role = self.catalog().try_get_role_by_name(role_name.as_str());
783
784        match role_login_status(role) {
785            RoleLoginStatus::NotFound => {
786                let _ = tx.send(Err(AdapterError::AuthenticationError(
787                    AuthenticationError::RoleNotFound,
788                )));
789                return;
790            }
791            RoleLoginStatus::NonLogin => {
792                let _ = tx.send(Err(AdapterError::AuthenticationError(
793                    AuthenticationError::NonLogin,
794                )));
795                return;
796            }
797            RoleLoginStatus::CanLogin => {}
798        }
799
800        let role_auth = role.and_then(|r| self.catalog().try_get_role_auth_by_id(&r.id));
801
802        if let Some(auth) = role_auth {
803            if let Some(hash) = &auth.password_hash {
804                let hash = hash.clone();
805                task::spawn_blocking(
806                    || "auth-check-hash",
807                    move || {
808                        let _ = match mz_auth::hash::scram256_verify(&password, &hash) {
809                            Ok(_) => tx.send(Ok(())),
810                            Err(_) => tx.send(Err(AdapterError::AuthenticationError(
811                                AuthenticationError::InvalidCredentials,
812                            ))),
813                        };
814                    },
815                );
816                return;
817            }
818        }
819        // Authentication failed due to missing password hash.
820        let _ = tx.send(Err(AdapterError::AuthenticationError(
821            AuthenticationError::InvalidCredentials,
822        )));
823    }
824
825    #[mz_ore::instrument(level = "debug")]
826    async fn handle_startup(
827        &mut self,
828        tx: oneshot::Sender<Result<StartupResponse, AdapterError>>,
829        user: User,
830        conn_id: ConnectionId,
831        secret_key: u32,
832        uuid: uuid::Uuid,
833        client_ip: Option<IpAddr>,
834        application_name: String,
835        notice_tx: mpsc::UnboundedSender<AdapterNotice>,
836    ) {
837        // Early return if successful, otherwise cleanup any possible state.
838        match self
839            .handle_startup_inner(&user, &conn_id, &client_ip, &notice_tx)
840            .await
841        {
842            Ok((role_id, superuser_attribute, session_defaults)) => {
843                let (frontend_cancel_tx, frontend_cancel_rx) = watch::channel(());
844                let session_type = metrics::session_type_label_value(&user);
845                self.metrics
846                    .active_sessions
847                    .with_label_values(&[session_type])
848                    .inc();
849                let conn = ConnMeta {
850                    frontend_cancel_tx,
851                    secret_key,
852                    notice_tx,
853                    drop_sinks: BTreeSet::new(),
854                    connected_at: self.now(),
855                    user,
856                    application_name,
857                    uuid,
858                    client_ip,
859                    conn_id: conn_id.clone(),
860                    authenticated_role: role_id,
861                    deferred_lock: None,
862                };
863                let update = self.catalog().state().pack_session_update(&conn, Diff::ONE);
864                let update = self.catalog().state().resolve_builtin_table_update(update);
865                self.begin_session_for_statement_logging(&conn);
866                self.active_conns.insert(conn_id.clone(), conn);
867
868                // Note: Do NOT await the notify here, we pass this back to
869                // whatever requested the startup to prevent blocking startup
870                // and the Coordinator on a builtin table update.
871                let updates = vec![update];
872                // It's not a hard error if our list is missing a builtin table, but we want to
873                // make sure these two things stay in-sync.
874                if mz_ore::assert::soft_assertions_enabled() {
875                    let required_tables: BTreeSet<_> = super::appends::REQUIRED_BUILTIN_TABLES
876                        .iter()
877                        .map(|table| self.catalog().resolve_builtin_table(*table))
878                        .collect();
879                    let updates_tracked = updates
880                        .iter()
881                        .all(|update| required_tables.contains(&update.id));
882                    let all_mz_internal = super::appends::REQUIRED_BUILTIN_TABLES
883                        .iter()
884                        .all(|table| table.schema == MZ_INTERNAL_SCHEMA);
885                    mz_ore::soft_assert_or_log!(
886                        updates_tracked,
887                        "not tracking all required builtin table updates!"
888                    );
889                    // TODO(parkmycar): When checking if a query depends on these builtin table
890                    // writes we do not check the transitive dependencies of the query, because
891                    // we don't support creating views on mz_internal objects. If one of these
892                    // tables is promoted out of mz_internal then we'll need to add this check.
893                    mz_ore::soft_assert_or_log!(
894                        all_mz_internal,
895                        "not all builtin tables are in mz_internal! need to check transitive depends",
896                    )
897                }
898                let notify = self.builtin_table_update().background(updates);
899
900                let catalog = self.owned_catalog();
901                let build_info_human_version =
902                    catalog.state().config().build_info.human_version(None);
903
904                let statement_logging_frontend = self
905                    .statement_logging
906                    .create_frontend(build_info_human_version);
907
908                let resp = Ok(StartupResponse {
909                    connection_peeks: self.peek_registry.connection(conn_id.clone()),
910                    frontend_cancel_rx,
911                    role_id,
912                    write_notify: notify,
913                    session_defaults,
914                    catalog,
915                    storage_collections: Arc::clone(&self.controller.storage_collections),
916                    transient_id_gen: Arc::clone(&self.transient_id_gen),
917                    optimizer_metrics: self.optimizer_metrics.clone(),
918                    persist_client: self.persist_client.clone(),
919                    statement_logging_frontend,
920                    superuser_attribute,
921                    occ_write_semaphore: Arc::clone(&self.occ_write_semaphore),
922                    group_commit_notifier: self.group_commit_tx.clone(),
923                    read_only: self.controller.read_only(),
924                });
925                if tx.send(resp).is_err() {
926                    // Failed to send to adapter, but everything is setup so we can terminate
927                    // normally.
928                    self.handle_terminate(conn_id).await;
929                }
930            }
931            Err(e) => {
932                // Nothing to clean up and `handle_terminate` must not be called. Per the
933                // `handle_startup_inner` invariant, no per-connection state exists and the
934                // connection was never registered in `active_conns`. An auto-provisioned role
935                // stays, it is role-scoped rather than tied to this connection. Temporary
936                // schemas are created lazily, so none exists yet. For the same reason, a
937                // failure to send the error back to the client needs no handling.
938                let _ = tx.send(Err(e));
939            }
940        }
941    }
942
943    /// Fallible startup work.
944    ///
945    /// Invariant: when this returns an error, no per-connection coordinator
946    /// state exists. Per-connection state is registered only in
947    /// `handle_startup`'s Ok arm, after this function has succeeded. The
948    /// cleanup guard in `Client::startup` relies on this invariant by not
949    /// sending `Terminate` when startup fails, and `handle_terminate` panics
950    /// on connections it does not know about.
951    ///
952    /// Durable catalog changes made before an error (an auto-provisioned
953    /// role, synced role memberships) are role-scoped rather than
954    /// connection-scoped and are intentionally kept.
955    async fn handle_startup_inner(
956        &mut self,
957        user: &User,
958        _conn_id: &ConnectionId,
959        client_ip: &Option<IpAddr>,
960        notice_tx: &mpsc::UnboundedSender<AdapterNotice>,
961    ) -> Result<(RoleId, SuperuserAttribute, BTreeMap<String, OwnedVarInput>), AdapterError> {
962        if self.catalog().try_get_role_by_name(&user.name).is_none() {
963            // If the user has made it to this point, that means they have been fully authenticated.
964            // This includes preventing any user, except a pre-defined set of system users, from
965            // connecting to an internal port. Therefore it's ok to always create a new role for the
966            // user.
967            let mut attributes = RoleAttributesRaw::new();
968            // When auto-provisioning, we store the authenticator that was used to provision the role.
969            attributes.auto_provision_source = match user.authenticator_kind {
970                Some(AuthenticatorKind::Oidc) => Some(AutoProvisionSource::Oidc),
971                Some(AuthenticatorKind::Frontegg) => Some(AutoProvisionSource::Frontegg),
972                Some(AuthenticatorKind::None) => Some(AutoProvisionSource::None),
973                _ => {
974                    warn!(
975                        "auto-provisioning role with unexpected authenticator kind: {:?}",
976                        user.authenticator_kind
977                    );
978                    None
979                }
980            };
981
982            // Auto-provision roles with the LOGIN attribute to distinguish
983            // them as users.
984            attributes.login = Some(true);
985
986            let plan = CreateRolePlan {
987                name: user.name.to_string(),
988                attributes,
989            };
990            self.sequence_create_role_for_startup(plan).await?;
991        }
992        let role = self
993            .catalog()
994            .try_get_role_by_name(&user.name)
995            .expect("created above");
996        let role_id = role.id;
997        let superuser_attribute = role.attributes.superuser;
998
999        // JWT group-to-role sync: reconcile role memberships with JWT group claims.
1000        // Missing groups claim (None) → skip sync; empty (Some([])) → revoke all.
1001        self.maybe_sync_jwt_groups(role_id, user.groups.as_deref(), notice_tx)
1002            .await?;
1003
1004        if role_id.is_user() && !ALLOW_USER_SESSIONS.get(self.catalog().system_config().dyncfgs()) {
1005            return Err(AdapterError::UserSessionsDisallowed);
1006        }
1007
1008        // Initialize the default session variables for this role.
1009        let mut session_defaults = BTreeMap::new();
1010        let system_config = self.catalog().state().system_config();
1011
1012        // Override the session with any system defaults.
1013        session_defaults.extend(
1014            system_config
1015                .iter_session()
1016                .map(|v| (v.name().to_string(), OwnedVarInput::Flat(v.value()))),
1017        );
1018        // Special case.
1019        let statement_logging_default = system_config
1020            .statement_logging_default_sample_rate()
1021            .format();
1022        session_defaults.insert(
1023            STATEMENT_LOGGING_SAMPLE_RATE.name().to_string(),
1024            OwnedVarInput::Flat(statement_logging_default),
1025        );
1026        // Override system defaults with role defaults.
1027        session_defaults.extend(
1028            self.catalog()
1029                .get_role(&role_id)
1030                .vars()
1031                .map(|(name, val)| (name.to_string(), val.clone())),
1032        );
1033
1034        // If the resolved `transaction_isolation` default names a feature-flagged
1035        // isolation level whose flag is now disabled (e.g. a role default set
1036        // while `strong session serializable` was enabled, then the flag turned
1037        // off), drop it so the session falls back to the built-in default rather
1038        // than silently using a gated level.
1039        if let Some(value) = session_defaults.get(TRANSACTION_ISOLATION_VAR_NAME) {
1040            if check_transaction_isolation_feature_flag(
1041                TRANSACTION_ISOLATION_VAR_NAME,
1042                value.borrow(),
1043                system_config,
1044            )
1045            .is_err()
1046            {
1047                session_defaults.remove(TRANSACTION_ISOLATION_VAR_NAME);
1048            }
1049        }
1050
1051        // Validate network policies for external users. Internal users can only connect on the
1052        // internal interfaces (internal HTTP/ pgwire). It is up to the person deploying the system
1053        // to ensure these internal interfaces are well secured.
1054        //
1055        // HACKY(parkmycar): We don't have a fully formed session yet for this role, but we want
1056        // the default network policy for this role, so we read directly out of what the session
1057        // will get initialized with.
1058        if !user.is_internal() {
1059            let network_policy_name = session_defaults
1060                .get(NETWORK_POLICY.name())
1061                .and_then(|value| match value {
1062                    OwnedVarInput::Flat(name) => Some(name.clone()),
1063                    OwnedVarInput::SqlSet(names) => {
1064                        tracing::error!(?names, "found multiple network policies");
1065                        None
1066                    }
1067                })
1068                .unwrap_or_else(|| system_config.default_network_policy_name());
1069            let maybe_network_policy = self
1070                .catalog()
1071                .get_network_policy_by_name(&network_policy_name);
1072
1073            let Some(network_policy) = maybe_network_policy else {
1074                // We should prevent dropping the default network policy, or setting the policy
1075                // to something that doesn't exist, so complain loudly if this occurs.
1076                tracing::error!(
1077                    network_policy_name,
1078                    "default network policy does not exist. All user traffic will be blocked"
1079                );
1080                let reason = match client_ip {
1081                    Some(ip) => super::NetworkPolicyError::AddressDenied(ip.clone()),
1082                    None => super::NetworkPolicyError::MissingIp,
1083                };
1084                return Err(AdapterError::NetworkPolicyDenied(reason));
1085            };
1086
1087            if let Some(ip) = client_ip {
1088                match validate_ip_with_policy_rules(ip, &network_policy.rules) {
1089                    Ok(_) => {}
1090                    Err(e) => return Err(AdapterError::NetworkPolicyDenied(e)),
1091                }
1092            } else {
1093                // Only temporary and internal representation of a session
1094                // should be missing a client_ip. These sessions should not be
1095                // making requests or going through handle_startup.
1096                return Err(AdapterError::NetworkPolicyDenied(
1097                    super::NetworkPolicyError::MissingIp,
1098                ));
1099            }
1100        }
1101
1102        // Temporary schemas are now created lazily when the first temporary object is created,
1103        // rather than eagerly on connection startup. This avoids expensive catalog_mut() calls
1104        // for the common case where connections never create temporary objects.
1105
1106        Ok((
1107            role_id,
1108            SuperuserAttribute(superuser_attribute),
1109            session_defaults,
1110        ))
1111    }
1112
1113    /// Handles an execute command.
1114    #[instrument(name = "coord::handle_execute", fields(session = session.uuid().to_string()))]
1115    pub(crate) async fn handle_execute(
1116        &mut self,
1117        portal_name: String,
1118        mut session: Session,
1119        tx: ClientTransmitter<ExecuteResponse>,
1120        // If this command was part of another execute command
1121        // (for example, executing a `FETCH` statement causes an execute to be
1122        //  issued for the cursor it references),
1123        // then `outer_context` should be `Some`.
1124        // This instructs the coordinator that the
1125        // outer execute should be considered finished once the inner one is.
1126        outer_context: Option<ExecuteContextExtra>,
1127    ) {
1128        // Arm the obligation before anything can return: from here on, every
1129        // exit either retires it or hands it to a guard whose `Drop` does.
1130        // Nothing could have dropped it on the way here either, the command
1131        // travels a channel that only this loop drains.
1132        let outer_context = outer_context
1133            .map(|extra| ExecuteContextGuard::new(extra.retire(), self.internal_cmd_tx.clone()));
1134
1135        // A new statement is starting, so discard any cancellation that was signaled while no
1136        // statement was running. Such a cancellation targeted an earlier statement and must not
1137        // cancel the new one. (Like in PostgreSQL, a cancel request that arrives when nothing is
1138        // running has no effect.) The watch would otherwise retain a stale `true` within an
1139        // explicit transaction, because it is removed only when the transaction is cleared, not
1140        // at statement end.
1141        //
1142        // Don't do this for nested executes (e.g., FETCH executing its cursor's statement): the
1143        // outer statement is still running and a pending cancellation may target it.
1144        if outer_context.is_none() {
1145            self.connection_cancel_watches.remove(session.conn_id());
1146        }
1147
1148        if session.vars().emit_trace_id_notice() {
1149            let span_context = tracing::Span::current()
1150                .context()
1151                .span()
1152                .span_context()
1153                .clone();
1154            if span_context.is_valid() {
1155                session.add_notice(AdapterNotice::QueryTrace {
1156                    trace_id: span_context.trace_id(),
1157                });
1158            }
1159        }
1160
1161        if let Err(err) = Self::verify_portal(self.catalog(), &mut session, &portal_name) {
1162            // If statement logging hasn't started yet, we don't need
1163            // to add any "end" event, so just make up a no-op
1164            // `ExecuteContextExtra` here, via `Default::default`.
1165            //
1166            // It's a bit unfortunate because the edge case of failed
1167            // portal verifications won't show up in statement
1168            // logging, but there seems to be nothing else we can do,
1169            // because we need access to the portal to begin logging.
1170            //
1171            // Another option would be to log a begin and end event, but just fill in NULLs
1172            // for everything we get from the portal (prepared statement id, params).
1173            let extra = outer_context.unwrap_or_else(Default::default);
1174            let ctx = ExecuteContext::from_parts(tx, self.internal_cmd_tx.clone(), session, extra);
1175            return ctx.retire(Err(err));
1176        }
1177
1178        // The reference to `portal` can't outlive `session`, which we
1179        // use to construct the context, so scope the reference to this block where we
1180        // get everything we need from the portal for later.
1181        let (stmt, ctx, params) = {
1182            let portal = session
1183                .get_portal_unverified(&portal_name)
1184                .expect("known to exist");
1185            let params = portal.parameters.clone();
1186            let stmt = portal.stmt.clone();
1187            let logging = Arc::clone(&portal.logging);
1188            let lifecycle_timestamps = portal.lifecycle_timestamps.clone();
1189
1190            let extra = if let Some(extra) = outer_context {
1191                // We are executing in the context of another SQL statement, so we don't
1192                // want to begin statement logging anew. The context of the actual statement
1193                // being executed is the one that should be retired once this finishes.
1194                extra
1195            } else {
1196                // This is a new statement, log it and return the context
1197                let maybe_uuid = self.begin_statement_execution(
1198                    &mut session,
1199                    &params,
1200                    &logging,
1201                    lifecycle_timestamps,
1202                );
1203
1204                ExecuteContextGuard::new(maybe_uuid, self.internal_cmd_tx.clone())
1205            };
1206            let ctx = ExecuteContext::from_parts(tx, self.internal_cmd_tx.clone(), session, extra);
1207            (stmt, ctx, params)
1208        };
1209
1210        let stmt = match stmt {
1211            Some(stmt) => stmt,
1212            None => return ctx.retire(Ok(ExecuteResponse::EmptyQuery)),
1213        };
1214
1215        let session_type = metrics::session_type_label_value(ctx.session().user());
1216        let stmt_type = metrics::statement_type_label_value(&stmt);
1217        self.metrics
1218            .query_total
1219            .with_label_values(&[session_type, stmt_type])
1220            .inc();
1221        self.handle_execute_inner(stmt, params, ctx).await
1222    }
1223
1224    #[instrument(
1225        name = "coord::handle_execute_inner",
1226        fields(stmt = truncate_sql_for_logging(stmt.to_ast_string_redacted())),
1227    )]
1228    pub(crate) async fn handle_execute_inner(
1229        &mut self,
1230        stmt: Arc<Statement<Raw>>,
1231        params: Params,
1232        mut ctx: ExecuteContext,
1233    ) {
1234        // This comment describes the various ways DDL can execute (the ordered operations: name
1235        // resolve, purify, plan, sequence), all of which are managed by this function. DDL has
1236        // three notable properties that all partially interact.
1237        //
1238        // 1. Most DDL statements (and a few others) support single-statement transaction delayed
1239        //    execution. This occurs when a session executes `BEGIN`, a single DDL, then `COMMIT`.
1240        //    We announce success of the single DDL when it is executed, but do not attempt to plan
1241        //    or sequence it until `COMMIT`, which is able to error if needed while sequencing the
1242        //    DDL (this behavior is Postgres-compatible). The purpose of this is because some
1243        //    drivers or tools wrap all statements in `BEGIN` and `COMMIT` and we would like them to
1244        //    work. When the single DDL is announced as successful we also put the session's
1245        //    transaction ops into `SingleStatement` which will produce an error if any other
1246        //    statement is run in the transaction except `COMMIT`. Additionally, this will cause
1247        //    `handle_execute_inner` to stop further processing (no planning, etc.) of the
1248        //    statement.
1249        // 2. A few other DDL statements (`ALTER .. RENAME/SWAP`) enter the `DDL` ops which allows
1250        //    any number of only these DDL statements to be executed in a transaction. During
1251        //    sequencing we run an incremental catalog dry run against in-memory transaction state
1252        //    and store the resulting `CatalogState` in `TransactionOps::DDL`, but nothing is yet
1253        //    committed to the durable catalog. At `COMMIT`, all accumulated ops are applied in one
1254        //    catalog transaction. The purpose of this is to allow multiple, atomic renames in the
1255        //    same transaction.
1256        // 3. Some DDLs do off-thread work during purification or sequencing that is expensive or
1257        //    makes network calls (interfacing with secrets, optimization of views/indexes, source
1258        //    purification). These must guarantee correctness when they return to the main
1259        //    coordinator thread because the catalog state could have changed while they were doing
1260        //    the off-thread work. Previously we would use `PlanValidity::Checks` to specify a bunch
1261        //    of IDs that we needed to exist. We discovered the way we were doing that was not
1262        //    always correct. Instead of attempting to get that completely right, we have opted to
1263        //    serialize DDL. Getting this right is difficult because catalog changes can affect name
1264        //    resolution, planning, sequencing, and optimization. Correctly writing logic that is
1265        //    aware of all possible catalog changes that would affect any of those parts is not
1266        //    something our current code has been designed to be helpful at. Even if a DDL statement
1267        //    is doing off-thread work, another DDL must not yet execute at all. Executing these
1268        //    serially will guarantee that no off-thread work has affected the state of the catalog.
1269        //    This is done by adding a VecDeque of deferred statements and a lock to the
1270        //    Coordinator. When a DDL is run in `handle_execute_inner` (after applying whatever
1271        //    transaction ops are needed to the session as described above), it attempts to own the
1272        //    lock (a tokio Mutex). If acquired, it stashes the lock in the connection`s `ConnMeta`
1273        //    struct in `active_conns` and proceeds. The lock is dropped at transaction end in
1274        //    `clear_transaction` and a message sent to the Coordinator to execute the next queued
1275        //    DDL. If the lock could not be acquired, the DDL is put into the VecDeque where it
1276        //    awaits dequeuing caused by the lock being released.
1277
1278        if StatementKind::from(&*stmt).is_explain() {
1279            if let Err(error) = ctx.session_mut().transaction_mut().record_explain() {
1280                return ctx.retire(Err(error));
1281            }
1282        }
1283
1284        // For `Started`, this separates the first statement of an extended-protocol
1285        // pipeline from a later one that joins the ops staged before it.
1286        let txn_contains_ops = ctx.session().transaction().contains_ops();
1287
1288        // Verify that this statement type can be executed in the current
1289        // transaction state.
1290        match ctx.session().transaction() {
1291            // By this point we should be in a running transaction.
1292            TransactionStatus::Default => unreachable!(),
1293
1294            // Failed transactions have already been checked in pgwire for a safe statement
1295            // (COMMIT, ROLLBACK, etc.) and can proceed.
1296            TransactionStatus::Failed(_) => {}
1297
1298            // Started is a deceptive name, and means different things depending on which
1299            // protocol was used. It's either exactly one statement (known because this
1300            // is the simple protocol and the parser parsed the entire string, and it had
1301            // one statement). Or from the extended protocol, it means *some* query is
1302            // being executed, but there might be others after it before the Sync (commit)
1303            // message. Postgres handles this by teaching Started to eagerly commit certain
1304            // statements that can't be run in a transaction block.
1305            TransactionStatus::Started(_) if !txn_contains_ops => {
1306                if let Statement::Declare(_) = &*stmt {
1307                    // Declare is an exception. Although it's not against any spec to execute
1308                    // it, it will always result in nothing happening, since all portals will be
1309                    // immediately closed. Users don't know this detail, so this error helps them
1310                    // understand what's going wrong. Postgres does this too.
1311                    return ctx.retire(Err(AdapterError::OperationRequiresTransaction(
1312                        "DECLARE CURSOR".into(),
1313                    )));
1314                }
1315            }
1316
1317            // Implicit or explicit transactions.
1318            //
1319            // Implicit transactions happen when a multi-statement query is executed
1320            // (a "simple query"). However if a "BEGIN" appears somewhere in there,
1321            // then the existing implicit transaction will be upgraded to an explicit
1322            // transaction. Thus, we should not separate what implicit and explicit
1323            // transactions can do unless there's some additional checking to make sure
1324            // something disallowed in explicit transactions did not previously take place
1325            // in the implicit portion.
1326            //
1327            // A `Started` transaction with staged ops belongs here too: this statement
1328            // runs alongside them, so a DDL or read-then-write that cannot see them must
1329            // be rejected rather than run against a state that lacks them.
1330            TransactionStatus::Started(_)
1331            | TransactionStatus::InTransactionImplicit(_)
1332            | TransactionStatus::InTransaction(_) => {
1333                match &*stmt {
1334                    // Statements that are safe in a transaction. We still need to verify that we
1335                    // don't interleave reads and writes since we can't perform those serializably.
1336                    Statement::Close(_)
1337                    | Statement::Commit(_)
1338                    | Statement::Copy(_)
1339                    | Statement::Deallocate(_)
1340                    | Statement::Declare(_)
1341                    | Statement::Discard(_)
1342                    | Statement::Fetch(_)
1343                    | Statement::Prepare(_)
1344                    | Statement::Rollback(_)
1345                    | Statement::SetTransaction(_)
1346                    | Statement::Show(_)
1347                    | Statement::SetVariable(_)
1348                    | Statement::ResetVariable(_)
1349                    | Statement::StartTransaction(_)
1350                    | Statement::Raise(_)
1351                    | Statement::ExplainPlan(_)
1352                    | Statement::ExplainPushdown(_)
1353                    | Statement::ExplainAnalyzeObject(_)
1354                    | Statement::ExplainAnalyzeCluster(_)
1355                    | Statement::ExplainSinkSchema(_) => {
1356                        // Always safe.
1357                    }
1358
1359                    // `SessionClient::execute_attempts` unrolls `EXECUTE`, and the frontend takes
1360                    // over the other statements, so none of them reach the coordinator. Planning one
1361                    // below would hit `sequence_plan`'s soft-panicking arm.
1362                    Statement::Delete(_)
1363                    | Statement::Execute(_)
1364                    | Statement::ExplainTimestamp(_)
1365                    | Statement::Insert(_)
1366                    | Statement::Select(_)
1367                    | Statement::Subscribe(_)
1368                    | Statement::Update(_) => {}
1369
1370                    // These statements must be kept in-sync with `must_serialize_ddl()`.
1371                    Statement::AlterObjectRename(_)
1372                    | Statement::AlterObjectSwap(_)
1373                    | Statement::CreateTableFromSource(_)
1374                    | Statement::CreateSource(_) => {
1375                        if !ctx.session().transaction().is_ddl() {
1376                            // Preparation can yield before the first dry run. Capture both
1377                            // baselines now so unrelated commits cannot mix their contents.
1378                            let (state, snapshot) = self.catalog().ddl_transaction_snapshot().await;
1379
1380                            // Initialize our transaction with a set of empty ops, or return an error
1381                            // if we can't run a DDL transaction
1382                            let txn_status = ctx.session_mut().transaction_mut();
1383                            if let Err(err) = txn_status.add_ops(TransactionOps::DDL {
1384                                commands: vec![],
1385                                state,
1386                                snapshot,
1387                            }) {
1388                                return ctx.retire(Err(err));
1389                            }
1390                        }
1391                    }
1392
1393                    // Statements below must by run singly (in Started).
1394                    Statement::AlterCluster(_)
1395                    | Statement::AlterConnection(_)
1396                    | Statement::AlterDefaultPrivileges(_)
1397                    | Statement::AlterIndex(_)
1398                    | Statement::AlterMaterializedViewApplyReplacement(_)
1399                    | Statement::AlterSetCluster(_)
1400                    | Statement::AlterOwner(_)
1401                    | Statement::AlterRetainHistory(_)
1402                    | Statement::AlterRole(_)
1403                    | Statement::AlterSecret(_)
1404                    | Statement::AlterSink(_)
1405                    | Statement::AlterSource(_)
1406                    | Statement::AlterSystemReset(_)
1407                    | Statement::AlterSystemResetAll(_)
1408                    | Statement::AlterSystemSet(_)
1409                    | Statement::AlterTableAddColumn(_)
1410                    | Statement::AlterNetworkPolicy(_)
1411                    | Statement::AlterQueryPolicy(_)
1412                    | Statement::CreateCluster(_)
1413                    | Statement::CreateClusterReplica(_)
1414                    | Statement::CreateConnection(_)
1415                    | Statement::CreateDatabase(_)
1416                    | Statement::CreateIndex(_)
1417                    | Statement::CreateMaterializedView(_)
1418                    | Statement::CreateRole(_)
1419                    | Statement::CreateSchema(_)
1420                    | Statement::CreateSecret(_)
1421                    | Statement::CreateSink(_)
1422                    | Statement::CreateMetricSink(_)
1423                    | Statement::CreateSubsource(_)
1424                    | Statement::CreateTable(_)
1425                    | Statement::CreateType(_)
1426                    | Statement::CreateView(_)
1427                    | Statement::CreateWebhookSource(_)
1428                    | Statement::CreateNetworkPolicy(_)
1429                    | Statement::CreateQueryPolicy(_)
1430                    | Statement::DropObjects(_)
1431                    | Statement::DropOwned(_)
1432                    | Statement::GrantPrivileges(_)
1433                    | Statement::GrantRole(_)
1434                    | Statement::ReassignOwned(_)
1435                    | Statement::RevokePrivileges(_)
1436                    | Statement::RevokeRole(_)
1437                    | Statement::ValidateConnection(_)
1438                    | Statement::Comment(_)
1439                    | Statement::ExecuteUnitTest(_) => {
1440                        let txn_status = ctx.session_mut().transaction_mut();
1441
1442                        // If we're not in an implicit transaction and we could generate exactly one
1443                        // valid ExecuteResponse, we can delay execution until commit.
1444                        if !txn_status.is_implicit() {
1445                            // Statements whose tag is trivial (known only from an unexecuted statement) can
1446                            // be run in a special single-statement explicit mode. In this mode (`BEGIN;
1447                            // <stmt>; COMMIT`), we generate the expected tag from a successful <stmt>, but
1448                            // delay execution until `COMMIT`.
1449                            if let Ok(resp) = ExecuteResponse::try_from(&*stmt) {
1450                                if let Err(err) = txn_status
1451                                    .add_ops(TransactionOps::SingleStatement { stmt, params })
1452                                {
1453                                    ctx.retire(Err(err));
1454                                    return;
1455                                }
1456                                ctx.retire(Ok(resp));
1457                                return;
1458                            }
1459                        }
1460
1461                        // For statements that can carry sensitive material, redact
1462                        // literals so they don't leak into the error message, which
1463                        // is persisted in `mz_statement_execution_history` (matching
1464                        // how their SQL text is redacted). Other statements keep
1465                        // their literals for a clearer error.
1466                        let op = if StatementKind::from(&*stmt).is_sensitive() {
1467                            stmt.to_ast_string_redacted()
1468                        } else {
1469                            stmt.to_string()
1470                        };
1471                        return ctx.retire(Err(AdapterError::OperationProhibitsTransaction(op)));
1472                    }
1473                }
1474            }
1475        }
1476
1477        // DDLs must be planned and sequenced serially. We do not rely on PlanValidity checking
1478        // various IDs because we have incorrectly done that in the past. Attempt to acquire the
1479        // ddl lock. The lock is stashed in the ConnMeta which is dropped at transaction end. If
1480        // acquired, proceed with sequencing. If not, enqueue and return. This logic assumes that
1481        // Coordinator::clear_transaction is correctly called when session transactions are ended
1482        // because that function will release the held lock from active_conns.
1483        if Self::must_serialize_ddl(&stmt, &ctx) {
1484            if let Ok(guard) = self.serialized_ddl.try_lock_owned() {
1485                let prev = self
1486                    .active_conns
1487                    .get_mut(ctx.session().conn_id())
1488                    .expect("connection must exist")
1489                    .deferred_lock
1490                    .replace(guard);
1491                assert!(
1492                    prev.is_none(),
1493                    "connections should have at most one lock guard"
1494                );
1495            } else {
1496                if self
1497                    .active_conns
1498                    .get(ctx.session().conn_id())
1499                    .expect("connection must exist")
1500                    .deferred_lock
1501                    .is_some()
1502                {
1503                    // This session *already* has the lock, and incorrectly tried to execute another
1504                    // DDL while still holding the lock, violating the assumption documented above.
1505                    // This is an internal error, probably in some AdapterClient user (pgwire or
1506                    // http). Because the session is now in some unexpected state, return an error
1507                    // which should cause the AdapterClient user to fail the transaction.
1508                    // (Terminating the connection is maybe what we would prefer to do, but is not
1509                    // currently a thing we can do from the coordinator: calling handle_terminate
1510                    // cleans up Coordinator state for the session but doesn't inform the
1511                    // AdapterClient that the session should terminate.)
1512                    soft_panic_or_log!(
1513                        "session {} attempted to get ddl lock while already owning it",
1514                        ctx.session().conn_id()
1515                    );
1516                    ctx.retire(Err(AdapterError::Internal(
1517                        "session attempted to get ddl lock while already owning it".to_string(),
1518                    )));
1519                    return;
1520                }
1521                self.serialized_ddl
1522                    .push_back(DeferredDdl::Statement { ctx, stmt, params });
1523                return;
1524            }
1525        }
1526
1527        if catalog::command::CatalogResultCommand::supports_statement(&stmt) {
1528            self.sequence_catalog_result_command(ctx, stmt, params);
1529            return;
1530        }
1531        if matches!(&*stmt, Statement::CreateConnection(_)) {
1532            self.sequence_create_connection_command(ctx, stmt, params)
1533                .await;
1534            return;
1535        }
1536        if matches!(&*stmt, Statement::AlterConnection(stmt)
1537            if !stmt.actions.iter().any(|action|
1538                matches!(action, AlterConnectionAction::RotateKeys)))
1539        {
1540            self.sequence_alter_connection_command(ctx, stmt, params)
1541                .await;
1542            return;
1543        }
1544
1545        if matches!(
1546            &*stmt,
1547            Statement::AlterObjectRename(_) | Statement::AlterObjectSwap(_)
1548        ) {
1549            self.sequence_rename_command(ctx, stmt, params).await;
1550            return;
1551        }
1552
1553        if matches!(
1554            &*stmt,
1555            Statement::CreateSource(_) | Statement::CreateTableFromSource(_)
1556        ) || matches!(&*stmt, Statement::AlterSource(stmt)
1557            if matches!(stmt.action,
1558                mz_sql::ast::AlterSourceAction::AddSubsources { .. }
1559                | mz_sql::ast::AlterSourceAction::RefreshReferences))
1560        {
1561            self.sequence_source_statement(ctx, stmt, params).await;
1562            return;
1563        }
1564
1565        let catalog = self.catalog();
1566        let catalog = catalog.for_session(ctx.session());
1567        let original_stmt = Arc::clone(&stmt);
1568        // `resolved_ids` should be derivable from `stmt`. If `stmt` is transformed to remove/add
1569        // IDs, then `resolved_ids` should be updated to also remove/add those IDs.
1570        let (stmt, mut resolved_ids) = match mz_sql::names::resolve(&catalog, (*stmt).clone()) {
1571            Ok(resolved) => resolved,
1572            Err(e) => return ctx.retire(Err(e.into())),
1573        };
1574        // N.B. The catalog can change during purification so we must validate that the dependencies still exist after
1575        // purification.  This should be done back on the main thread.
1576        // We do the validation:
1577        //   - In the handler for `Message::PurifiedStatementReady`, before we handle the purified statement.
1578        // If we add special handling for more types of `Statement`s, we'll need to ensure similar verification
1579        // occurs.
1580        let (stmt, resolved_ids) = match stmt {
1581            // Various statements must be purified off the main coordinator thread of control.
1582            stmt if Self::must_spawn_purification(&stmt) => {
1583                let internal_cmd_tx = self.internal_cmd_tx.clone();
1584                let conn_id = ctx.session().conn_id().clone();
1585                let catalog = self.owned_catalog();
1586                let now = self.now();
1587                let otel_ctx = OpenTelemetryContext::obtain();
1588                let current_storage_configuration = self.controller.storage.config().clone();
1589                task::spawn(|| format!("purify:{conn_id}"), async move {
1590                    let conn_catalog = catalog.for_session(ctx.session());
1591
1592                    let statement_source = mz_sql::pure::statement_source(&conn_catalog, &stmt);
1593
1594                    // Authorization is usually checked after planning, but purification
1595                    // happens before planning and may use connections and secrets, so it
1596                    // gets its own check.
1597                    if let Err(e) = rbac::check_purification(
1598                        &conn_catalog,
1599                        ctx.session(),
1600                        statement_source,
1601                        &resolved_ids,
1602                    ) {
1603                        return ctx.retire(Err(e.into()));
1604                    }
1605
1606                    let (result, cluster_id) = mz_sql::pure::purify_statement(
1607                        conn_catalog,
1608                        now,
1609                        stmt,
1610                        &current_storage_configuration,
1611                    )
1612                    .await;
1613                    let result = result.map_err(|e| e.into());
1614                    // `ALTER SOURCE` carries its target as an unresolved name, so name
1615                    // resolution never records it and `resolved_ids` does not cover it.
1616                    // Without it a source dropped while purification ran off-thread
1617                    // passes the validity check below and then panics the coordinator
1618                    // on the missing catalog entry ("catalog out of sync") during
1619                    // planning.
1620                    let mut dependency_ids: BTreeSet<_> = resolved_ids.items().copied().collect();
1621                    dependency_ids.extend(statement_source.map(|source| source.id()));
1622                    let plan_validity = PlanValidity::new(
1623                        &catalog,
1624                        dependency_ids,
1625                        cluster_id,
1626                        None,
1627                        ctx.session().role_metadata().clone(),
1628                    );
1629                    // It is not an error for purification to complete after `internal_cmd_rx` is dropped.
1630                    let result = internal_cmd_tx.send(Message::PurifiedStatementReady(
1631                        PurifiedStatementReady {
1632                            ctx,
1633                            result,
1634                            params,
1635                            plan_validity,
1636                            original_stmt,
1637                            otel_ctx,
1638                        },
1639                    ));
1640                    if let Err(e) = result {
1641                        tracing::warn!("internal_cmd_rx dropped before we could send: {:?}", e);
1642                    }
1643                });
1644                return;
1645            }
1646
1647            // `CREATE SUBSOURCE` statements are disallowed for users and are only generated
1648            // automatically as part of purification
1649            Statement::CreateSubsource(_) => {
1650                ctx.retire(Err(AdapterError::Unsupported(
1651                    "CREATE SUBSOURCE statements",
1652                )));
1653                return;
1654            }
1655
1656            Statement::CreateMaterializedView(mut cmvs) => {
1657                // `CREATE MATERIALIZED VIEW ... AS OF ...` syntax is disallowed for users and is
1658                // only used for storing initial frontiers in the catalog.
1659                if cmvs.as_of.is_some() {
1660                    return ctx.retire(Err(AdapterError::Unsupported(
1661                        "CREATE MATERIALIZED VIEW ... AS OF statements",
1662                    )));
1663                }
1664
1665                let mz_now = match self
1666                    .resolve_mz_now_for_create_materialized_view(
1667                        &cmvs,
1668                        &resolved_ids,
1669                        ctx.session_mut(),
1670                        true,
1671                    )
1672                    .await
1673                {
1674                    Ok(mz_now) => mz_now,
1675                    Err(e) => return ctx.retire(Err(e)),
1676                };
1677
1678                let catalog = self.catalog().for_session(ctx.session());
1679
1680                purify_create_materialized_view_options(
1681                    catalog,
1682                    mz_now,
1683                    &mut cmvs,
1684                    &mut resolved_ids,
1685                );
1686
1687                let purified_stmt =
1688                    Statement::CreateMaterializedView(CreateMaterializedViewStatement::<Aug> {
1689                        if_exists: cmvs.if_exists,
1690                        name: cmvs.name,
1691                        columns: cmvs.columns,
1692                        replacement_for: cmvs.replacement_for,
1693                        in_cluster: cmvs.in_cluster,
1694                        in_cluster_replica: cmvs.in_cluster_replica,
1695                        query: cmvs.query,
1696                        with_options: cmvs.with_options,
1697                        as_of: None,
1698                    });
1699
1700                // (Purifying CreateMaterializedView doesn't happen async, so no need to send
1701                // `Message::PurifiedStatementReady` here.)
1702                (purified_stmt, resolved_ids)
1703            }
1704
1705            Statement::ExplainPlan(ExplainPlanStatement {
1706                stage,
1707                with_options,
1708                format,
1709                explainee: Explainee::CreateMaterializedView(box_cmvs, broken),
1710            }) => {
1711                let mut cmvs = *box_cmvs;
1712                let mz_now = match self
1713                    .resolve_mz_now_for_create_materialized_view(
1714                        &cmvs,
1715                        &resolved_ids,
1716                        ctx.session_mut(),
1717                        false,
1718                    )
1719                    .await
1720                {
1721                    Ok(mz_now) => mz_now,
1722                    Err(e) => return ctx.retire(Err(e)),
1723                };
1724
1725                let catalog = self.catalog().for_session(ctx.session());
1726
1727                purify_create_materialized_view_options(
1728                    catalog,
1729                    mz_now,
1730                    &mut cmvs,
1731                    &mut resolved_ids,
1732                );
1733
1734                let purified_stmt = Statement::ExplainPlan(ExplainPlanStatement {
1735                    stage,
1736                    with_options,
1737                    format,
1738                    explainee: Explainee::CreateMaterializedView(Box::new(cmvs), broken),
1739                });
1740
1741                (purified_stmt, resolved_ids)
1742            }
1743
1744            // All other statements are handled immediately.
1745            _ => (stmt, resolved_ids),
1746        };
1747
1748        match self.plan_statement(ctx.session(), stmt, &params, &resolved_ids) {
1749            Ok((plan, sql_impl_ids)) => {
1750                self.sequence_plan(ctx, plan, resolved_ids, sql_impl_ids)
1751                    .await
1752            }
1753            Err(e) => ctx.retire(Err(e)),
1754        }
1755    }
1756
1757    /// Whether the statement must be serialized and is DDL.
1758    fn must_serialize_ddl(stmt: &Statement<Raw>, ctx: &ExecuteContext) -> bool {
1759        // Non-DDL is not serialized here.
1760        if !StatementClassification::from(&*stmt).is_ddl() {
1761            return false;
1762        }
1763        // External preparation can perform arbitrarily slow network calls, so it must not
1764        // hold the DDL lock. Source commands re-execute against the current catalog at commit.
1765        // CREATE SINK and the remaining purified ALTER SOURCE forms use PlanValidity.
1766        if Self::must_spawn_purification(stmt) {
1767            return false;
1768        }
1769
1770        // Statements that support multiple DDLs in a single transaction aren't serialized here.
1771        // Their operations are serialized when applied to the catalog, guaranteeing that any
1772        // off-thread DDLs concurrent with a multiple DDL transaction will have a serial order.
1773        if ctx.session.transaction().is_ddl() {
1774            return false;
1775        }
1776
1777        // Some DDL is exempt. It is not great that we are matching on Statements here because
1778        // different plans can be produced from the same top-level statement type (i.e., `ALTER
1779        // CONNECTION ROTATE KEYS`). But the whole point of this is to prevent things from being
1780        // planned in the first place, so we accept the abstraction leak.
1781        match stmt {
1782            // Secrets have a small and understood set of dependencies, and their off-thread work
1783            // interacts with k8s.
1784            Statement::AlterSecret(_) => false,
1785            Statement::CreateSecret(_) => false,
1786            Statement::AlterConnection(AlterConnectionStatement { actions, .. })
1787                if actions
1788                    .iter()
1789                    .all(|action| matches!(action, AlterConnectionAction::RotateKeys)) =>
1790            {
1791                false
1792            }
1793
1794            // The off-thread work that altering a cluster may do (waiting for replicas to spin-up),
1795            // does not affect its catalog names or ids and so is safe to not serialize. This could
1796            // change the set of replicas that exist. For queries that name replicas or use the
1797            // current_replica session var, the `replica_id` field of `PlanValidity` serves to
1798            // ensure that those replicas exist during the query finish stage. Additionally, that
1799            // work can take hours (configured by the user), so would also be a bad experience for
1800            // users.
1801            Statement::AlterCluster(_) => false,
1802
1803            // `ALTER SINK` waits for the sink to make enough progress for a clean cutover to the
1804            // new configuration. If the sink is stalled, it may block forever. Checks in
1805            // sequencing ensure that the operation fails if any one of these happens concurrently:
1806            //   * the sink is dropped
1807            //   * the source relation is dropped
1808            //   * another `ALTER SINK` for the same sink is applied first
1809            Statement::AlterSink(_) => false,
1810
1811            // `ALTER MATERIALIZED VIEW ... APPLY REPLACEMENT` waits for the target MV to make
1812            // enough progress for a clean cutover. If the target MV is stalled, it may block
1813            // forever. Checks in sequencing ensure the operation fails if any of these happens
1814            // concurrently:
1815            //   * the target MV is dropped
1816            //   * the replacement MV is dropped
1817            Statement::AlterMaterializedViewApplyReplacement(_) => false,
1818
1819            // Everything else must be serialized.
1820            _ => true,
1821        }
1822    }
1823
1824    /// Whether the statement must be purified off of the Coordinator thread.
1825    ///
1826    /// Every statement listed here is authorized by [`rbac::check_purification`]
1827    /// before purification runs, against the source that
1828    /// [`mz_sql::pure::statement_source`] resolves for it.
1829    fn must_spawn_purification<A: AstInfo>(stmt: &Statement<A>) -> bool {
1830        // `CREATE` and `ALTER` `SOURCE` and `SINK` statements must be purified off the main
1831        // coordinator thread.
1832        if !matches!(
1833            stmt,
1834            Statement::CreateSource(_)
1835                | Statement::AlterSource(_)
1836                | Statement::CreateSink(_)
1837                | Statement::CreateTableFromSource(_)
1838        ) {
1839            return false;
1840        }
1841
1842        // However `ALTER SOURCE RETAIN HISTORY` should be excluded from off-thread purification.
1843        if let Statement::AlterSource(stmt) = stmt {
1844            let names: Vec<CreateSourceOptionName> = match &stmt.action {
1845                AlterSourceAction::SetOptions(options) => {
1846                    options.iter().map(|o| o.name.clone()).collect()
1847                }
1848                AlterSourceAction::ResetOptions(names) => names.clone(),
1849                _ => vec![],
1850            };
1851            if !names.is_empty()
1852                && names
1853                    .iter()
1854                    .all(|n| matches!(n, CreateSourceOptionName::RetainHistory))
1855            {
1856                return false;
1857            }
1858        }
1859
1860        true
1861    }
1862
1863    /// Chooses a timestamp for `mz_now()`, if `mz_now()` occurs in a REFRESH option of the
1864    /// materialized view. Additionally, if `acquire_read_holds` is true and the MV has any REFRESH
1865    /// option, this function grabs read holds at the earliest possible time on input collections
1866    /// that might be involved in the MV.
1867    ///
1868    /// Note that this is NOT what handles `mz_now()` in the query part of the MV. (handles it only
1869    /// in `with_options`).
1870    ///
1871    /// (Note that the chosen timestamp won't be the same timestamp as the system table inserts,
1872    /// unfortunately.)
1873    async fn resolve_mz_now_for_create_materialized_view(
1874        &mut self,
1875        cmvs: &CreateMaterializedViewStatement<Aug>,
1876        resolved_ids: &ResolvedIds,
1877        session: &Session,
1878        acquire_read_holds: bool,
1879    ) -> Result<Option<Timestamp>, AdapterError> {
1880        if cmvs
1881            .with_options
1882            .iter()
1883            .any(|wo| matches!(wo.value, Some(WithOptionValue::Refresh(..))))
1884        {
1885            let catalog = self.catalog().for_session(session);
1886            let cluster = mz_sql::plan::resolve_cluster_for_materialized_view(&catalog, cmvs)?;
1887            let ids = self
1888                .index_oracle(cluster)
1889                .sufficient_collections(resolved_ids.collections().copied());
1890
1891            // If there is any REFRESH option, then acquire read holds. (Strictly speaking, we'd
1892            // need this only if there is a `REFRESH AT`, not for `REFRESH EVERY`, because later
1893            // we want to check the AT times against the read holds that we acquire here. But
1894            // we do it for any REFRESH option, to avoid having so many code paths doing different
1895            // things.)
1896            //
1897            // It's important that we acquire read holds _before_ we determine the least valid read.
1898            // Otherwise, we're not guaranteed that the since frontier doesn't
1899            // advance forward from underneath us.
1900            let read_holds = self.acquire_read_holds(&ids);
1901
1902            // Does `mz_now()` occur?
1903            let mz_now_ts = if cmvs
1904                .with_options
1905                .iter()
1906                .any(materialized_view_option_contains_temporal)
1907            {
1908                let timeline_context = self
1909                    .catalog()
1910                    .validate_timeline_context(resolved_ids.collections().copied())?;
1911
1912                // We default to EpochMilliseconds, similarly to `determine_timestamp_for`,
1913                // but even in the TimestampIndependent case.
1914                // Note that we didn't accurately decide whether we are TimestampDependent
1915                // or TimestampIndependent, because for this we'd need to also check whether
1916                // `query.contains_temporal()`, similarly to how `peek_stage_validate` does.
1917                // However, this doesn't matter here, as we are just going to default to
1918                // EpochMilliseconds in both cases.
1919                let timeline = timeline_context
1920                    .timeline()
1921                    .unwrap_or(&Timeline::EpochMilliseconds);
1922
1923                // Let's start with the timestamp oracle read timestamp.
1924                let mut timestamp = self.get_timestamp_oracle(timeline).read_ts().await;
1925
1926                // If `least_valid_read` is later than the oracle, then advance to that time.
1927                // If we didn't do this, then there would be a danger of missing the first refresh,
1928                // which might cause the materialized view to be unreadable for hours. This might
1929                // be what was happening here:
1930                // https://github.com/MaterializeInc/database-issues/issues/7265#issuecomment-1931856361
1931                //
1932                // In the long term, it would be good to actually block the MV creation statement
1933                // until `least_valid_read`. https://github.com/MaterializeInc/database-issues/issues/7504
1934                // Without blocking, we have the problem that a REFRESH AT CREATION is not linearized
1935                // with the CREATE MATERIALIZED VIEW statement, in the sense that a query from the MV
1936                // after its creation might see input changes that happened after the CRATE MATERIALIZED
1937                // VIEW statement returned.
1938                let oracle_timestamp = timestamp;
1939                let least_valid_read = read_holds.least_valid_read();
1940                timestamp.advance_by(least_valid_read.borrow());
1941
1942                if oracle_timestamp != timestamp {
1943                    warn!(%cmvs.name, %oracle_timestamp, %timestamp, "REFRESH MV's inputs are not readable at the oracle read ts");
1944                }
1945
1946                info!("Resolved `mz_now()` to {timestamp} for REFRESH MV");
1947                Ok(Some(timestamp))
1948            } else {
1949                Ok(None)
1950            };
1951
1952            // NOTE: The Drop impl of ReadHolds makes sure that the hold is
1953            // released when we don't use it.
1954            if acquire_read_holds {
1955                self.store_transaction_read_holds(session.conn_id().clone(), read_holds);
1956            }
1957
1958            mz_now_ts
1959        } else {
1960            Ok(None)
1961        }
1962    }
1963
1964    /// Instruct the dataflow layer to cancel any ongoing, interactive work for
1965    /// the named `conn_id` if the correct secret key is specified.
1966    ///
1967    /// Note: Here we take a [`ConnectionIdType`] as opposed to an owned
1968    /// `ConnectionId` because this method gets called by external clients when
1969    /// they request to cancel a request.
1970    #[mz_ore::instrument(level = "debug")]
1971    async fn handle_cancel(&mut self, conn_id: ConnectionIdType, secret_key: u32) {
1972        if let Some((id_handle, conn_meta)) = self.active_conns.get_key_value(&conn_id) {
1973            // If the secret key specified by the client doesn't match the
1974            // actual secret key for the target connection, we treat this as a
1975            // rogue cancellation request and ignore it.
1976            if conn_meta.secret_key != secret_key {
1977                return;
1978            }
1979
1980            // Now that we've verified the secret key, this is a privileged
1981            // cancellation request. We can upgrade the raw connection ID to a
1982            // proper `IdHandle`.
1983            self.handle_privileged_cancel(id_handle.clone()).await;
1984        }
1985    }
1986
1987    /// Unconditionally instructs the dataflow layer to cancel any ongoing,
1988    /// interactive work for the named `conn_id`.
1989    #[mz_ore::instrument(level = "debug")]
1990    pub(crate) async fn handle_privileged_cancel(&mut self, conn_id: ConnectionId) {
1991        let canceled_peeks = self.peek_registry.cancel_connection(&conn_id);
1992        self.metrics
1993            .canceled_peeks
1994            .inc_by(u64::cast_from(canceled_peeks));
1995        if let Some(conn) = self.active_conns.get(&conn_id) {
1996            conn.frontend_cancel_tx.send_replace(());
1997        }
1998        let mut maybe_ctx = None;
1999        // A COMMIT waiting for group commit or for its read to be linearized.
2000        let mut maybe_commit_ctx = None;
2001
2002        // Cancel all pending writes for this connection:
2003        // - At most one session-bound write (`UserWriteResponder::Session`),
2004        //   retired via its `ExecuteContext` below.
2005        // - Any frontend blind write that has not entered the committer. The
2006        //   waiter receives `WriteResult::Canceled`. Timestamped writes already
2007        //   in the committer have an indeterminate outcome until it responds.
2008        let (cancelled, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut self.pending_writes)
2009            .into_iter()
2010            .partition(|pending_write_txn| match pending_write_txn {
2011                PendingWriteTxn::User {
2012                    responder: UserWriteResponder::Session(PendingTxn { ctx, .. }),
2013                    ..
2014                } => *ctx.session().conn_id() == conn_id,
2015                PendingWriteTxn::User {
2016                    responder: UserWriteResponder::Internal { conn_id: c, .. },
2017                    ..
2018                } => *c == conn_id,
2019                PendingWriteTxn::System { .. } => false,
2020            });
2021        self.pending_writes = kept;
2022        for pending in cancelled {
2023            match pending {
2024                PendingWriteTxn::User {
2025                    responder: UserWriteResponder::Session(PendingTxn { ctx, .. }),
2026                    ..
2027                } => {
2028                    maybe_commit_ctx = Some(ctx);
2029                }
2030                PendingWriteTxn::User {
2031                    responder: UserWriteResponder::Internal { result, .. },
2032                    ..
2033                } => {
2034                    result.send(WriteResult::Canceled);
2035                }
2036                PendingWriteTxn::System { .. } => unreachable!("filtered out above"),
2037            }
2038        }
2039
2040        // Cancel deferred statements.
2041        let deferred_ddl_idx = self
2042            .serialized_ddl
2043            .iter()
2044            .position(|deferred| *deferred.conn_id() == conn_id);
2045        if let Some(idx) = deferred_ddl_idx {
2046            let deferred = self
2047                .serialized_ddl
2048                .remove(idx)
2049                .expect("known to exist from call to `position` above");
2050            match deferred {
2051                DeferredDdl::Statement {
2052                    ctx,
2053                    stmt: _,
2054                    params: _,
2055                } => maybe_ctx = Some(ctx),
2056                DeferredDdl::Commit(pending) => {
2057                    self.finish_ddl_commit(pending, Err(AdapterError::Canceled));
2058                }
2059            }
2060        }
2061
2062        // Cancel reads waiting on being linearized. There is at most one linearized read per
2063        // session.
2064        if let Some(pending_read_txn) = self.pending_linearize_read_txns.remove(&conn_id) {
2065            maybe_commit_ctx = Some(pending_read_txn.take_context());
2066        }
2067
2068        if let Some(ctx) = maybe_commit_ctx {
2069            // The COMMIT already cleared the session's transaction status, so the transaction's
2070            // `SET LOCAL` and staged variable values are the only transaction state left. Without
2071            // ending them here they apply to the session's next transaction.
2072            //
2073            // NOTE: The error response cannot carry the changed parameters, so a reverted
2074            // parameter in the notify set is not announced to the client.
2075            let (ctx, result) = CompletedClientTransmitter::new(
2076                ctx,
2077                Err(AdapterError::Canceled),
2078                EndTransactionAction::Rollback,
2079            )
2080            .finalize();
2081            ctx.retire(result);
2082        }
2083        if let Some(ctx) = maybe_ctx {
2084            ctx.retire(Err(AdapterError::Canceled));
2085        }
2086
2087        self.cancel_pending_watchsets(&conn_id);
2088        let retire_notify = self.cancel_compute_sinks_for_conn(&conn_id).await;
2089        // SQL cancellation has no success response to delay. Each subscribe
2090        // still waits for its own retraction before it observes retirement.
2091        drop(retire_notify);
2092        self.cancel_pending_copy(&conn_id);
2093        if let Some((tx, _rx)) = self.connection_cancel_watches.get_mut(&conn_id) {
2094            let _ = tx.send(true);
2095        }
2096    }
2097
2098    /// Handle termination of a client session.
2099    ///
2100    /// This cleans up any state in the coordinator associated with the session.
2101    ///
2102    /// Must only be called for connections that completed a successful
2103    /// startup, i.e. that are present in `active_conns`. A failed startup
2104    /// leaves no state behind (see `handle_startup_inner`), so no Terminate
2105    /// may be sent for it.
2106    #[mz_ore::instrument(level = "debug")]
2107    async fn handle_terminate(&mut self, conn_id: ConnectionId) {
2108        // Checked up front so that an unknown connection panics before the cleanup below runs.
2109        assert!(
2110            self.active_conns.contains_key(&conn_id),
2111            "unknown connection: {conn_id:?}"
2112        );
2113        let canceled_peeks = self.peek_registry.close_connection(&conn_id);
2114        self.metrics
2115            .canceled_peeks
2116            .inc_by(u64::cast_from(canceled_peeks));
2117
2118        // We do not need to call clear_transaction here because there are no side effects to run
2119        // based on any session transaction state.
2120        let retire_notify = self.clear_connection(&conn_id).await;
2121        // Termination has no statement response to delay. Each subscribe still
2122        // waits for its own retraction before it observes retirement.
2123        drop(retire_notify);
2124
2125        self.drop_temp_items(&conn_id).await;
2126        // Only call catalog_mut() if a temporary namespace actually exists for this connection.
2127        // This avoids an expensive Arc::make_mut clone for the common case where the connection
2128        // never created any temporary objects.
2129        if self.catalog().state().has_temporary_namespace(&conn_id) {
2130            self.catalog_mut().drop_temporary_namespace(&conn_id);
2131        }
2132        let conn = self.active_conns.remove(&conn_id).expect("conn must exist");
2133        let session_type = metrics::session_type_label_value(conn.user());
2134        self.metrics
2135            .active_sessions
2136            .with_label_values(&[session_type])
2137            .dec();
2138        self.cancel_pending_watchsets(&conn_id);
2139        self.cancel_pending_copy(&conn_id);
2140        self.end_session_for_statement_logging(conn.uuid());
2141
2142        // Queue the retraction for the next group commit without waiting for it, so closing many
2143        // connections at once doesn't block the Coordinator. Forcing a commit here (`defer`)
2144        // would hand every `mz_catalog_server` dataflow a new timestamp per closed session,
2145        // making connection churn cost catalog server CPU per connection.
2146        let update = self
2147            .catalog()
2148            .state()
2149            .pack_session_update(&conn, Diff::MINUS_ONE);
2150        let update = self.catalog().state().resolve_builtin_table_update(update);
2151
2152        let _builtin_update_notify = self.builtin_table_update().background(vec![update]);
2153    }
2154
2155    /// Returns the necessary metadata for appending to a webhook source, and a channel to send
2156    /// rows.
2157    #[mz_ore::instrument(level = "debug")]
2158    fn handle_get_webhook(
2159        &mut self,
2160        database: String,
2161        schema: String,
2162        name: String,
2163        tx: oneshot::Sender<Result<AppendWebhookResponse, AppendWebhookError>>,
2164    ) {
2165        /// Attempts to resolve a Webhook source from a provided `database.schema.name` path.
2166        ///
2167        /// Returns a struct that can be used to append data to the underlying storate collection, and the
2168        /// types we should cast the request to.
2169        fn resolve(
2170            coord: &mut Coordinator,
2171            database: String,
2172            schema: String,
2173            name: String,
2174        ) -> Result<AppendWebhookResponse, PartialItemName> {
2175            // Resolve our collection.
2176            let name = PartialItemName {
2177                database: Some(database),
2178                schema: Some(schema),
2179                item: name,
2180            };
2181            let Ok(entry) = coord
2182                .catalog()
2183                .resolve_entry(None, &vec![], &name, &SYSTEM_CONN_ID)
2184            else {
2185                return Err(name);
2186            };
2187
2188            // Webhooks can be created with `CREATE SOURCE` or `CREATE TABLE`.
2189            let (data_source, desc, global_id) = match entry.item() {
2190                CatalogItem::Source(Source {
2191                    data_source: data_source @ DataSourceDesc::Webhook { .. },
2192                    desc,
2193                    global_id,
2194                    ..
2195                }) => (data_source, desc.clone(), *global_id),
2196                CatalogItem::Table(
2197                    table @ Table {
2198                        desc,
2199                        data_source:
2200                            TableDataSource::DataSource {
2201                                desc: data_source @ DataSourceDesc::Webhook { .. },
2202                                ..
2203                            },
2204                        ..
2205                    },
2206                ) => (data_source, desc.latest(), table.global_id_writes()),
2207                _ => return Err(name),
2208            };
2209
2210            let DataSourceDesc::Webhook {
2211                validate_using,
2212                body_format,
2213                headers,
2214                ..
2215            } = data_source
2216            else {
2217                mz_ore::soft_panic_or_log!("programming error! checked above for webhook");
2218                return Err(name);
2219            };
2220            let body_format = body_format.clone();
2221            let header_tys = headers.clone();
2222
2223            // Assert we have one column for the body, and how ever many are required for
2224            // the headers.
2225            let num_columns = headers.num_columns() + 1;
2226            mz_ore::soft_assert_or_log!(
2227                desc.arity() <= num_columns,
2228                "expected at most {} columns, but got {}",
2229                num_columns,
2230                desc.arity()
2231            );
2232
2233            // Double check that the body column of the webhook source matches the type
2234            // we're about to deserialize as.
2235            let body_column = desc
2236                .get_by_name(&"body".into())
2237                .map(|(_idx, ty)| ty.clone())
2238                .ok_or_else(|| name.clone())?;
2239            assert!(!body_column.nullable, "webhook body column is nullable!?");
2240            assert_eq!(body_column.scalar_type, SqlScalarType::from(body_format));
2241
2242            // Create a validator that can be called to validate a webhook request.
2243            let validator = validate_using.as_ref().map(|v| {
2244                let validation = v.clone();
2245                AppendWebhookValidator::new(validation, coord.caching_secrets_reader.clone())
2246            });
2247
2248            // Get a channel so we can queue updates to be written.
2249            let row_tx = coord
2250                .controller
2251                .storage
2252                .monotonic_appender(global_id)
2253                .map_err(|_| name.clone())?;
2254            let stats = coord
2255                .controller
2256                .storage
2257                .webhook_statistics(global_id)
2258                .map_err(|_| name)?;
2259            let invalidator = coord
2260                .active_webhooks
2261                .entry(entry.id())
2262                .or_insert_with(WebhookAppenderInvalidator::new);
2263            let tx = WebhookAppender::new(row_tx, invalidator.guard(), stats);
2264
2265            Ok(AppendWebhookResponse {
2266                tx,
2267                body_format,
2268                header_tys,
2269                validator,
2270            })
2271        }
2272
2273        let response = resolve(self, database, schema, name).map_err(|name| {
2274            AppendWebhookError::UnknownWebhook {
2275                database: name.database.expect("provided"),
2276                schema: name.schema.expect("provided"),
2277                name: name.item,
2278            }
2279        });
2280        let _ = tx.send(response);
2281    }
2282}