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