Skip to main content

mz_adapter/
client.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
10use std::collections::BTreeMap;
11use std::fmt::{Debug, Display, Formatter};
12use std::future::Future;
13use std::pin::{self, Pin};
14use std::sync::Arc;
15use std::time::{Duration, Instant};
16
17use anyhow::bail;
18use chrono::{DateTime, Utc};
19use derivative::Derivative;
20use futures::{FutureExt, Stream, StreamExt};
21use itertools::Itertools;
22use mz_adapter_types::connection::{ConnectionId, ConnectionIdType};
23use mz_auth::password::Password;
24use mz_auth::{Authenticated, AuthenticatorKind};
25use mz_build_info::BuildInfo;
26use mz_compute_types::ComputeInstanceId;
27use mz_expr::UnmaterializableFunc;
28use mz_expr::{CollectionPlan, RowSetFinishing};
29use mz_ore::channel::OneshotReceiverExt;
30use mz_ore::collections::CollectionExt;
31use mz_ore::id_gen::{IdAllocator, IdAllocatorInnerBitSet, MAX_ORG_ID, org_id_conn_bits};
32use mz_ore::instrument;
33use mz_ore::now::{EpochMillis, NowFn, to_datetime};
34use mz_ore::str::StrExt;
35use mz_ore::task::AbortOnDropHandle;
36use mz_ore::thread::JoinOnDropHandle;
37use mz_ore::tracing::OpenTelemetryContext;
38use mz_repr::user::InternalUserMetadata;
39use mz_repr::{CatalogItemId, ColumnIndex, SqlScalarType};
40use mz_sql::ast::ConstantVisitor;
41use mz_sql::ast::{Raw, Statement};
42use mz_sql::catalog::{EnvironmentId, SessionCatalog};
43use mz_sql::plan::{MutationKind, Plan, ReadThenWritePlan};
44use mz_sql::session::hint::ApplicationNameHint;
45use mz_sql::session::metadata::SessionMetadata;
46use mz_sql::session::user::SUPPORT_USER;
47use mz_sql::session::vars::{CLUSTER, OwnedVarInput, SystemVars, Var};
48use mz_sql_parser::ast::display::AstDisplay;
49use mz_sql_parser::ast::{InsertStatement, StatementKind};
50use mz_sql_parser::parser::{ParserStatementError, StatementParseResult};
51use prometheus::Histogram;
52use serde_json::json;
53use tokio::sync::{mpsc, oneshot};
54use tracing::{debug, error};
55use uuid::Uuid;
56
57use crate::catalog::Catalog;
58use crate::command::{
59    CatalogDump, CatalogSnapshot, Command, CopyFromStdinWriter, ExecuteResponse, Response,
60    SASLChallengeResponse, SASLVerifyProofResponse, SuperuserAttribute,
61};
62use crate::config::{ScopedParameters, ScopedParametersScope, SystemParameterFrontend};
63use crate::coord::read_then_write::DependencyPolicy;
64use crate::coord::{Coordinator, ExecuteContextGuard};
65use crate::error::AdapterError;
66use crate::frontend_read_then_write::{
67    WriteAttemptState, WriteCancellation, contains_mz_now, validate_selection_dependencies,
68};
69use crate::metrics::Metrics;
70use crate::notice::ExecutionTimeKind;
71use crate::optimize::dataflows::{EvalTime, ExprPrepOneShot};
72use crate::optimize::{self, Optimize, OptimizerError};
73use crate::peek_client::{CoordinatorClient, ExecutionLogging, PeekCancelSafety, TakeOver};
74use crate::session::{
75    EndTransactionAction, PreparedStatement, Session, SessionConfig, StateRevision, TransactionId,
76    TransactionStatus,
77};
78use crate::statement_logging::{StatementEndedExecutionReason, StatementExecutionStrategy};
79use crate::telemetry::{self, EventDetails, SegmentClientExt, StatementFailureType};
80use crate::webhook::AppendWebhookResponse;
81use crate::{
82    AdapterNotice, AppendWebhookError, ExecutionTime, PeekClient, PeekResponseUnary,
83    StartupResponse,
84};
85
86/// A handle to a running coordinator.
87///
88/// The coordinator runs on its own thread. Dropping the handle will wait for
89/// the coordinator's thread to exit, which will only occur after all
90/// outstanding [`Client`]s for the coordinator have dropped.
91pub struct Handle {
92    pub(crate) session_id: Uuid,
93    pub(crate) start_instant: Instant,
94    pub(crate) _thread: JoinOnDropHandle<()>,
95}
96
97impl Handle {
98    /// Returns the session ID associated with this coordinator.
99    ///
100    /// The session ID is generated on coordinator boot. It lasts for the
101    /// lifetime of the coordinator. Restarting the coordinator will result
102    /// in a new session ID.
103    pub fn session_id(&self) -> Uuid {
104        self.session_id
105    }
106
107    /// Returns the instant at which the coordinator booted.
108    pub fn start_instant(&self) -> Instant {
109        self.start_instant
110    }
111}
112
113/// A coordinator client.
114///
115/// A coordinator client is a simple handle to a communication channel with the
116/// coordinator. It can be cheaply cloned.
117///
118/// Clients keep the coordinator alive. The coordinator will not exit until all
119/// outstanding clients have dropped.
120#[derive(Debug, Clone)]
121pub struct Client {
122    build_info: &'static BuildInfo,
123    inner_cmd_tx: mpsc::UnboundedSender<(OpenTelemetryContext, Command)>,
124    id_alloc: IdAllocator<IdAllocatorInnerBitSet>,
125    now: NowFn,
126    metrics: Metrics,
127    environment_id: EnvironmentId,
128    segment_client: Option<mz_segment::Client>,
129}
130
131impl Client {
132    pub(crate) fn new(
133        build_info: &'static BuildInfo,
134        cmd_tx: mpsc::UnboundedSender<(OpenTelemetryContext, Command)>,
135        metrics: Metrics,
136        now: NowFn,
137        environment_id: EnvironmentId,
138        segment_client: Option<mz_segment::Client>,
139    ) -> Client {
140        // Connection ids are 32 bits and have 3 parts.
141        // 1. MSB bit is always 0 because these are interpreted as an i32, and it is possible some
142        //    driver will not handle a negative id since postgres has never produced one because it
143        //    uses process ids.
144        // 2. Next 12 bits are the lower 12 bits of the org id. This allows balancerd to route
145        //    incoming cancel messages to a subset of the environments.
146        // 3. Last 19 bits are random.
147        let env_lower = org_id_conn_bits(&environment_id.organization_id());
148        Client {
149            build_info,
150            inner_cmd_tx: cmd_tx,
151            id_alloc: IdAllocator::new(1, MAX_ORG_ID, env_lower),
152            now,
153            metrics,
154            environment_id,
155            segment_client,
156        }
157    }
158
159    /// Allocates a client for an incoming connection.
160    pub fn new_conn_id(&self) -> Result<ConnectionId, AdapterError> {
161        self.id_alloc.alloc().ok_or(AdapterError::IdExhaustionError)
162    }
163
164    /// Creates a new session associated with this client for the given user.
165    ///
166    /// It is the caller's responsibility to have authenticated the user.
167    /// We pass in an Authenticated marker as a guardrail to ensure the
168    /// user has authenticated with an authenticator before creating a session.
169    pub fn new_session(&self, config: SessionConfig, _authenticated: Authenticated) -> Session {
170        // We use the system clock to determine when a session connected to Materialize. This is not
171        // intended to be 100% accurate and correct, so we don't burden the timestamp oracle with
172        // generating a more correct timestamp.
173        Session::new(self.build_info, config, self.metrics().session_metrics())
174    }
175
176    /// Used by [mz_auth::AuthenticatorKind::Password]
177    /// to verify the provided user's password against the
178    /// stored credentials in the catalog.
179    pub async fn authenticate(
180        &self,
181        user: &String,
182        password: &Password,
183    ) -> Result<Authenticated, AdapterError> {
184        let (tx, rx) = oneshot::channel();
185        self.send(Command::AuthenticatePassword {
186            role_name: user.to_string(),
187            password: Some(password.clone()),
188            tx,
189        });
190        rx.await.expect("sender dropped")?;
191        Ok(Authenticated)
192    }
193
194    /// Used by [mz_auth::AuthenticatorKind::Sasl] for SASL-SCRAM authentication.
195    /// This is used prior to [Client::verify_sasl_proof].
196    pub async fn generate_sasl_challenge(
197        &self,
198        user: &String,
199        client_nonce: &String,
200    ) -> Result<SASLChallengeResponse, AdapterError> {
201        let (tx, rx) = oneshot::channel();
202        self.send(Command::AuthenticateGetSASLChallenge {
203            role_name: user.to_string(),
204            nonce: client_nonce.to_string(),
205            tx,
206        });
207        let response = rx.await.expect("sender dropped")?;
208        Ok(response)
209    }
210
211    /// Used by [mz_auth::AuthenticatorKind::Sasl] for SASL-SCRAM authentication.
212    /// This is used after [Client::generate_sasl_challenge].
213    pub async fn verify_sasl_proof(
214        &self,
215        user: &String,
216        proof: &String,
217        nonce: &String,
218        mock_hash: &String,
219    ) -> Result<(SASLVerifyProofResponse, Authenticated), AdapterError> {
220        let (tx, rx) = oneshot::channel();
221        self.send(Command::AuthenticateVerifySASLProof {
222            role_name: user.to_string(),
223            proof: proof.to_string(),
224            auth_message: nonce.to_string(),
225            mock_hash: mock_hash.to_string(),
226            tx,
227        });
228        let response = rx.await.expect("sender dropped")?;
229        Ok((response, Authenticated))
230    }
231
232    /// Checks if a role exists and has the `LOGIN` attribute.
233    pub async fn role_can_login(&self, role_name: &str) -> Result<(), AdapterError> {
234        let (tx, rx) = oneshot::channel();
235        self.send(Command::CheckRoleCanLogin {
236            role_name: role_name.to_string(),
237            tx,
238        });
239        rx.await.expect("sender dropped")
240    }
241
242    /// Upgrades this client to a session client.
243    ///
244    /// A session is a connection that has successfully negotiated parameters,
245    /// like the user. Most coordinator operations are available only after
246    /// upgrading a connection to a session.
247    ///
248    /// Returns a new client that is bound to the session and a response
249    /// containing various details about the startup.
250    #[mz_ore::instrument(level = "debug")]
251    pub async fn startup(&self, session: Session) -> Result<SessionClient, AdapterError> {
252        let user = session.user().clone();
253        let conn_id = session.conn_id().clone();
254        let secret_key = session.secret_key();
255        let uuid = session.uuid();
256        let client_ip = session.client_ip();
257        let application_name = session.application_name().into();
258        let notice_tx = session.retain_notice_transmitter();
259
260        let (tx, rx) = oneshot::channel();
261
262        // ~~SPOOKY ZONE~~
263        //
264        // This guard prevents a race where the startup command finishes, but the Future returned
265        // by this function is concurrently dropped, so we never create a `SessionClient` and thus
266        // never cleanup the initialized Session.
267        //
268        // NOTE: Terminate must only be sent for a successful startup. On a failed startup the
269        // Coordinator never registered the connection, so a Terminate for it would trip the
270        // Coordinator's "unknown connection" assertion. There is also nothing that needs
271        // cleaning up, see the invariant on `Coordinator::handle_startup_inner`.
272        let rx = rx.with_guard(|resp: Result<StartupResponse, _>| {
273            if resp.is_ok() {
274                self.send(Command::Terminate {
275                    conn_id: conn_id.clone(),
276                    tx: None,
277                });
278            }
279        });
280
281        self.send(Command::Startup {
282            tx,
283            user,
284            conn_id: conn_id.clone(),
285            secret_key,
286            uuid,
287            client_ip: client_ip.copied(),
288            application_name,
289            notice_tx,
290        });
291
292        // When startup fails, no need to call terminate (handle_startup does this). Delay creating
293        // the client until after startup to sidestep the panic in its `Drop` implementation.
294        let response = rx.await.expect("sender dropped")?;
295
296        // Create the client as soon as startup succeeds (before any await points) so its `Drop` can
297        // handle termination.
298        // Build the PeekClient with controller handles returned from startup.
299        let StartupResponse {
300            connection_peeks,
301            role_id,
302            write_notify,
303            session_defaults,
304            catalog,
305            storage_collections,
306            transient_id_gen,
307            optimizer_metrics,
308            persist_client,
309            statement_logging_frontend,
310            superuser_attribute,
311            occ_write_semaphore,
312            group_commit_notifier,
313            read_only,
314            frontend_cancel_rx,
315        } = response;
316
317        let peek_client = PeekClient::new(
318            CoordinatorClient::Session(self.clone()),
319            connection_peeks,
320            &catalog,
321            storage_collections,
322            transient_id_gen,
323            optimizer_metrics,
324            persist_client,
325            statement_logging_frontend,
326            occ_write_semaphore,
327            group_commit_notifier,
328            read_only,
329        );
330
331        let mut client = SessionClient {
332            inner: Some(self.clone()),
333            session: Some(session),
334            timeouts: Timeout::new(),
335            environment_id: self.environment_id.clone(),
336            segment_client: self.segment_client.clone(),
337            peek_client,
338            enable_frontend_transaction_completion: false,
339            frontend_cancel_rx,
340        };
341
342        let session = client.session();
343
344        // Apply the superuser attribute to the session's user if
345        // it exists.
346        if let SuperuserAttribute(Some(superuser)) = superuser_attribute {
347            session.apply_internal_user_metadata(InternalUserMetadata { superuser });
348        }
349
350        session.initialize_role_metadata(role_id);
351        let vars_mut = session.vars_mut();
352        for (name, val) in session_defaults {
353            if let Err(err) = vars_mut.set_default(&name, val.borrow()) {
354                // Note: erroring here is unexpected, but we don't want to panic if somehow our
355                // assumptions are wrong.
356                tracing::error!("failed to set peristed default, {err:?}");
357            }
358        }
359        session
360            .vars_mut()
361            .end_transaction(EndTransactionAction::Commit);
362
363        // Stash the future that notifies us of builtin table writes completing, we'll block on
364        // this future before allowing queries from this session against relevant relations.
365        //
366        // Note: We stash the future as opposed to waiting on it here to prevent blocking session
367        // creation on builtin table updates. This improves the latency for session creation and
368        // reduces scheduling load on any dataflows that read from these builtin relations, since
369        // it allows updates to be batched.
370        session.set_builtin_table_updates(write_notify);
371
372        let catalog = catalog.for_session(session);
373
374        let cluster_active = session.vars().cluster().to_string();
375        if session.vars().welcome_message() {
376            let cluster_info = if catalog.resolve_cluster(Some(&cluster_active)).is_err() {
377                format!("{cluster_active} (does not exist)")
378            } else {
379                cluster_active.to_string()
380            };
381
382            // Emit a welcome message, optimized for readability by humans using
383            // interactive tools. If you change the message, make sure that it
384            // formats nicely in both `psql` and the console's SQL shell.
385            session.add_notice(AdapterNotice::Welcome(format!(
386                "connected to Materialize v{}
387  Environment ID: {}
388  Region: {}
389  User: {}
390  Cluster: {}
391  Database: {}
392  {}
393  Session UUID: {}
394
395Issue a SQL query to get started. Need help?
396  View documentation: https://materialize.com/s/docs
397  Join our Slack community: https://materialize.com/s/chat
398    ",
399                session.vars().build_info().semver_version(),
400                self.environment_id,
401                self.environment_id.region(),
402                session.vars().user().name,
403                cluster_info,
404                session.vars().database(),
405                match session.vars().search_path() {
406                    [schema] => format!("Schema: {}", schema),
407                    schemas => format!(
408                        "Search path: {}",
409                        schemas.iter().map(|id| id.to_string()).join(", ")
410                    ),
411                },
412                session.uuid(),
413            )));
414        }
415
416        if session.vars().current_object_missing_warnings() {
417            if catalog.active_database().is_none() {
418                let db = session.vars().database().into();
419                session.add_notice(AdapterNotice::UnknownSessionDatabase(db));
420            }
421        }
422
423        // Users stub their toe on their default cluster not existing, so we provide a notice to
424        // help guide them on what do to.
425        let cluster_var = session
426            .vars()
427            .inspect(CLUSTER.name())
428            .expect("cluster should exist");
429        if session.vars().current_object_missing_warnings()
430            && catalog.resolve_cluster(Some(&cluster_active)).is_err()
431        {
432            let cluster_notice = 'notice: {
433                if cluster_var.inspect_session_value().is_some() {
434                    break 'notice Some(AdapterNotice::DefaultClusterDoesNotExist {
435                        name: cluster_active,
436                        kind: "session",
437                        suggested_action: "Pick an extant cluster with SET CLUSTER = name. Run SHOW CLUSTERS to see available clusters.".into(),
438                    });
439                }
440
441                let role_default = catalog.get_role(catalog.active_role_id());
442                let role_cluster = match role_default.vars().get(CLUSTER.name()) {
443                    Some(OwnedVarInput::Flat(name)) => Some(name),
444                    None => None,
445                    // This is unexpected!
446                    Some(v @ OwnedVarInput::SqlSet(_)) => {
447                        tracing::warn!(?v, "SqlSet found for cluster Role Default");
448                        break 'notice None;
449                    }
450                };
451
452                let alter_role = "with `ALTER ROLE <role> SET cluster TO <cluster>;`";
453                match role_cluster {
454                    // If there is no default, suggest a Role default.
455                    None => Some(AdapterNotice::DefaultClusterDoesNotExist {
456                        name: cluster_active,
457                        kind: "system",
458                        suggested_action: format!(
459                            "Set a default cluster for the current role {alter_role}."
460                        ),
461                    }),
462                    // If the default does not exist, suggest to change it.
463                    Some(_) => Some(AdapterNotice::DefaultClusterDoesNotExist {
464                        name: cluster_active,
465                        kind: "role",
466                        suggested_action: format!(
467                            "Change the default cluster for the current role {alter_role}."
468                        ),
469                    }),
470                }
471            };
472
473            if let Some(notice) = cluster_notice {
474                session.add_notice(notice);
475            }
476        }
477
478        let enable_frontend_transaction_completion =
479            mz_sql::session::vars::ENABLE_FRONTEND_TRANSACTION_COMPLETION
480                .require(catalog.system_vars())
481                .is_ok();
482        client.enable_frontend_transaction_completion = enable_frontend_transaction_completion;
483        Ok(client)
484    }
485
486    /// Cancels the query currently running on the specified connection.
487    pub fn cancel_request(&self, conn_id: ConnectionIdType, secret_key: u32) {
488        self.send(Command::CancelRequest {
489            conn_id,
490            secret_key,
491        });
492    }
493
494    /// Executes a single SQL statement that returns rows as the
495    /// `mz_support` user.
496    pub async fn support_execute_one(
497        &self,
498        sql: &str,
499    ) -> Result<Pin<Box<dyn Stream<Item = PeekResponseUnary> + Send>>, anyhow::Error> {
500        // Connect to the coordinator.
501        let conn_id = self.new_conn_id()?;
502        let session = self.new_session(
503            SessionConfig {
504                conn_id,
505                uuid: Uuid::new_v4(),
506                user: SUPPORT_USER.name.clone(),
507                client_ip: None,
508                external_metadata_rx: None,
509                helm_chart_version: None,
510                authenticator_kind: AuthenticatorKind::None,
511                groups: None,
512            },
513            Authenticated,
514        );
515        let mut session_client = self.startup(session).await?;
516
517        // Parse the SQL statement.
518        let stmts = mz_sql::parse::parse(sql)?;
519        if stmts.len() != 1 {
520            bail!("must supply exactly one query");
521        }
522        let StatementParseResult { ast: stmt, sql } = stmts.into_element();
523
524        const EMPTY_PORTAL: &str = "";
525        session_client.start_transaction(Some(1))?;
526        session_client
527            .declare(EMPTY_PORTAL.into(), stmt, sql.to_string())
528            .await?;
529
530        let execute_result = session_client
531            .execute(EMPTY_PORTAL.into(), futures::future::pending(), None)
532            .await?;
533        match execute_result {
534            (ExecuteResponse::SendingRowsStreaming { mut rows, .. }, _) => {
535                // We have to only drop the session client _after_ we read the
536                // result. Otherwise the peek will get cancelled right when we
537                // drop the session client. So we wrap it up in an extra stream
538                // like this, which owns the client and can return it.
539                let owning_response_stream = async_stream::stream! {
540                    while let Some(rows) = rows.next().await {
541                        yield rows;
542                    }
543                    drop(session_client);
544                };
545                Ok(Box::pin(owning_response_stream))
546            }
547            r => bail!("unsupported response type: {r:?}"),
548        }
549    }
550
551    /// Returns the metrics associated with the adapter layer.
552    pub fn metrics(&self) -> &Metrics {
553        &self.metrics
554    }
555
556    /// The current time according to the [`Client`].
557    pub fn now(&self) -> DateTime<Utc> {
558        to_datetime((self.now)())
559    }
560
561    /// Get a metadata and a channel that can be used to append to a webhook source.
562    pub async fn get_webhook_appender(
563        &self,
564        database: String,
565        schema: String,
566        name: String,
567    ) -> Result<AppendWebhookResponse, AppendWebhookError> {
568        let (tx, rx) = oneshot::channel();
569
570        // Send our request.
571        self.send(Command::GetWebhook {
572            database,
573            schema,
574            name,
575            tx,
576        });
577
578        // Using our one shot channel to get the result, returning an error if the sender dropped.
579        let response = rx
580            .await
581            .map_err(|_| anyhow::anyhow!("failed to receive webhook response"))?;
582
583        response
584    }
585
586    /// Gets the current value of all system variables.
587    pub async fn get_system_vars(&self) -> SystemVars {
588        let (tx, rx) = oneshot::channel();
589        self.send(Command::GetSystemVars { tx });
590        rx.await.expect("coordinator unexpectedly gone")
591    }
592
593    /// Returns a snapshot of the catalog.
594    ///
595    /// Does a Coordinator round-trip. Session-bound callers should
596    /// prefer [`SessionClient::catalog_snapshot`], which serves from the
597    /// session's snapshot cache.
598    pub async fn catalog_snapshot_expensive(&self) -> Arc<Catalog> {
599        let (tx, rx) = oneshot::channel();
600        self.send(Command::CatalogSnapshot { tx });
601        let CatalogSnapshot { catalog } = rx.await.expect("coordinator unexpectedly gone");
602        catalog
603    }
604
605    /// Reconciles the coordinator's scoped feature-flag working copy towards
606    /// `overrides`. Used by the system-parameter sync loop from continuous
607    /// LaunchDarkly evaluation.
608    ///
609    /// `prune_scope` bounds which objects' rows the reconcile may remove (the
610    /// objects `overrides` was evaluated for). The sync loop passes the live
611    /// objects from its snapshot. See
612    /// [`crate::catalog::Op::UpdateScopedSystemParameters`].
613    pub async fn update_scoped_system_parameters(
614        &self,
615        overrides: ScopedParameters,
616        prune_scope: ScopedParametersScope,
617    ) {
618        let (tx, rx) = oneshot::channel();
619        self.send(Command::UpdateScopedSystemParameters {
620            overrides,
621            prune_scope,
622            tx,
623        });
624        let _ = rx.await;
625    }
626
627    /// Installs (or replaces) the shared system-parameter frontend on the
628    /// coordinator, letting the create-cluster / create-replica paths resolve a
629    /// new object's scoped overrides synchronously. Sent by the sync loop each
630    /// time it (re)initializes the frontend. Fire-and-forget.
631    pub fn install_scoped_system_parameter_frontend(&self, frontend: Arc<SystemParameterFrontend>) {
632        self.send(Command::InstallScopedSystemParameterFrontend { frontend });
633    }
634
635    #[instrument(level = "debug")]
636    pub(crate) fn try_send(&self, cmd: Command) -> bool {
637        self.inner_cmd_tx
638            .send((OpenTelemetryContext::obtain(), cmd))
639            .is_ok()
640    }
641
642    #[instrument(level = "debug")]
643    pub(crate) fn send(&self, cmd: Command) {
644        assert!(self.try_send(cmd), "coordinator unexpectedly gone");
645    }
646}
647
648/// A coordinator client that is bound to a connection.
649///
650/// See also [`Client`].
651pub struct SessionClient {
652    // Invariant: inner may only be `None` after the session has been terminated.
653    // Once the session is terminated, no communication to the Coordinator
654    // should be attempted.
655    inner: Option<Client>,
656    // Invariant: session may only be `None` during a method call. Every public
657    // method must ensure that `Session` is `Some` before it returns.
658    session: Option<Session>,
659    timeouts: Timeout,
660    segment_client: Option<mz_segment::Client>,
661    environment_id: EnvironmentId,
662    /// Client for frontend peek sequencing; populated at connection startup.
663    peek_client: PeekClient,
664    enable_frontend_transaction_completion: bool,
665    frontend_cancel_rx: tokio::sync::watch::Receiver<()>,
666}
667
668impl SessionClient {
669    /// Parses a SQL expression, reporting failures as a telemetry event if
670    /// possible.
671    pub fn parse<'a>(
672        &self,
673        sql: &'a str,
674    ) -> Result<Result<Vec<StatementParseResult<'a>>, ParserStatementError>, String> {
675        match mz_sql::parse::parse_with_limit(sql) {
676            Ok(Err(e)) => {
677                self.track_statement_parse_failure(&e);
678                Ok(Err(e))
679            }
680            r => r,
681        }
682    }
683
684    fn track_statement_parse_failure(&self, parse_error: &ParserStatementError) {
685        let session = self.session.as_ref().expect("session invariant violated");
686        let Some(user_id) = session.user().external_metadata.as_ref().map(|m| m.user_id) else {
687            return;
688        };
689        let Some(segment_client) = &self.segment_client else {
690            return;
691        };
692        let Some(statement_kind) = parse_error.statement else {
693            return;
694        };
695        let Some((action, object_type)) = telemetry::analyze_audited_statement(statement_kind)
696        else {
697            return;
698        };
699        let event_type = StatementFailureType::ParseFailure;
700        let event_name = format!(
701            "{} {} {}",
702            object_type.as_title_case(),
703            action.as_title_case(),
704            event_type.as_title_case(),
705        );
706        segment_client.environment_track(
707            &self.environment_id,
708            event_name,
709            json!({
710                "statement_kind": statement_kind,
711                "error": &parse_error.error,
712            }),
713            EventDetails {
714                user_id: Some(user_id),
715                application_name: Some(session.application_name()),
716                ..Default::default()
717            },
718        );
719    }
720
721    // Verify and return the named prepared statement. We need to verify each use
722    // to make sure the prepared statement is still safe to use.
723    pub async fn get_prepared_statement(
724        &mut self,
725        name: &str,
726    ) -> Result<&PreparedStatement, AdapterError> {
727        let catalog = self.catalog_snapshot("get_prepared_statement").await;
728        Coordinator::verify_prepared_statement(&catalog, self.session(), name)?;
729        Ok(self
730            .session()
731            .get_prepared_statement_unverified(name)
732            .expect("must exist"))
733    }
734
735    /// Saves the parsed statement as a prepared statement.
736    ///
737    /// The prepared statement is saved in the connection's [`crate::session::Session`]
738    /// under the specified name.
739    pub async fn prepare(
740        &mut self,
741        name: String,
742        stmt: Option<Statement<Raw>>,
743        sql: String,
744        param_types: Vec<Option<SqlScalarType>>,
745    ) -> Result<(), AdapterError> {
746        let catalog = self.catalog_snapshot("prepare").await;
747
748        // Note: This failpoint is used to simulate a request outliving the external connection
749        // that made it.
750        let mut async_pause = false;
751        (|| {
752            fail::fail_point!("async_prepare", |val| {
753                async_pause = val.map_or(false, |val| val.parse().unwrap_or(false))
754            });
755        })();
756        if async_pause {
757            tokio::time::sleep(Duration::from_secs(1)).await;
758        };
759
760        let desc = Coordinator::describe(&catalog, self.session(), stmt.clone(), param_types)?;
761        let now = self.now();
762        let state_revision = StateRevision {
763            catalog_revision: catalog.transient_revision(),
764            session_state_revision: self.session().state_revision(),
765        };
766        self.session()
767            .set_prepared_statement(name, stmt, sql, desc, state_revision, now);
768        Ok(())
769    }
770
771    /// Binds a statement to a portal.
772    #[mz_ore::instrument(level = "debug")]
773    pub async fn declare(
774        &mut self,
775        name: String,
776        stmt: Statement<Raw>,
777        sql: String,
778    ) -> Result<(), AdapterError> {
779        let catalog = self.catalog_snapshot("declare").await;
780        let param_types = vec![];
781        let desc =
782            Coordinator::describe(&catalog, self.session(), Some(stmt.clone()), param_types)?;
783        let params = vec![];
784        let result_formats = vec![mz_pgwire_common::Format::Text; desc.arity()];
785        let now = self.now();
786        let logging = self.session().mint_logging(sql, Some(&stmt), now);
787        let state_revision = StateRevision {
788            catalog_revision: catalog.transient_revision(),
789            session_state_revision: self.session().state_revision(),
790        };
791        self.session().set_portal(
792            name,
793            desc,
794            Some(stmt),
795            logging,
796            params,
797            result_formats,
798            state_revision,
799        )?;
800        Ok(())
801    }
802
803    /// Executes a previously-bound portal.
804    ///
805    /// Note: the provided `cancel_future` must be cancel-safe as it's polled in a `select!` loop.
806    ///
807    /// `outer_ctx_extra` is Some when we are executing as part of an outer statement, e.g., a FETCH
808    /// triggering the execution of the underlying query.
809    #[mz_ore::instrument(level = "debug")]
810    pub async fn execute(
811        &mut self,
812        portal_name: String,
813        cancel_future: impl Future<Output = std::io::Error> + Send,
814        outer_ctx_extra: Option<ExecuteContextGuard>,
815    ) -> Result<(ExecuteResponse, Instant), AdapterError> {
816        let execute_started = Instant::now();
817        self.frontend_cancel_rx.borrow_and_update();
818        let cancel_future = cancel_future.map(|_| ()).shared();
819
820        // Owning the end-of-execution obligation in this frame is what lets
821        // cancellation report an error: the inner future can be dropped without
822        // the obligation going with it. See `ExecutionLogging`.
823        let mut logging = ExecutionLogging::adopt(outer_ctx_extra, &self.peek_client);
824
825        let result = self
826            .execute_attempts(portal_name, &mut logging, cancel_future)
827            .await;
828
829        // The statement may have changed session state that the descriptions of prepared
830        // statements and portals depend on, such as `search_path`.
831        self.session().advance_state_revision();
832
833        logging.retire(&result);
834
835        result.map(|response| (response, execute_started))
836    }
837
838    /// Runs the execution paths in order of preference: frontend peek
839    /// sequencing, frontend read-then-write sequencing, and finally the
840    /// coordinator via `Command::Execute`.
841    async fn execute_attempts(
842        &mut self,
843        portal_name: String,
844        logging: &mut ExecutionLogging,
845        cancel_future: impl Future<Output = ()> + Send + Clone,
846    ) -> Result<ExecuteResponse, AdapterError> {
847        // Unroll SQL `EXECUTE <prepared> (...)` so the inner statement
848        // flows through `try_peek` /
849        // `try_read_then_write` below, rather than being
850        // re-dispatched via `Command::Execute` from the coordinator's
851        // `Plan::Execute` handler. Without this, a prepared statement
852        // would route differently from the same statement issued
853        // directly.
854        //
855        // On a successful unroll, `unroll_sql_execute` also takes over
856        // statement logging on the outer portal, so that
857        // `mz_statement_execution_history` records `EXECUTE foo (...)`
858        // rather than the inner SQL.
859        let portal_name = self.unroll_sql_execute(portal_name, logging).await?;
860
861        // Attempt peek sequencing in the session task.
862        // If unsupported, fall back to the Coordinator path.
863        let peek_result = self
864            .try_peek(&portal_name, logging, cancel_future.clone())
865            .await?;
866        if let Some(resp) = peek_result {
867            debug!("frontend peek succeeded");
868            return Ok(resp);
869        }
870        debug!("frontend peek did not happen, trying frontend read-then-write");
871
872        // Attempt read-then-write sequencing in the session task.
873        let rtw_result = self
874            .try_read_then_write_with_cancel(&portal_name, logging, cancel_future.clone())
875            .await?;
876        if let Some(resp) = rtw_result {
877            debug!("frontend read-then-write succeeded");
878            return Ok(resp);
879        }
880        debug!("frontend read-then-write did not happen, falling back to `Command::Execute`");
881
882        // No frontend path took the statement over, so the coordinator retires
883        // whatever entry we hold, or begins its own if we hold none.
884        let outer_ctx_extra = logging.release();
885        self.send_with_cancel(
886            |tx, session| Command::Execute {
887                portal_name,
888                session,
889                tx,
890                outer_ctx_extra,
891            },
892            cancel_future,
893        )
894        .await
895    }
896
897    /// If the named portal binds a SQL `EXECUTE <prepared>`, resolve the
898    /// prepared statement, install a fresh portal for the inner statement
899    /// (carrying the EXECUTE's actual parameter values), and return that
900    /// portal's name so the caller can run `try_peek` /
901    /// `try_read_then_write` against it.
902    ///
903    /// Only ever unrolls one level: the parser rejects
904    /// `PREPARE foo AS EXECUTE bar` (matching Postgres), so the inner
905    /// statement is guaranteed not to be another `EXECUTE`. A failsafe below
906    /// surfaces an internal error if that invariant is ever violated.
907    ///
908    /// When the portal does not bind an `EXECUTE`, the common case, returns the
909    /// original portal name, costing only a portal lookup.
910    async fn unroll_sql_execute(
911        &mut self,
912        portal_name: String,
913        logging: &mut ExecutionLogging,
914    ) -> Result<String, AdapterError> {
915        let (stmt, params, outer_logging, outer_lifecycle_timestamps) = {
916            let session = self.session.as_ref().expect("SessionClient invariant");
917            let portal = match session.get_portal_unverified(&portal_name) {
918                Some(p) => p,
919                // No portal: let `try_peek` /
920                // `try_read_then_write` surface the
921                // standard "missing portal" error.
922                None => return Ok(portal_name),
923            };
924            match &portal.stmt {
925                Some(stmt) => (
926                    Arc::clone(stmt),
927                    portal.parameters.clone(),
928                    Arc::clone(&portal.logging),
929                    portal.lifecycle_timestamps.clone(),
930                ),
931                None => return Ok(portal_name),
932            }
933        };
934
935        // Only EXECUTE statements need unrolling. Bail out before taking a
936        // catalog snapshot in the (overwhelmingly common) non-EXECUTE case.
937        if !matches!(&*stmt, Statement::Execute(_)) {
938            return Ok(portal_name);
939        }
940
941        let catalog = self.catalog_snapshot("unroll_sql_execute").await;
942
943        // Validate the outer EXECUTE portal against the (possibly newer)
944        // catalog: ensures the recorded portal description still matches
945        // what describing the EXECUTE would produce now.
946        {
947            let session = self.session.as_mut().expect("SessionClient invariant");
948            Coordinator::verify_portal(&catalog, session, &portal_name)?;
949        }
950
951        // Take over the EXECUTE itself, so that a planning error below produces
952        // an errored end-event in `mz_statement_execution_history` rather than
953        // no entry at all. We pass the *outer* portal's `logging` and
954        // pgwire-bound `params` so the recorded entry shows the user-visible
955        // `EXECUTE foo (...)`, not the inner SQL. The inner statement gets its
956        // own `query_total` increment when a frontend path takes it over, or,
957        // on bailout, in the coordinator's `handle_execute`.
958        logging.take_over(
959            &self.peek_client,
960            self.session.as_mut().expect("SessionClient invariant"),
961            Some(&stmt),
962            &params,
963            &outer_logging,
964            &catalog,
965            outer_lifecycle_timestamps,
966            TakeOver::UnrolledExecute,
967        );
968
969        self.install_inner_portal_for_execute(&catalog, &stmt, &params)
970    }
971
972    /// Helper for [`Self::unroll_sql_execute`]: plans the outer
973    /// `Statement::Execute`, verifies the referenced prepared statement, and
974    /// installs a fresh portal carrying the inner statement plus the
975    /// EXECUTE's bound parameter values. Returns the new portal's name.
976    fn install_inner_portal_for_execute(
977        &mut self,
978        catalog: &Arc<Catalog>,
979        stmt: &Arc<Statement<Raw>>,
980        params: &mz_sql::plan::Params,
981    ) -> Result<String, AdapterError> {
982        use mz_sql::plan::Plan;
983
984        let execute_plan = {
985            let session = self.session.as_mut().expect("SessionClient invariant");
986            let conn_catalog = catalog.for_session(session);
987            let (resolved_stmt, resolved_ids) =
988                mz_sql::names::resolve(&conn_catalog, (**stmt).clone())?;
989            let pcx = session.pcx();
990            let (plan, _sql_impl_ids) = mz_sql::plan::plan(
991                Some(pcx),
992                &conn_catalog,
993                resolved_stmt,
994                params,
995                &resolved_ids,
996            )?;
997            match plan {
998                Plan::Execute(plan) => plan,
999                other => {
1000                    // Planning a `Statement::Execute` must yield
1001                    // `Plan::Execute`. If it doesn't, the planner
1002                    // contract is broken.
1003                    return Err(AdapterError::Internal(format!(
1004                        "planning Statement::Execute yielded unexpected plan: {:?}",
1005                        mz_sql::plan::PlanKind::from(&other),
1006                    )));
1007                }
1008            }
1009        };
1010
1011        // Verify and install the inner portal. The new portal carries the
1012        // inner prepared statement's `logging`, but the logging slot already
1013        // holds the EXECUTE-level entry, so a frontend path taking the inner
1014        // statement over inherits that entry instead of starting fresh from
1015        // this portal.
1016        let session = self.session.as_mut().expect("SessionClient invariant");
1017        Coordinator::verify_prepared_statement(catalog, session, &execute_plan.name)?;
1018        let ps = session
1019            .get_prepared_statement_unverified(&execute_plan.name)
1020            .expect("verified above");
1021        let inner_stmt = ps.stmt().cloned();
1022        let inner_desc = ps.desc().clone();
1023        let state_revision = ps.state_revision;
1024        let inner_logging = Arc::clone(ps.logging());
1025
1026        // Failsafe: `PREPARE foo AS EXECUTE bar` is rejected by the parser,
1027        // so the resolved inner statement must not be another `EXECUTE`. If
1028        // that ever changes, we'd silently skip frontend sequencing for the
1029        // deeper EXECUTEs. Surface it as an internal error instead.
1030        if let Some(inner) = inner_stmt.as_ref() {
1031            if matches!(inner, Statement::Execute(_)) {
1032                return Err(AdapterError::Internal(format!(
1033                    "nested EXECUTE: prepared statement {} resolves to another EXECUTE; \
1034                     parser should reject `PREPARE ... AS EXECUTE ...`",
1035                    execute_plan.name.quoted(),
1036                )));
1037            }
1038        }
1039
1040        session.create_new_portal(
1041            inner_stmt,
1042            inner_logging,
1043            inner_desc,
1044            execute_plan.params,
1045            Vec::new(),
1046            state_revision,
1047        )
1048    }
1049
1050    fn now(&self) -> EpochMillis {
1051        (self.inner().now)()
1052    }
1053
1054    fn now_datetime(&self) -> DateTime<Utc> {
1055        to_datetime(self.now())
1056    }
1057
1058    /// Starts a transaction based on implicit:
1059    /// - `None`: InTransaction
1060    /// - `Some(1)`: Started
1061    /// - `Some(n > 1)`: InTransactionImplicit
1062    /// - `Some(0)`: no change
1063    pub fn start_transaction(&mut self, implicit: Option<usize>) -> Result<(), AdapterError> {
1064        let now = self.now_datetime();
1065        let session = self.session.as_mut().expect("session invariant violated");
1066        let result = match implicit {
1067            None => session.start_transaction(now, None, None),
1068            Some(stmts) => {
1069                session.start_transaction_implicit(now, stmts);
1070                Ok(())
1071            }
1072        };
1073        result
1074    }
1075
1076    /// Ends a transaction. Even if an error is returned, guarantees that the transaction in the
1077    /// session and Coordinator has cleared its state.
1078    #[instrument(level = "debug")]
1079    pub async fn end_transaction(
1080        &mut self,
1081        action: EndTransactionAction,
1082    ) -> Result<ExecuteResponse, AdapterError> {
1083        if self.enable_frontend_transaction_completion {
1084            if let Some(completion) = self.session().read_only_completion(action) {
1085                return crate::frontend_transaction::complete_read_only_transaction(
1086                    self.session.as_mut().expect("session invariant violated"),
1087                    &mut self.peek_client,
1088                    &mut self.frontend_cancel_rx,
1089                    completion,
1090                )
1091                .await;
1092            }
1093        }
1094        let res = self
1095            .send(|tx, session| Command::Commit {
1096                action,
1097                session,
1098                tx,
1099            })
1100            .await;
1101        // Commit isn't guaranteed to set the session's state to anything specific, so clear it
1102        // here. It's safe to ignore the returned `TransactionStatus` because that doesn't contain
1103        // any data that the Coordinator must act on for correctness.
1104        let _ = self.session().clear_transaction();
1105        res
1106    }
1107
1108    /// Settles a statement whose result is about to be reported. If `commit_implicit_transaction`
1109    /// and the session is in an implicit transaction, commits it first, which clears the session's
1110    /// transaction state, portals included. Returns the parameters the commit reverted, or the
1111    /// commit's error.
1112    ///
1113    /// Committing before the result means that a client sees the statement's success or the
1114    /// commit's failure, never both, as with the last statement of a simple query in PostgreSQL
1115    /// (`exec_simple_query`).
1116    pub async fn settle_statement(
1117        &mut self,
1118        commit_implicit_transaction: bool,
1119    ) -> Result<SettledStatement, AdapterError> {
1120        let mut reverted = BTreeMap::new();
1121        if commit_implicit_transaction && self.session().transaction().is_implicit() {
1122            let response = self.end_transaction(EndTransactionAction::Commit).await?;
1123            if let ExecuteResponse::TransactionCommitted { params } = response {
1124                reverted = params;
1125            }
1126        }
1127        Ok(SettledStatement { reverted })
1128    }
1129
1130    /// Fails a transaction.
1131    pub fn fail_transaction(&mut self) {
1132        let session = self.session.take().expect("session invariant violated");
1133        let session = session.fail_transaction();
1134        self.session = Some(session);
1135    }
1136
1137    /// Fetches the catalog, served from the session-side snapshot cache when
1138    /// the catalog is unchanged since the cached snapshot was taken. See
1139    /// [`PeekClient::catalog_snapshot`].
1140    #[instrument(level = "debug")]
1141    pub async fn catalog_snapshot(&mut self, context: &str) -> Arc<Catalog> {
1142        self.peek_client.catalog_snapshot(context).await
1143    }
1144
1145    /// Reports whether `enable_statement_arrival_logging` is on.
1146    pub async fn statement_arrival_logging_enabled(&mut self) -> bool {
1147        let catalog = self.catalog_snapshot("statement_arrival_logging").await;
1148        catalog.system_config().enable_statement_arrival_logging()
1149    }
1150
1151    /// Reports whether `enable_extended_protocol_implicit_transaction` is on.
1152    pub async fn extended_protocol_implicit_transaction_enabled(&mut self) -> bool {
1153        let catalog = self
1154            .catalog_snapshot("extended_protocol_implicit_transaction")
1155            .await;
1156        catalog
1157            .system_config()
1158            .enable_extended_protocol_implicit_transaction()
1159    }
1160
1161    /// Dumps the catalog to a JSON string.
1162    ///
1163    /// No authorization is performed, so access to this function must be limited to internal
1164    /// servers or superusers.
1165    pub async fn dump_catalog(&mut self) -> Result<CatalogDump, AdapterError> {
1166        let catalog = self.catalog_snapshot("dump_catalog").await;
1167        catalog.dump().map_err(AdapterError::from)
1168    }
1169
1170    /// Checks the catalog for internal consistency, returning a JSON object describing the
1171    /// inconsistencies, if there are any.
1172    ///
1173    /// No authorization is performed, so access to this function must be limited to internal
1174    /// servers or superusers.
1175    pub async fn check_catalog(&mut self) -> Result<(), serde_json::Value> {
1176        let catalog = self.catalog_snapshot("check_catalog").await;
1177        catalog.check_consistency()
1178    }
1179
1180    /// Checks the coordinator for internal consistency, returning a JSON object describing the
1181    /// inconsistencies, if there are any. This is a superset of checks that check_catalog performs,
1182    ///
1183    /// No authorization is performed, so access to this function must be limited to internal
1184    /// servers or superusers.
1185    pub async fn check_coordinator(&self) -> Result<(), serde_json::Value> {
1186        self.send_without_session(|tx| Command::CheckConsistency { tx })
1187            .await
1188            .map_err(|inconsistencies| {
1189                serde_json::to_value(inconsistencies).unwrap_or_else(|_| {
1190                    serde_json::Value::String("failed to serialize inconsistencies".to_string())
1191                })
1192            })
1193    }
1194
1195    pub async fn dump_coordinator_state(&self) -> Result<serde_json::Value, anyhow::Error> {
1196        self.send_without_session(|tx| Command::Dump { tx }).await
1197    }
1198
1199    /// Tells the coordinator a statement has finished execution, in the cases
1200    /// where we have no other reason to communicate with the coordinator.
1201    pub fn retire_execute(
1202        &self,
1203        guard: ExecuteContextGuard,
1204        reason: StatementEndedExecutionReason,
1205    ) {
1206        if !guard.is_trivial() {
1207            let data = guard.defuse();
1208            let cmd = Command::RetireExecute { data, reason };
1209            self.inner().send(cmd);
1210        }
1211    }
1212
1213    /// Sets up a streaming COPY FROM STDIN operation.
1214    ///
1215    /// Sends a command to the coordinator to create a background batch
1216    /// builder task. Returns a [`CopyFromStdinWriter`] that pgwire uses
1217    /// to stream decoded rows.
1218    pub async fn start_copy_from_stdin(
1219        &mut self,
1220        target_id: CatalogItemId,
1221        target_name: String,
1222        columns: Vec<ColumnIndex>,
1223        row_desc: mz_repr::RelationDesc,
1224        params: mz_pgcopy::CopyFormatParams<'static>,
1225    ) -> Result<CopyFromStdinWriter, AdapterError> {
1226        self.send(|tx, session| Command::StartCopyFromStdin {
1227            target_id,
1228            target_name,
1229            columns,
1230            row_desc,
1231            params,
1232            session,
1233            tx,
1234        })
1235        .await
1236    }
1237
1238    /// Commits staged COPY FROM STDIN batches to a table.
1239    ///
1240    /// Adds the pre-built persist batches to the session's transaction
1241    /// operations. The actual commit happens when the transaction ends.
1242    pub fn stage_copy_from_stdin_batches(
1243        &mut self,
1244        target_id: CatalogItemId,
1245        batches: Vec<mz_persist_client::batch::ProtoBatch>,
1246    ) -> Result<(), AdapterError> {
1247        use crate::session::{TransactionOps, WriteOp};
1248        use mz_storage_client::client::TableData;
1249
1250        self.session()
1251            .add_transaction_ops(TransactionOps::Writes(vec![WriteOp {
1252                id: target_id,
1253                rows: TableData::Batches(batches.into()),
1254            }]))?;
1255        Ok(())
1256    }
1257
1258    /// Gets the current value of all system variables.
1259    pub async fn get_system_vars(&self) -> SystemVars {
1260        self.inner().get_system_vars().await
1261    }
1262
1263    /// Updates the specified system variables to the specified values.
1264    pub async fn set_system_vars(
1265        &mut self,
1266        vars: BTreeMap<String, String>,
1267    ) -> Result<(), AdapterError> {
1268        let conn_id = self.session().conn_id().clone();
1269        self.send_without_session(|tx| Command::SetSystemVars { vars, conn_id, tx })
1270            .await
1271    }
1272
1273    /// Injects audit events into the catalog via the coordinator.
1274    ///
1275    /// No authorization is performed, so access to this function must be limited to internal
1276    /// servers or superusers.
1277    pub async fn inject_audit_events(
1278        &mut self,
1279        events: Vec<crate::catalog::InjectedAuditEvent>,
1280    ) -> Result<(), AdapterError> {
1281        let conn_id = self.session().conn_id().clone();
1282        self.send_without_session(|tx| Command::InjectAuditEvents {
1283            events,
1284            conn_id,
1285            tx,
1286        })
1287        .await
1288    }
1289
1290    /// Terminates the client session.
1291    pub async fn terminate(&mut self) {
1292        let conn_id = self.session().conn_id().clone();
1293        let res = self
1294            .send_without_session(|tx| Command::Terminate {
1295                conn_id,
1296                tx: Some(tx),
1297            })
1298            .await;
1299        if let Err(e) = res {
1300            // Nothing we can do to handle a failed terminate so we just log and ignore it.
1301            error!("Unable to terminate session: {e:?}");
1302        }
1303        // Prevent any communication with Coordinator after session is terminated.
1304        self.inner = None;
1305    }
1306
1307    /// Returns a mutable reference to the session bound to this client.
1308    pub fn session(&mut self) -> &mut Session {
1309        self.session.as_mut().expect("session invariant violated")
1310    }
1311
1312    /// Returns a reference to the inner client.
1313    pub fn inner(&self) -> &Client {
1314        self.inner.as_ref().expect("inner invariant violated")
1315    }
1316
1317    async fn send_without_session<T, F>(&self, f: F) -> T
1318    where
1319        F: FnOnce(oneshot::Sender<T>) -> Command,
1320    {
1321        let (tx, rx) = oneshot::channel();
1322        self.inner().send(f(tx));
1323        rx.await.expect("sender dropped")
1324    }
1325
1326    #[instrument(level = "debug")]
1327    async fn send<T, F>(&mut self, f: F) -> Result<T, AdapterError>
1328    where
1329        F: FnOnce(oneshot::Sender<Response<T>>, Session) -> Command,
1330    {
1331        self.send_with_cancel(f, futures::future::pending()).await
1332    }
1333
1334    /// Send a [`Command`] to the Coordinator, with the ability to cancel the command.
1335    ///
1336    /// Note: the provided `cancel_future` must be cancel-safe as it's polled in a `select!` loop.
1337    #[instrument(level = "debug")]
1338    async fn send_with_cancel<T, F>(
1339        &mut self,
1340        f: F,
1341        cancel_future: impl Future<Output = ()> + Send,
1342    ) -> Result<T, AdapterError>
1343    where
1344        F: FnOnce(oneshot::Sender<Response<T>>, Session) -> Command,
1345    {
1346        let session = self.session.take().expect("session invariant violated");
1347        let mut typ = None;
1348        let application_name = session.application_name();
1349        let name_hint = ApplicationNameHint::from_str(application_name);
1350        let conn_id = session.conn_id().clone();
1351        let (tx, rx) = oneshot::channel();
1352
1353        // Destructure self so we can hold a mutable reference to the inner client and session at
1354        // the same time.
1355        let Self {
1356            inner: inner_client,
1357            session: client_session,
1358            ..
1359        } = self;
1360
1361        // TODO(parkmycar): Leaking this invariant here doesn't feel great, but calling
1362        // `self.client()` doesn't work because then Rust takes a borrow on the entirity of self.
1363        let inner_client = inner_client.as_ref().expect("inner invariant violated");
1364
1365        // ~~SPOOKY ZONE~~
1366        //
1367        // This guard prevents a race where a `Session` is returned on `rx` but never placed
1368        // back in `self` because the Future returned by this function is concurrently dropped
1369        // with the Coordinator sending a response.
1370        let mut guarded_rx = rx.with_guard(|response: Response<_>| {
1371            *client_session = Some(response.session);
1372        });
1373
1374        inner_client.send({
1375            let cmd = f(tx, session);
1376            // Measure the success and error rate of certain commands:
1377            // - declare reports success of SQL statement planning
1378            // - execute reports success of dataflow execution
1379            match cmd {
1380                Command::Execute { .. } => typ = Some("execute"),
1381                Command::GetWebhook { .. } => typ = Some("webhook"),
1382                Command::StartCopyFromStdin { .. }
1383                | Command::Startup { .. }
1384                | Command::AuthenticatePassword { .. }
1385                | Command::AuthenticateGetSASLChallenge { .. }
1386                | Command::AuthenticateVerifySASLProof { .. }
1387                | Command::CheckRoleCanLogin { .. }
1388                | Command::CatalogSnapshot { .. }
1389                | Command::Commit { .. }
1390                | Command::CancelRequest { .. }
1391                | Command::PrivilegedCancelRequest { .. }
1392                | Command::GetSystemVars { .. }
1393                | Command::SetSystemVars { .. }
1394                | Command::UpdateScopedSystemParameters { .. }
1395                | Command::InstallScopedSystemParameterFrontend { .. }
1396                | Command::Terminate { .. }
1397                | Command::RetireExecute { .. }
1398                | Command::CheckConsistency { .. }
1399                | Command::Dump { .. }
1400                | Command::GetComputeInstanceClient { .. }
1401                | Command::GetOracle { .. }
1402                | Command::DetermineRealTimeRecentTimestamp { .. }
1403                | Command::GetTransactionReadHoldsBundle { .. }
1404                | Command::StoreTransactionReadHolds { .. }
1405                | Command::ExecuteSlowPathPeek { .. }
1406                | Command::ExecuteSubscribe { .. }
1407                | Command::CopyToPreflight { .. }
1408                | Command::ExecuteCopyTo { .. }
1409                | Command::ExecuteSideEffectingFunc { .. }
1410                | Command::LookupConnection { .. }
1411                | Command::InstallPeekWatchSets { .. }
1412                | Command::ExplainTimestamp { .. }
1413                | Command::InjectAuditEvents { .. }
1414                | Command::RegisterConnectionCancelWatch { .. }
1415                | Command::CreateInternalSubscribe { .. }
1416                | Command::AttemptWrite { .. }
1417                | Command::DropInternalSubscribe { .. } => {}
1418            };
1419            cmd
1420        });
1421
1422        let mut cancel_future = pin::pin!(cancel_future);
1423        let mut cancelled = false;
1424        loop {
1425            tokio::select! {
1426                res = &mut guarded_rx => {
1427                    // We received a result, so drop our guard to drop our borrows.
1428                    drop(guarded_rx);
1429
1430                    let res = res.expect("sender dropped");
1431                    let status = res.result.is_ok().then_some("success").unwrap_or("error");
1432                    if let Err(err) = res.result.as_ref() {
1433                        if name_hint.should_trace_errors() {
1434                            tracing::warn!(?err, ?name_hint, "adapter response error");
1435                        }
1436                    }
1437
1438                    if let Some(typ) = typ {
1439                        inner_client
1440                            .metrics
1441                            .commands
1442                            .with_label_values(&[typ, status, name_hint.as_str()])
1443                            .inc();
1444                    }
1445                    *client_session = Some(res.session);
1446                    return res.result;
1447                },
1448                _ = &mut cancel_future, if !cancelled => {
1449                    cancelled = true;
1450                    inner_client.send(Command::PrivilegedCancelRequest {
1451                        conn_id: conn_id.clone(),
1452                    });
1453                }
1454            };
1455        }
1456    }
1457
1458    pub fn add_idle_in_transaction_session_timeout(&mut self) {
1459        let session = self.session();
1460        let timeout_dur = session.vars().idle_in_transaction_session_timeout();
1461        if !timeout_dur.is_zero() {
1462            let timeout_dur = timeout_dur.clone();
1463            if let Some(txn) = session.transaction().inner() {
1464                let txn_id = txn.id.clone();
1465                let timeout = TimeoutType::IdleInTransactionSession(txn_id);
1466                self.timeouts.add_timeout(timeout, timeout_dur);
1467            }
1468        }
1469    }
1470
1471    pub fn remove_idle_in_transaction_session_timeout(&mut self) {
1472        let session = self.session();
1473        if let Some(txn) = session.transaction().inner() {
1474            let txn_id = txn.id.clone();
1475            self.timeouts
1476                .remove_timeout(&TimeoutType::IdleInTransactionSession(txn_id));
1477        }
1478    }
1479
1480    /// # Cancel safety
1481    ///
1482    /// This method is cancel safe. If `recv` is used as the event in a
1483    /// `tokio::select!` statement and some other branch
1484    /// completes first, it is guaranteed that no messages were received on this
1485    /// channel.
1486    pub async fn recv_timeout(&mut self) -> Option<TimeoutType> {
1487        self.timeouts.recv().await
1488    }
1489
1490    /// Attempt to sequence a peek from the session task.
1491    ///
1492    /// Returns `Ok(Some(response))` if we handled the peek, or `Ok(None)` if the statement is
1493    /// not one that the frontend peek sequencing handles, in which case the Coordinator sequences
1494    /// it. If it returns an error, it should be returned to the user.
1495    pub(crate) async fn try_peek(
1496        &mut self,
1497        portal_name: &str,
1498        logging: &mut ExecutionLogging,
1499        connection_closed: impl Future<Output = ()> + Send,
1500    ) -> Result<Option<ExecuteResponse>, AdapterError> {
1501        let connection = Arc::clone(self.peek_client.connection_peeks());
1502        let mut cancellation = self.frontend_cancel_rx.clone();
1503        let cancel_safety = PeekCancelSafety::new();
1504        let session = self.session.as_mut().expect("SessionClient invariant");
1505        let attempt = self
1506            .peek_client
1507            .try_peek(portal_name, session, logging, &cancel_safety);
1508        tokio::pin!(attempt);
1509        let connection_cancel = async move {
1510            if cancellation.changed().await.is_err() {
1511                futures::future::pending::<()>().await;
1512            }
1513        };
1514        tokio::select! {
1515            biased;
1516            _ = connection_cancel => {}
1517            _ = connection_closed => {}
1518            result = &mut attempt => return result,
1519        }
1520        if cancel_safety.can_abort() {
1521            // Invalidate registration's execution epoch before dropping
1522            // the future. Commands already queued for slow peeks carry
1523            // the same lifecycle and cannot issue after this cancellation.
1524            connection.cancel();
1525            Err(AdapterError::Canceled)
1526        } else {
1527            // A non-peek command can already have a side effect. Dropping
1528            // its waiter would lose its definitive response and ownership.
1529            attempt.await
1530        }
1531    }
1532
1533    /// Whether the frontend read-then-write path could take this portal over.
1534    ///
1535    /// The gate is deliberately cheap, a portal lookup, because
1536    /// every statement that reaches `execute_attempts` without being handled by
1537    /// the peek path is tested against it. Everything expensive, including the
1538    /// coordinator round-trip that registers the connection cancel watch, sits
1539    /// behind it.
1540    fn read_then_write_applies(&self, portal_name: &str) -> bool {
1541        let session = self.session.as_ref().expect("SessionClient invariant");
1542        match session.get_portal_unverified(portal_name) {
1543            Some(portal) => portal
1544                .stmt
1545                .as_deref()
1546                .is_some_and(is_read_then_write_statement),
1547            None => false,
1548        }
1549    }
1550
1551    /// Runs frontend read-then-write while reacting to both local/session
1552    /// cancellation and coordinator-issued connection cancellation.
1553    ///
1554    /// Returns `Ok(None)` when the statement is not eligible for this path and
1555    /// the caller must fall back to the coordinator, either because
1556    /// `try_read_then_write` declined it or because this wrapper did.
1557    ///
1558    /// Cancellation and statement timeout are never reported for a write that
1559    /// may have committed. Once a write has been submitted we await its
1560    /// definitive result instead of returning the cancellation.
1561    async fn try_read_then_write_with_cancel(
1562        &mut self,
1563        portal_name: &str,
1564        logging: &mut ExecutionLogging,
1565        cancel_future: impl Future<Output = ()> + Send,
1566    ) -> Result<Option<ExecuteResponse>, AdapterError> {
1567        // Bail out before the cancel-watch registration below, which is a
1568        // synchronous round-trip through the coordinator's command loop. A
1569        // statement this path will not take over must not pay for it, and must
1570        // not add queueing latency for other sessions either.
1571        if !self.read_then_write_applies(portal_name) {
1572            return Ok(None);
1573        }
1574
1575        self.session().require_coordinator_completion();
1576        let conn_id = self.session().conn_id().clone();
1577        let statement_timeout = *self.session().vars().statement_timeout();
1578        let inner_client = self.inner().clone();
1579        let attempt_state = Arc::new(WriteAttemptState::new());
1580
1581        let mut cancel_future = pin::pin!(cancel_future);
1582        let statement_timeout = async move {
1583            if statement_timeout.is_zero() {
1584                futures::future::pending::<()>().await;
1585            } else {
1586                tokio::time::sleep(statement_timeout).await;
1587            }
1588        };
1589        tokio::pin!(statement_timeout);
1590
1591        // Registering installs a fresh channel, so this cannot observe a
1592        // cancellation aimed at an earlier statement. The entry it leaves behind
1593        // is replaced by the next registration and removed when a statement
1594        // reaches the coordinator or the connection's state is cleared, so there
1595        // is nothing to unregister here.
1596        let mut connection_cancel_rx = {
1597            let register =
1598                self.peek_client
1599                    .call_coordinator(|tx| Command::RegisterConnectionCancelWatch {
1600                        conn_id: conn_id.clone(),
1601                        tx,
1602                    });
1603            tokio::pin!(register);
1604            tokio::select! {
1605                rx = &mut register => rx?,
1606                _ = &mut cancel_future => {
1607                    inner_client.try_send(Command::PrivilegedCancelRequest {
1608                        conn_id: conn_id.clone(),
1609                    });
1610                    return Err(AdapterError::Canceled);
1611                }
1612                _ = &mut statement_timeout => {
1613                    inner_client.try_send(Command::PrivilegedCancelRequest {
1614                        conn_id: conn_id.clone(),
1615                    });
1616                    return Err(AdapterError::StatementTimeout);
1617                }
1618            }
1619        };
1620        if *connection_cancel_rx.borrow() {
1621            return Err(AdapterError::Canceled);
1622        }
1623        let connection_cancel = async move {
1624            if connection_cancel_rx.wait_for(|v| *v).await.is_err() {
1625                futures::future::pending::<()>().await;
1626            }
1627        };
1628        tokio::pin!(connection_cancel);
1629
1630        let read_then_write =
1631            self.try_read_then_write(portal_name, logging, Arc::clone(&attempt_state));
1632        tokio::pin!(read_then_write);
1633
1634        let requested = tokio::select! {
1635            response = &mut read_then_write => return response,
1636            _ = &mut cancel_future => WriteCancellation::Canceled,
1637            _ = &mut connection_cancel => WriteCancellation::Canceled,
1638            _ = &mut statement_timeout => WriteCancellation::StatementTimeout,
1639        };
1640
1641        attempt_state.request(requested);
1642        inner_client.try_send(Command::PrivilegedCancelRequest {
1643            conn_id: conn_id.clone(),
1644        });
1645
1646        if !attempt_state.write_submitted() {
1647            return Err(requested.into());
1648        }
1649
1650        // A submitted write can already be durable. Await its definitive result
1651        // rather than reporting cancellation or timeout incorrectly.
1652        read_then_write.await
1653    }
1654
1655    /// Attempt to sequence a read-then-write (DELETE/UPDATE/INSERT INTO ..
1656    /// SELECT .. FROM) from the session task.
1657    ///
1658    /// Returns `Ok(Some(response))` if we handled the operation, or `Ok(None)`
1659    /// to fall back to the Coordinator's sequencing. If it returns an error, it
1660    /// should be returned to the user.
1661    async fn try_read_then_write(
1662        &mut self,
1663        portal_name: &str,
1664        logging: &mut ExecutionLogging,
1665        attempt_state: Arc<WriteAttemptState>,
1666    ) -> Result<Option<ExecuteResponse>, AdapterError> {
1667        let catalog = self.catalog_snapshot("try_read_then_write").await;
1668
1669        let stmt = {
1670            let session = self.session.as_ref().expect("SessionClient invariant");
1671            let portal = match session.get_portal_unverified(portal_name) {
1672                Some(portal) => portal,
1673                None => return Ok(None), // Portal doesn't exist, fall back
1674            };
1675            portal.stmt.clone()
1676        };
1677
1678        let stmt = match stmt {
1679            Some(stmt) if is_read_then_write_statement(&stmt) => stmt,
1680            Some(_stmt) => {
1681                return Ok(None);
1682            }
1683            None => {
1684                return Ok(None);
1685            }
1686        };
1687
1688        // Verify and plan against one catalog snapshot. Pairing a stale plan
1689        // with a newer target generation could direct a write incorrectly.
1690        // A failed verification is not logged, mirroring the coordinator: the
1691        // portal is what statement logging draws its record from.
1692        Coordinator::verify_portal(
1693            &catalog,
1694            self.session.as_mut().expect("SessionClient invariant"),
1695            portal_name,
1696        )?;
1697
1698        let (params, logging_info, lifecycle_timestamps) = {
1699            let portal = self
1700                .session
1701                .as_ref()
1702                .expect("SessionClient invariant")
1703                .get_portal_unverified(portal_name)
1704                .expect("verified above");
1705            (
1706                portal.parameters.clone(),
1707                Arc::clone(&portal.logging),
1708                portal.lifecycle_timestamps.clone(),
1709            )
1710        };
1711
1712        // Past this point the coordinator never sees this statement, so every
1713        // exit has to produce an outcome for it. The remaining `Ok(None)`
1714        // bailouts are all above.
1715        logging.take_over(
1716            &self.peek_client,
1717            self.session.as_mut().expect("SessionClient invariant"),
1718            Some(&stmt),
1719            &params,
1720            &logging_info,
1721            &catalog,
1722            lifecycle_timestamps,
1723            TakeOver::StatementToRun,
1724        );
1725
1726        // Mirror the coordinator's transaction-state gate in `handle_execute`:
1727        // in a multi-statement transaction (an implicit batch or an explicit
1728        // block), the only DML allowed is an AST-constant INSERT without
1729        // RETURNING, which joins the transaction's write ops and commits at
1730        // transaction end. All other DML is prohibited because writes on this
1731        // path commit immediately and cannot be rolled back at transaction
1732        // end. `Failed` transactions pass through, pgwire only admits
1733        // COMMIT/ROLLBACK in that state.
1734        //
1735        // An AST-constant source can still plan to a read, so the check on the
1736        // planned selection further down narrows this.
1737        {
1738            let session = self.session.as_ref().expect("SessionClient invariant");
1739            // `Started` does not mean "single statement" on its own. An
1740            // extended-protocol pipeline keeps the transaction `Started` across
1741            // statements until `Sync`, so once it holds write ops this
1742            // statement runs alongside them and belongs with the
1743            // multi-statement cases. Committing here would commit against a
1744            // snapshot that lacks those ops, reordering this statement before
1745            // writes that a later pipeline error would roll back.
1746            let contains_ops = session.transaction().contains_ops();
1747            match session.transaction() {
1748                TransactionStatus::Default | TransactionStatus::Failed(_) => {}
1749                TransactionStatus::Started(_) if !contains_ops => {}
1750                TransactionStatus::Started(_)
1751                | TransactionStatus::InTransactionImplicit(_)
1752                | TransactionStatus::InTransaction(_) => {
1753                    let constant_insert = matches!(
1754                        &*stmt,
1755                        Statement::Insert(InsertStatement {
1756                            source, returning, ..
1757                        }) if returning.is_empty() && ConstantVisitor::insert_source(source)
1758                    );
1759                    if !constant_insert {
1760                        return Err(prohibited_in_transaction(&stmt));
1761                    }
1762                }
1763            }
1764        }
1765
1766        let (plan, target_cluster, resolved_ids, sql_impl_ids) = {
1767            let session = self.session.as_mut().expect("SessionClient invariant");
1768            let conn_catalog = catalog.for_session(session);
1769            let (stmt, resolved_ids) = mz_sql::names::resolve(&conn_catalog, (*stmt).clone())?;
1770            let pcx = session.pcx();
1771            let (plan, sql_impl_ids) =
1772                mz_sql::plan::plan(Some(pcx), &conn_catalog, stmt, &params, &resolved_ids)?;
1773
1774            let target_cluster = match session.transaction().cluster() {
1775                Some(cluster_id) => crate::coord::TargetCluster::Transaction(cluster_id),
1776                None => crate::coord::catalog_serving::auto_run_on_catalog_server(
1777                    &conn_catalog,
1778                    session,
1779                    &plan,
1780                ),
1781            };
1782
1783            (plan, target_cluster, resolved_ids, sql_impl_ids)
1784        };
1785
1786        // Reject mutations in read-only mode (e.g. during 0dt upgrades). Placed
1787        // where the coordinator has it, in `sequence_plan`: after planning, so a
1788        // statement that does not plan reports the planning error, and before
1789        // the cluster and RBAC checks below, which the coordinator also reports
1790        // second. Every sub-path from here on writes (constant INSERT and the
1791        // OCC INSERT/UPDATE/DELETE), so one check covers them all.
1792        if self.peek_client.read_only {
1793            return Err(AdapterError::ReadOnly);
1794        }
1795
1796        // Cluster restrictions and RBAC, mirroring the coordinator's checks
1797        // in sequencer.rs. Resolution may fail if the target cluster doesn't
1798        // exist. That gets reported later (with the correct error) by
1799        // `validate_read_then_write`. For the purposes of these checks we
1800        // treat it as "no cluster known", consistent with the coordinator.
1801        let (target_cluster_id, target_cluster_name) = {
1802            let session = self.session.as_ref().expect("SessionClient invariant");
1803            match catalog.resolve_target_cluster(target_cluster.clone(), session) {
1804                Ok(cluster) => (Some(cluster.id), Some(cluster.name.clone())),
1805                Err(_) => (None, None),
1806            }
1807        };
1808
1809        // Record the cluster before the checks below can fail, so that their
1810        // error rows carry it, as the coordinator's do.
1811        if let (Some(logging_id), Some(cluster_id), Some(cluster_name)) =
1812            (logging.id(), target_cluster_id, target_cluster_name.clone())
1813        {
1814            self.peek_client
1815                .log_set_cluster(logging_id, cluster_id, cluster_name);
1816        }
1817
1818        {
1819            let session = self.session.as_ref().expect("SessionClient invariant");
1820            let conn_catalog = catalog.for_session(session);
1821            if let Some(cluster_name) = &target_cluster_name {
1822                crate::coord::catalog_serving::check_cluster_restrictions(
1823                    cluster_name,
1824                    &conn_catalog,
1825                    &plan,
1826                )?;
1827            }
1828            if let Err(e) = mz_sql::rbac::check_plan(
1829                &conn_catalog,
1830                None,
1831                session,
1832                &plan,
1833                target_cluster_id,
1834                &resolved_ids,
1835                &sql_impl_ids,
1836            ) {
1837                return Err(e.into());
1838            }
1839        }
1840
1841        // Wait for any in-flight startup builtin-table appends that this plan
1842        // depends on. Mirrors the frontend peek sequencing, and is a no-op for
1843        // plans that don't depend on builtin tables.
1844        {
1845            let session = self.session.as_mut().expect("SessionClient invariant");
1846            if let Some(wait_future) =
1847                crate::coord::appends::waiting_on_startup_appends(&catalog, session, &plan)
1848            {
1849                wait_future.await;
1850            }
1851        }
1852
1853        // `allows_writes` is only defined inside a transaction, which is also
1854        // the only place it can be false: outside one the session task opens a
1855        // fresh transaction with no ops. Autocommit statements therefore rely on
1856        // the check in `PeekClient::session_read_then_write` instead.
1857        {
1858            let session = self.session.as_ref().expect("SessionClient invariant");
1859            if session.transaction().is_in_multi_statement_transaction()
1860                && !session.transaction().allows_writes()
1861            {
1862                return Err(AdapterError::ReadOnlyTransaction);
1863            }
1864            if session
1865                .vars()
1866                .transaction_isolation()
1867                .is_bounded_staleness()
1868            {
1869                return Err(AdapterError::BoundedStalenessReadOnly);
1870            }
1871        }
1872
1873        // Handle ReadThenWrite plans or Insert plans.
1874        let rtw_plan = match plan {
1875            Plan::ReadThenWrite(rtw_plan) => rtw_plan,
1876            Plan::Insert(insert_plan) => {
1877                // A constant INSERT without RETURNING is a blind write, handled
1878                // here through the coordinator's `insert_constant` helper, which
1879                // buffers the rows as session write ops.
1880                //
1881                // Deciding that needs HIR lowered to MIR, because a VALUES list
1882                // is planned as a `Wrap` call at the HIR level.
1883                //
1884                // Only take that path when the HIR names no persisted
1885                // collections (no `Get` nodes on tables or MVs). The MIR
1886                // optimizer can fold an MV reference into a literal when the
1887                // MV's plan happens to be constant, but "plan is constant" is
1888                // NOT the same as "content is visible at the current
1889                // oracle_ts". A `REFRESH AT year 30000` MV has a constant plan
1890                // but no durable content until the refresh fires. Folding it
1891                // and blind-writing the literal would skip timestamp selection
1892                // and linearization, producing data that was never observable.
1893                // Preserving the HIR-level `Get` nodes routes the INSERT through
1894                // the RTW path, where timestamp selection handles REFRESH and
1895                // other time-dependent reads correctly.
1896                let has_read_deps = !insert_plan.values.depends_on().is_empty();
1897
1898                if !has_read_deps {
1899                    let optimized_mir = if insert_plan.values.as_const().is_some() {
1900                        // Already constant at HIR level - just lower without optimization
1901                        let expr = insert_plan
1902                            .values
1903                            .clone()
1904                            .lower(catalog.system_config(), None)?;
1905                        mz_expr::OptimizedMirRelationExpr(expr)
1906                    } else {
1907                        // Need to optimize to check if it becomes constant.
1908                        // Use one-shot expression prep so unmaterializable
1909                        // functions like current_user() are resolved before we
1910                        // decide whether this can use the blind-write path.
1911                        let optimizer_config =
1912                            optimize::OptimizerConfig::from(catalog.system_config());
1913                        let session = self.session.as_ref().expect("SessionClient invariant");
1914                        let prep = ExprPrepOneShot {
1915                            logical_time: EvalTime::NotAvailable,
1916                            session,
1917                            catalog_state: catalog.state(),
1918                        };
1919                        let mut optimizer =
1920                            optimize::view::Optimizer::new_with_prep(optimizer_config, None, prep);
1921                        match optimizer.optimize(insert_plan.values.clone()) {
1922                            Ok(expr) => expr,
1923                            Err(OptimizerError::UncallableFunction {
1924                                func: UnmaterializableFunc::MzNow,
1925                                ..
1926                            }) => {
1927                                // Preserve the established user-facing `mz_now()`
1928                                // error by falling back to the RTW validator.
1929                                let expr = insert_plan
1930                                    .values
1931                                    .clone()
1932                                    .lower(catalog.system_config(), None)?;
1933                                mz_expr::OptimizedMirRelationExpr(expr)
1934                            }
1935                            Err(e) => return Err(e.into()),
1936                        }
1937                    };
1938
1939                    let inner_mir = optimized_mir.into_inner();
1940                    if inner_mir.as_const().is_some() && insert_plan.returning.is_empty() {
1941                        let session = self.session.as_mut().expect("SessionClient invariant");
1942                        let result = Coordinator::insert_constant(
1943                            &catalog,
1944                            session,
1945                            insert_plan.id,
1946                            inner_mir,
1947                        );
1948
1949                        return Ok(Some(result?));
1950                    }
1951                }
1952
1953                let desc_arity = match catalog.try_get_entry(&insert_plan.id) {
1954                    Some(table) => {
1955                        let desc = table
1956                            .relation_desc_latest()
1957                            .ok_or_else(|| AdapterError::Internal("table has no desc".into()))?;
1958                        desc.arity()
1959                    }
1960                    None => {
1961                        return Err(AdapterError::Catalog(mz_catalog::memory::error::Error {
1962                            kind: mz_catalog::memory::error::ErrorKind::Sql(
1963                                mz_sql::catalog::CatalogError::UnknownItem(
1964                                    insert_plan.id.to_string(),
1965                                ),
1966                            ),
1967                        }));
1968                    }
1969                };
1970
1971                let finishing = RowSetFinishing {
1972                    order_by: vec![],
1973                    limit: None,
1974                    offset: 0,
1975                    project: (0..desc_arity).collect(),
1976                };
1977
1978                ReadThenWritePlan {
1979                    id: insert_plan.id,
1980                    selection: insert_plan.values,
1981                    finishing,
1982                    assignments: BTreeMap::new(),
1983                    kind: MutationKind::Insert,
1984                    returning: insert_plan.returning,
1985                }
1986            }
1987            _ => {
1988                return Err(AdapterError::Internal(
1989                    "unexpected plan type for mutation".into(),
1990                ));
1991            }
1992        };
1993
1994        // The syntactic predicate for "reads persisted state", see the module
1995        // docs on `session_read_then_write`. Inside a transaction, only a write
1996        // that reads nothing can run on this path.
1997        //
1998        // The AST gate above is not enough to establish this. It admits
1999        // INSERTs whose source is constant in the AST, and such a statement can
2000        // still plan to a selection with `Get` nodes, because SQL-implemented
2001        // builtins (`pg_get_viewdef`, `text` to `reg*` casts, ...) read system
2002        // relations. So decide on the planned selection, and do it before we
2003        // execute a dataflow for a statement we would then refuse.
2004        {
2005            let session = self.session.as_ref().expect("SessionClient invariant");
2006            let in_transaction = session
2007                .transaction()
2008                .may_share_transaction_with_other_statements();
2009            let depends_on = rtw_plan.selection.depends_on();
2010            if in_transaction && !depends_on.is_empty() {
2011                // Report the reasons that hold wherever the statement runs
2012                // before the one that holds only here. A statement carrying
2013                // `mz_now`, or reading a system table, never works anywhere.
2014                // Answering with the transaction state names the one condition
2015                // the caller could remove, which tells them to retry outside a
2016                // transaction and get the same refusal again.
2017                if contains_mz_now(&rtw_plan) {
2018                    return Err(AdapterError::Unsupported(
2019                        "calls to mz_now in write statements",
2020                    ));
2021                }
2022                validate_selection_dependencies(&catalog, &depends_on, DependencyPolicy::UserDml)?;
2023                return Err(prohibited_in_transaction(&stmt));
2024            }
2025        }
2026
2027        let session = self.session.as_mut().expect("SessionClient invariant");
2028        self.peek_client
2029            .session_read_then_write(
2030                session,
2031                rtw_plan,
2032                target_cluster,
2033                &catalog,
2034                logging.id(),
2035                attempt_state,
2036            )
2037            .await
2038            .map(Some)
2039    }
2040}
2041
2042/// Whether a statement is one the frontend read-then-write path sequences.
2043///
2044/// These are the statement kinds that plan to a `ReadThenWrite` or an `Insert`.
2045/// Note that not every one of them ends up on the OCC path: an `INSERT` whose
2046/// source folds to a constant is dispatched as a blind write instead.
2047fn is_read_then_write_statement(stmt: &Statement<Raw>) -> bool {
2048    matches!(
2049        stmt,
2050        Statement::Delete(_) | Statement::Update(_) | Statement::Insert(_)
2051    )
2052}
2053
2054/// Builds the error for DML that cannot run in a transaction block, mirroring
2055/// the coordinator's redaction in `handle_execute`: statements that can carry
2056/// sensitive literals are redacted because the error message is persisted in
2057/// `mz_statement_execution_history`.
2058fn prohibited_in_transaction(stmt: &Statement<Raw>) -> AdapterError {
2059    let op = if StatementKind::from(stmt).is_sensitive() {
2060        stmt.to_ast_string_redacted()
2061    } else {
2062        stmt.to_string()
2063    };
2064    AdapterError::OperationProhibitsTransaction(op)
2065}
2066
2067impl Drop for SessionClient {
2068    fn drop(&mut self) {
2069        // We may not have a session if this client was dropped while awaiting
2070        // a response. In this case, it is the coordinator's responsibility to
2071        // terminate the session.
2072        if let Some(session) = self.session.take() {
2073            // We may not have a connection to the Coordinator if the session was
2074            // prematurely terminated, for example due to a timeout.
2075            if let Some(inner) = &self.inner {
2076                inner.send(Command::Terminate {
2077                    conn_id: session.conn_id().clone(),
2078                    tx: None,
2079                })
2080            }
2081        }
2082    }
2083}
2084
2085/// Renders SQL for statement arrival logging: parsed and displayed with its
2086/// literals redacted, which is the same redaction the statement log applies,
2087/// and capped by [`truncate_sql_for_logging`].
2088/// When the text does not parse or exceeds the statement batch size limit, a
2089/// placeholder with the byte length is returned. Raw text is never returned,
2090/// so a statement that crashes the parser is not captured, an accepted
2091/// limitation.
2092pub fn redact_sql_for_logging(sql: &str) -> String {
2093    match mz_sql_parser::parser::parse_statements_with_limit(sql) {
2094        Ok(Ok(stmts)) => truncate_sql_for_logging(
2095            stmts
2096                .into_iter()
2097                .map(|stmt| stmt.ast.to_ast_string_redacted())
2098                .join("; "),
2099        ),
2100        Ok(Err(_)) => format!("<unparseable ({} bytes)>", sql.len()),
2101        Err(_) => format!("<too large ({} bytes)>", sql.len()),
2102    }
2103}
2104
2105/// The maximum length in bytes of SQL text included in a log line.
2106///
2107/// Loki rejects a log entry larger than 256 KiB and drops it whole. A span's
2108/// fields are repeated in every event logged inside the span, twice when it is
2109/// the innermost span (the JSON format writes both `span` and `spans`), so one
2110/// statement can appear several times in an entry.
2111const MAX_LOGGED_SQL_LEN: usize = 8 * 1024;
2112
2113/// Truncates SQL text to `MAX_LOGGED_SQL_LEN` bytes for a log line, noting
2114/// the original length.
2115pub fn truncate_sql_for_logging(sql: String) -> String {
2116    if sql.len() <= MAX_LOGGED_SQL_LEN {
2117        return sql;
2118    }
2119    let end = sql.floor_char_boundary(MAX_LOGGED_SQL_LEN);
2120    format!("{}... <truncated from {} bytes>", &sql[..end], sql.len())
2121}
2122
2123#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Debug)]
2124pub enum TimeoutType {
2125    IdleInTransactionSession(TransactionId),
2126}
2127
2128impl Display for TimeoutType {
2129    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
2130        match self {
2131            TimeoutType::IdleInTransactionSession(txn_id) => {
2132                writeln!(f, "Idle in transaction session for transaction '{txn_id}'")
2133            }
2134        }
2135    }
2136}
2137
2138impl From<TimeoutType> for AdapterError {
2139    fn from(timeout: TimeoutType) -> Self {
2140        match timeout {
2141            TimeoutType::IdleInTransactionSession(_) => {
2142                AdapterError::IdleInTransactionSessionTimeout
2143            }
2144        }
2145    }
2146}
2147
2148struct Timeout {
2149    tx: mpsc::UnboundedSender<TimeoutType>,
2150    rx: mpsc::UnboundedReceiver<TimeoutType>,
2151    active_timeouts: BTreeMap<TimeoutType, AbortOnDropHandle<()>>,
2152}
2153
2154impl Timeout {
2155    fn new() -> Self {
2156        let (tx, rx) = mpsc::unbounded_channel();
2157        Timeout {
2158            tx,
2159            rx,
2160            active_timeouts: BTreeMap::new(),
2161        }
2162    }
2163
2164    /// # Cancel safety
2165    ///
2166    /// This method is cancel safe. If `recv` is used as the event in a
2167    /// `tokio::select!` statement and some other branch
2168    /// completes first, it is guaranteed that no messages were received on this
2169    /// channel.
2170    ///
2171    /// <https://docs.rs/tokio/latest/tokio/sync/mpsc/struct.UnboundedReceiver.html#cancel-safety>
2172    async fn recv(&mut self) -> Option<TimeoutType> {
2173        self.rx.recv().await
2174    }
2175
2176    fn add_timeout(&mut self, timeout: TimeoutType, duration: Duration) {
2177        let tx = self.tx.clone();
2178        let timeout_key = timeout.clone();
2179        let handle = mz_ore::task::spawn(|| format!("{timeout_key}"), async move {
2180            tokio::time::sleep(duration).await;
2181            let _ = tx.send(timeout);
2182        })
2183        .abort_on_drop();
2184        self.active_timeouts.insert(timeout_key, handle);
2185    }
2186
2187    fn remove_timeout(&mut self, timeout: &TimeoutType) {
2188        self.active_timeouts.remove(timeout);
2189
2190        // Remove the timeout from the rx queue if it exists.
2191        let mut timeouts = Vec::new();
2192        while let Ok(pending_timeout) = self.rx.try_recv() {
2193            if timeout != &pending_timeout {
2194                timeouts.push(pending_timeout);
2195            }
2196        }
2197        for pending_timeout in timeouts {
2198            self.tx.send(pending_timeout).expect("rx is in this struct");
2199        }
2200    }
2201}
2202
2203/// Additions to a statement's result that are known only after any commit that the result waits
2204/// for, such as the session parameters that the commit reverted.
2205#[derive(Debug)]
2206pub struct SettledStatement {
2207    /// Session parameters that committing the statement's implicit transaction reverted, if any,
2208    /// such as a value set with `SET LOCAL`.
2209    pub reverted: BTreeMap<&'static str, String>,
2210}
2211
2212/// A wrapper around a Stream of PeekResponseUnary that records when it sees the
2213/// first row data in the given histogram. It also keeps track of whether we have already observed
2214/// the end of the underlying stream.
2215#[derive(Derivative)]
2216#[derivative(Debug)]
2217pub struct RecordFirstRowStream {
2218    /// The underlying stream of rows.
2219    #[derivative(Debug = "ignore")]
2220    pub rows: Box<dyn Stream<Item = PeekResponseUnary> + Unpin + Send + Sync>,
2221    /// The Instant when execution started.
2222    pub execute_started: Instant,
2223    /// The histogram where the time since `execute_started` will be recorded when we see the first
2224    /// row.
2225    pub time_to_first_row_seconds: Histogram,
2226    /// Whether we've seen any rows.
2227    pub saw_rows: bool,
2228    /// The Instant when we saw the first row.
2229    pub recorded_first_row_instant: Option<Instant>,
2230    /// Whether we have already observed the end of the underlying stream.
2231    pub no_more_rows: bool,
2232    /// Whether the first-to-last-byte metric has already been recorded for this stream.
2233    pub metric_recorded: bool,
2234    execution_time: Option<ExecutionTime>,
2235    execution_time_reported: bool,
2236}
2237
2238impl RecordFirstRowStream {
2239    /// Create a new [`RecordFirstRowStream`]
2240    pub fn new(
2241        rows: Box<dyn Stream<Item = PeekResponseUnary> + Unpin + Send + Sync>,
2242        execute_started: Instant,
2243        client: &SessionClient,
2244        instance_id: Option<ComputeInstanceId>,
2245        strategy: Option<StatementExecutionStrategy>,
2246    ) -> Self {
2247        let histogram = Self::histogram(client, instance_id, strategy);
2248        Self {
2249            rows,
2250            execute_started,
2251            time_to_first_row_seconds: histogram,
2252            saw_rows: false,
2253            recorded_first_row_instant: None,
2254            no_more_rows: false,
2255            metric_recorded: false,
2256            execution_time: None,
2257            execution_time_reported: false,
2258        }
2259    }
2260
2261    fn histogram(
2262        client: &SessionClient,
2263        instance_id: Option<ComputeInstanceId>,
2264        strategy: Option<StatementExecutionStrategy>,
2265    ) -> Histogram {
2266        let session = client.session.as_ref().expect("session invariant");
2267        let isolation_level = *session.vars().transaction_isolation();
2268        let name_hint = ApplicationNameHint::from_str(session.application_name());
2269
2270        client
2271            .inner()
2272            .metrics()
2273            .by_cluster
2274            .time_to_first_row_seconds(instance_id, isolation_level, strategy, name_hint)
2275    }
2276
2277    /// If you want to match [`RecordFirstRowStream`]'s logic but don't need
2278    /// a UnboundedReceiver, you can tell it when to record an observation.
2279    pub fn record(
2280        execute_started: Instant,
2281        client: &SessionClient,
2282        instance_id: Option<ComputeInstanceId>,
2283        strategy: Option<StatementExecutionStrategy>,
2284    ) {
2285        Self::histogram(client, instance_id, strategy)
2286            .observe(execute_started.elapsed().as_secs_f64());
2287    }
2288
2289    pub async fn recv(&mut self) -> Option<PeekResponseUnary> {
2290        let mut msg = self.rows.next().await;
2291        if !self.saw_rows && matches!(msg, Some(PeekResponseUnary::Rows(_))) {
2292            self.saw_rows = true;
2293            self.time_to_first_row_seconds
2294                .observe(self.execute_started.elapsed().as_secs_f64());
2295            self.recorded_first_row_instant = Some(Instant::now());
2296        }
2297        if msg.is_none() {
2298            self.no_more_rows = true;
2299        }
2300        if self.execution_time.is_none() && !self.execution_time_reported {
2301            let kind = match &mut msg {
2302                // An empty batch does not end the interval. A stashed result can start with an
2303                // empty inline batch, and an `OFFSET` can empty whole stashed batches.
2304                Some(PeekResponseUnary::Rows(rows)) => {
2305                    rows.peek().is_some().then_some(ExecutionTimeKind::FirstRow)
2306                }
2307                None => Some(ExecutionTimeKind::EmptyResult),
2308                _ => None,
2309            };
2310            self.execution_time = kind.map(|kind| ExecutionTime {
2311                kind,
2312                elapsed: self.execute_started.elapsed(),
2313            });
2314        }
2315        msg
2316    }
2317
2318    /// Disables execution time notices for an unbounded subscription.
2319    pub fn without_execution_time(mut self) -> Self {
2320        self.execution_time = None;
2321        self.execution_time_reported = true;
2322        self
2323    }
2324
2325    /// Takes the timing on the first execution step only, if a row or EOF was observed.
2326    /// Later steps must not include a client's pause, even if the first step was `FETCH 0`.
2327    pub fn take_execution_time(&mut self) -> Option<ExecutionTime> {
2328        self.execution_time_reported = true;
2329        self.execution_time.take()
2330    }
2331}
2332
2333#[cfg(test)]
2334mod tests {
2335    use super::*;
2336
2337    #[mz_ore::test]
2338    fn truncate_sql_for_logging_caps_length() {
2339        let short = "SELECT 1".to_string();
2340        assert_eq!(truncate_sql_for_logging(short.clone()), short);
2341
2342        let exact = "x".repeat(MAX_LOGGED_SQL_LEN);
2343        assert_eq!(truncate_sql_for_logging(exact.clone()), exact);
2344
2345        // A multi-byte character straddles the cap, so the cut must move back
2346        // to the previous character boundary.
2347        let long = format!(
2348            "{}é{}",
2349            "x".repeat(MAX_LOGGED_SQL_LEN - 1),
2350            "y".repeat(1000)
2351        );
2352        let truncated = truncate_sql_for_logging(long.clone());
2353        assert_eq!(
2354            truncated,
2355            format!(
2356                "{}... <truncated from {} bytes>",
2357                "x".repeat(MAX_LOGGED_SQL_LEN - 1),
2358                long.len()
2359            )
2360        );
2361    }
2362}