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