Skip to main content

mz_adapter/
statement_logging.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::borrow::Cow;
11use std::collections::{BTreeMap, BTreeSet};
12use std::sync::atomic::Ordering;
13use std::sync::{Arc, Mutex, MutexGuard};
14
15use bytes::BytesMut;
16use mz_catalog::memory::objects::CatalogItem;
17use mz_controller_types::ClusterId;
18use mz_dyncfg::{ConfigSet, ConfigValHandle};
19use mz_ore::cast::{CastFrom, CastInto};
20use mz_ore::now::{EpochMillis, NowFn, epoch_to_uuid_v7, to_datetime};
21use mz_ore::soft_panic_or_log;
22use mz_repr::adt::array::ArrayDimension;
23use mz_repr::adt::timestamp::TimestampLike;
24use mz_repr::{Datum, Diff, GlobalId, Row, RowIterator, RowPacker, Timestamp};
25use mz_sql::ast::display::AstDisplay;
26use mz_sql::ast::{AstInfo, Statement};
27use mz_sql::plan::Params;
28use mz_sql::session::metadata::SessionMetadata;
29use mz_sql::session::vars::SystemVars;
30use mz_sql_parser::ast::{StatementKind, statement_kind_label_value};
31use qcell::QCell;
32use rand::distr::{Bernoulli, Distribution};
33use sha2::{Digest, Sha256};
34use uuid::Uuid;
35
36use crate::catalog::CatalogState;
37use crate::session::{LifecycleTimestamps, Session, TransactionId};
38use crate::{AdapterError, CollectionIdBundle, ExecuteResponse};
39
40#[derive(Clone, Debug)]
41pub enum StatementLifecycleEvent {
42    ExecutionBegan,
43    OptimizationFinished,
44    StorageDependenciesFinished,
45    ComputeDependenciesFinished,
46    ExecutionFinished,
47}
48
49impl StatementLifecycleEvent {
50    pub fn as_str(&self) -> &str {
51        match self {
52            Self::ExecutionBegan => "execution-began",
53            Self::OptimizationFinished => "optimization-finished",
54            Self::StorageDependenciesFinished => "storage-dependencies-finished",
55            Self::ComputeDependenciesFinished => "compute-dependencies-finished",
56            Self::ExecutionFinished => "execution-finished",
57        }
58    }
59}
60
61/// Contains all the information necessary to generate the initial
62/// entry in `mz_statement_execution_history`. We need to keep this
63/// around in order to modify the entry later once the statement finishes executing.
64#[derive(Clone, Debug)]
65pub struct StatementBeganExecutionRecord {
66    pub id: Uuid,
67    pub prepared_statement_id: Uuid,
68    pub sample_rate: f64,
69    pub params: Vec<Option<String>>,
70    pub began_at: EpochMillis,
71    pub cluster_id: Option<ClusterId>,
72    pub cluster_name: Option<String>,
73    pub database_name: String,
74    pub search_path: Vec<String>,
75    pub application_name: String,
76    pub transaction_isolation: String,
77    pub execution_timestamp: Option<EpochMillis>,
78    pub transaction_id: TransactionId,
79    pub transient_index_id: Option<GlobalId>,
80    pub mz_version: String,
81    /// The kind of statement being executed, if known. Used to redact
82    /// `error_message` for kinds that can carry secret material.
83    pub kind: Option<StatementKind>,
84}
85
86#[derive(Clone, Copy, Debug)]
87pub enum StatementExecutionStrategy {
88    /// The statement was executed by spinning up a dataflow.
89    Standard,
90    /// The statement was executed by reading from an existing
91    /// arrangement.
92    FastPath,
93    /// Experimental: The statement was executed by reading from an existing
94    /// persist collection.
95    PersistFastPath,
96    /// The statement was determined to be constant by
97    /// environmentd, and not sent to a cluster.
98    Constant,
99}
100
101impl StatementExecutionStrategy {
102    pub fn name(&self) -> &'static str {
103        match self {
104            Self::Standard => "standard",
105            Self::FastPath => "fast-path",
106            Self::PersistFastPath => "persist-fast-path",
107            Self::Constant => "constant",
108        }
109    }
110}
111
112#[derive(Clone, Debug)]
113pub enum StatementEndedExecutionReason {
114    Success {
115        result_size: Option<u64>,
116        rows_returned: Option<u64>,
117        execution_strategy: Option<StatementExecutionStrategy>,
118    },
119    Canceled,
120    Errored {
121        error: String,
122    },
123    /// Should only be emitted by `impl Drop for ExecuteContextGuard`.
124    /// Code paths that explicitly complete execution should use
125    /// `retire_execute` with `Success`, `Canceled`, or `Errored`.
126    Aborted,
127}
128
129#[derive(Clone, Debug)]
130pub struct StatementEndedExecutionRecord {
131    pub id: Uuid,
132    pub reason: StatementEndedExecutionReason,
133    pub ended_at: EpochMillis,
134}
135
136/// Contains all the information necessary to generate an entry in
137/// `mz_prepared_statement_history`
138#[derive(Clone, Debug)]
139pub(crate) struct StatementPreparedRecord {
140    pub id: Uuid,
141    pub sql_hash: [u8; 32],
142    pub name: String,
143    pub session_id: Uuid,
144    pub prepared_at: EpochMillis,
145    pub kind: Option<StatementKind>,
146}
147
148#[derive(Clone, Debug)]
149pub(crate) struct SessionHistoryEvent {
150    pub id: Uuid,
151    pub connected_at: EpochMillis,
152    pub application_name: String,
153    pub authenticated_user: String,
154}
155
156impl From<&Result<ExecuteResponse, AdapterError>> for StatementEndedExecutionReason {
157    fn from(value: &Result<ExecuteResponse, AdapterError>) -> StatementEndedExecutionReason {
158        match value {
159            Ok(resp) => resp.into(),
160            Err(e) => StatementEndedExecutionReason::Errored {
161                error: e.to_string(),
162            },
163        }
164    }
165}
166
167impl From<&ExecuteResponse> for StatementEndedExecutionReason {
168    fn from(value: &ExecuteResponse) -> StatementEndedExecutionReason {
169        match value {
170            ExecuteResponse::CopyTo { resp, .. } => match resp.as_ref() {
171                // NB [btv]: It's not clear that this combination
172                // can ever actually happen.
173                ExecuteResponse::SendingRowsImmediate { rows, .. } => {
174                    // Note(parkmycar): It potentially feels bad here to iterate over the entire
175                    // iterator _just_ to get the encoded result size. As noted above, it's not
176                    // entirely clear this case ever happens, so the simplicity is worth it.
177                    let result_size: usize = rows.box_clone().map(|row| row.byte_len()).sum();
178                    StatementEndedExecutionReason::Success {
179                        result_size: Some(u64::cast_from(result_size)),
180                        rows_returned: Some(u64::cast_from(rows.count())),
181                        execution_strategy: Some(StatementExecutionStrategy::Constant),
182                    }
183                }
184                ExecuteResponse::SendingRowsStreaming { .. } => {
185                    panic!("SELECTs terminate on peek finalization, not here.")
186                }
187                ExecuteResponse::Subscribing { .. } => {
188                    panic!("SUBSCRIBEs terminate in the protocol layer, not here.")
189                }
190                _ => panic!("Invalid COPY response type"),
191            },
192            ExecuteResponse::CopyFrom { .. } => {
193                panic!("COPY FROMs terminate in the protocol layer, not here.")
194            }
195            ExecuteResponse::Fetch { .. } => {
196                panic!("FETCHes terminate after a follow-up message is sent.")
197            }
198            ExecuteResponse::SendingRowsStreaming { .. } => {
199                panic!("SELECTs terminate on peek finalization, not here.")
200            }
201            ExecuteResponse::Subscribing { .. } => {
202                panic!("SUBSCRIBEs terminate in the protocol layer, not here.")
203            }
204
205            ExecuteResponse::SendingRowsImmediate { rows, .. } => {
206                // Note(parkmycar): It potentially feels bad here to iterate over the entire
207                // iterator _just_ to get the encoded result size, the number of Rows returned here
208                // shouldn't be too large though. An alternative is to pre-compute some of the
209                // result size, but that would require always decoding Rows to handle projecting
210                // away columns, which has a negative impact for much larger response sizes.
211                let result_size: usize = rows.box_clone().map(|row| row.byte_len()).sum();
212                StatementEndedExecutionReason::Success {
213                    result_size: Some(u64::cast_from(result_size)),
214                    rows_returned: Some(u64::cast_from(rows.count())),
215                    execution_strategy: Some(StatementExecutionStrategy::Constant),
216                }
217            }
218
219            ExecuteResponse::AlteredDefaultPrivileges
220            | ExecuteResponse::AlteredObject(_)
221            | ExecuteResponse::AlteredRole
222            | ExecuteResponse::AlteredSystemConfiguration
223            | ExecuteResponse::ClosedCursor
224            | ExecuteResponse::Comment
225            | ExecuteResponse::Copied(_)
226            | ExecuteResponse::CreatedConnection
227            | ExecuteResponse::CreatedDatabase
228            | ExecuteResponse::CreatedSchema
229            | ExecuteResponse::CreatedRole
230            | ExecuteResponse::CreatedCluster
231            | ExecuteResponse::CreatedClusterReplica
232            | ExecuteResponse::CreatedIndex
233            | ExecuteResponse::CreatedIntrospectionSubscribe
234            | ExecuteResponse::CreatedMetricSink
235            | ExecuteResponse::CreatedSecret
236            | ExecuteResponse::CreatedSink
237            | ExecuteResponse::CreatedSource
238            | ExecuteResponse::CreatedTable
239            | ExecuteResponse::CreatedView
240            | ExecuteResponse::CreatedViews
241            | ExecuteResponse::CreatedMaterializedView
242            | ExecuteResponse::CreatedType
243            | ExecuteResponse::CreatedNetworkPolicy
244            | ExecuteResponse::CreatedQueryPolicy
245            | ExecuteResponse::Deallocate { .. }
246            | ExecuteResponse::DeclaredCursor
247            | ExecuteResponse::Deleted(_)
248            | ExecuteResponse::DiscardedTemp
249            | ExecuteResponse::DiscardedAll { .. }
250            | ExecuteResponse::DroppedObject(_)
251            | ExecuteResponse::DroppedOwned
252            | ExecuteResponse::EmptyQuery
253            | ExecuteResponse::GrantedPrivilege
254            | ExecuteResponse::GrantedRole
255            | ExecuteResponse::Inserted(_)
256            | ExecuteResponse::Prepare
257            | ExecuteResponse::Raised
258            | ExecuteResponse::ReassignOwned
259            | ExecuteResponse::RevokedPrivilege
260            | ExecuteResponse::RevokedRole
261            | ExecuteResponse::SetVariable { .. }
262            | ExecuteResponse::StartedTransaction
263            | ExecuteResponse::TransactionCommitted { .. }
264            | ExecuteResponse::TransactionRolledBack { .. }
265            | ExecuteResponse::Updated(_)
266            | ExecuteResponse::ValidatedConnection { .. } => {
267                StatementEndedExecutionReason::Success {
268                    result_size: None,
269                    rows_returned: None,
270                    execution_strategy: None,
271                }
272            }
273        }
274    }
275}
276
277mod sealed {
278    /// A struct that is purposefully private so folks are forced to use the constructor of an
279    /// enum.
280    #[derive(Debug, Copy, Clone)]
281    pub struct Private;
282}
283
284/// Metadata required for logging a prepared statement.
285#[derive(Debug)]
286pub enum PreparedStatementLoggingInfo {
287    /// The statement has already been logged; we don't need to log it
288    /// again if a future execution hits the sampling rate; we merely
289    /// need to reference the corresponding UUID.
290    AlreadyLogged {
291        uuid: Uuid,
292        kind: Option<StatementKind>,
293    },
294    /// The statement has not yet been logged; if a future execution
295    /// hits the sampling rate, we need to log it at that point.
296    StillToLog {
297        /// The SQL text of the statement.
298        sql: String,
299        /// The SQL text of the statement, redacted to follow our data management
300        /// policy
301        redacted_sql: String,
302        /// When the statement was prepared
303        prepared_at: EpochMillis,
304        /// The name with which the statement was prepared
305        name: String,
306        /// The ID of the session that prepared the statement
307        session_id: Uuid,
308        /// Whether we have already recorded this in the "would have logged" metric
309        accounted: bool,
310        /// The top-level kind of the statement (e.g., `Select`), or `None` for an empty statement
311        kind: Option<StatementKind>,
312
313        /// Private type that forces use of the [`PreparedStatementLoggingInfo::still_to_log`]
314        /// constructor.
315        _sealed: sealed::Private,
316    },
317}
318
319impl PreparedStatementLoggingInfo {
320    /// The kind of the prepared statement, if known. Available regardless of
321    /// whether the statement has already been logged.
322    pub fn kind(&self) -> Option<StatementKind> {
323        match self {
324            PreparedStatementLoggingInfo::StillToLog { kind, .. } => *kind,
325            PreparedStatementLoggingInfo::AlreadyLogged { kind, .. } => *kind,
326        }
327    }
328
329    /// Constructor for the [`PreparedStatementLoggingInfo::StillToLog`] variant that ensures SQL
330    /// statements are properly redacted.
331    pub fn still_to_log<A: AstInfo>(
332        raw_sql: String,
333        stmt: Option<&Statement<A>>,
334        prepared_at: EpochMillis,
335        name: String,
336        session_id: Uuid,
337        accounted: bool,
338    ) -> Self {
339        let kind = stmt.map(StatementKind::from);
340        let sql = match kind {
341            // Redact the SQL text of statements that can carry sensitive material:
342            // secret values (`CREATE`/`ALTER SECRET`), or bulk/PII user data
343            // (`INSERT`/`UPDATE`/`EXECUTE`). See `StatementKind::is_sensitive`.
344            Some(kind) if kind.is_sensitive() => {
345                stmt.map(|s| s.to_ast_string_redacted()).unwrap_or_default()
346            }
347            _ => raw_sql,
348        };
349
350        PreparedStatementLoggingInfo::StillToLog {
351            sql,
352            redacted_sql: stmt.map(|s| s.to_ast_string_redacted()).unwrap_or_default(),
353            prepared_at,
354            name,
355            session_id,
356            accounted,
357            kind,
358            _sealed: sealed::Private,
359        }
360    }
361}
362
363#[derive(Copy, Clone, Debug, Ord, Eq, PartialOrd, PartialEq)]
364pub struct StatementLoggingId(pub Uuid);
365
366/// Rows to be written to `mz_prepared_statement_history` and `mz_sql_text`, with the session id.
367#[derive(Debug, Clone)]
368pub struct PreparedStatementEvent {
369    pub prepared_statement: Row,
370    pub sql_text: Row,
371    pub session_id: Uuid,
372}
373
374/// Throttling state for statement logging, shared across frontend tasks and the coordinator.
375#[derive(Debug)]
376pub struct ThrottlingState {
377    /// Inner state protected by a mutex for rate-limiting, because the two inner fields have to be
378    /// manipulated together atomically.
379    /// This mutex is locked once per unsampled query. (There is both sampling and throttling.
380    /// Sampling happens before throttling.) This should be ok for now: Our QPS will not be more
381    /// than 10000s for now, and a mutex should be able to do 100000s of lockings per second, even
382    /// with some contention. If this ever becomes an issue, then we could redesign throttling to be
383    /// per-session/per-tokio-worker-thread.
384    inner: Mutex<ThrottlingStateInner>,
385    /// The number of statements that have been throttled since the last successfully logged
386    /// statement. This is not needed for the throttling decision itself, so it can be a separate
387    /// atomic to allow reading/writing without acquiring the inner mutex.
388    throttled_count: std::sync::atomic::AtomicUsize,
389}
390
391#[derive(Debug)]
392struct ThrottlingStateInner {
393    /// The number of bytes that we are allowed to emit for statement logging without being throttled.
394    /// Increases at a rate of [`mz_sql::session::vars::STATEMENT_LOGGING_TARGET_DATA_RATE`] per second,
395    /// up to a max value of [`mz_sql::session::vars::STATEMENT_LOGGING_MAX_DATA_CREDIT`].
396    tokens: u64,
397    /// The last time at which a statement was logged.
398    last_logged_ts_seconds: u64,
399}
400
401impl ThrottlingState {
402    /// Create a new throttling state.
403    pub fn new(now: &NowFn) -> Self {
404        Self {
405            inner: Mutex::new(ThrottlingStateInner {
406                tokens: 0,
407                last_logged_ts_seconds: now() / 1000,
408            }),
409            throttled_count: std::sync::atomic::AtomicUsize::new(0),
410        }
411    }
412
413    /// Check if we need to drop a statement due to throttling, and update the number of available
414    /// tokens appropriately.
415    ///
416    /// Returns `false` if we must throttle this statement, and `true` otherwise.
417    /// Note: `throttled_count` is NOT modified by this method - callers are responsible
418    /// for incrementing it on throttle failure and resetting it when appropriate.
419    pub fn throttling_check(
420        &self,
421        cost: u64,
422        target_data_rate: u64,
423        max_data_credit: Option<u64>,
424        now: &NowFn,
425    ) -> bool {
426        let ts = now() / 1000;
427        let mut inner = self.inner.lock().expect("throttling state lock poisoned");
428        // We use saturating_sub here because system time isn't monotonic, causing cases
429        // when last_logged_ts_seconds is greater than ts.
430        let elapsed = ts.saturating_sub(inner.last_logged_ts_seconds);
431        inner.last_logged_ts_seconds = ts;
432        inner.tokens = inner
433            .tokens
434            .saturating_add(target_data_rate.saturating_mul(elapsed));
435        if let Some(max_data_credit) = max_data_credit {
436            inner.tokens = inner.tokens.min(max_data_credit);
437        }
438        if let Some(remaining) = inner.tokens.checked_sub(cost) {
439            tracing::debug!("throttling check passed. tokens remaining: {remaining}; cost: {cost}");
440            inner.tokens = remaining;
441            true
442        } else {
443            tracing::debug!(
444                "throttling check failed. tokens available: {}; cost: {cost}",
445                inner.tokens
446            );
447            false
448        }
449    }
450
451    pub fn get_throttled_count(&self) -> usize {
452        self.throttled_count.load(Ordering::Relaxed)
453    }
454
455    pub fn increment_throttled_count(&self) {
456        self.throttled_count.fetch_add(1, Ordering::Relaxed);
457    }
458
459    pub fn reset_throttled_count(&self) {
460        self.throttled_count.store(0, Ordering::Relaxed);
461    }
462}
463
464/// Encapsulates statement logging state needed by the frontend peek sequencing.
465///
466/// This struct bundles together all the statement logging-related state that
467/// the frontend peek sequencing needs to perform statement logging independently
468/// of the Coordinator's main task.
469#[derive(Debug, Clone)]
470pub struct StatementLoggingFrontend {
471    /// The log that statements executed by the session task are recorded in.
472    pub log: Arc<StatementLog>,
473    /// Shared throttling state for rate-limiting statement logging.
474    pub throttling_state: Arc<ThrottlingState>,
475    /// Reproducible RNG for statement sampling (only used in tests).
476    pub reproducible_rng: Arc<Mutex<rand::rngs::ChaCha8Rng>>,
477    /// Cached human version string from build info.
478    pub build_info_human_version: String,
479    /// Function to get current time for statement logging.
480    pub now: NowFn,
481}
482
483impl StatementLoggingFrontend {
484    /// Get prepared statement info for frontend peek sequencing.
485    ///
486    /// This function processes prepared statement logging info and builds the event rows.
487    /// It does NOT do throttling - that is handled externally by the caller in `begin_statement_execution`.
488    /// This is a read-only operation that does not mutate
489    /// the `PreparedStatementLoggingInfo` metadata.
490    ///
491    /// # Arguments
492    /// * `session` - The session executing the statement
493    /// * `logging` - Prepared statement logging info
494    ///
495    /// # Returns
496    /// A tuple containing:
497    /// - `Option<PreparedStatementEvent>`: If the prepared statement has not yet been logged,
498    ///   returns the packed rows for the prepared statement.
499    /// - `Uuid`: The UUID of the prepared statement.
500    fn get_prepared_statement_info(
501        &self,
502        session: &Session,
503        logging: &Arc<QCell<PreparedStatementLoggingInfo>>,
504    ) -> (Option<PreparedStatementEvent>, Uuid) {
505        let logging_ref = session.qcell_ro(&*logging);
506
507        match logging_ref {
508            PreparedStatementLoggingInfo::AlreadyLogged { uuid, .. } => (None, *uuid),
509            PreparedStatementLoggingInfo::StillToLog {
510                sql,
511                redacted_sql,
512                prepared_at,
513                name,
514                session_id,
515                accounted,
516                kind,
517                _sealed: _,
518            } => {
519                assert!(
520                    *accounted,
521                    "accounting for logging should be done in `begin_statement_execution`"
522                );
523                let uuid = epoch_to_uuid_v7(prepared_at);
524                let sql_hash: [u8; 32] = Sha256::digest(sql.as_bytes()).into();
525
526                let record = StatementPreparedRecord {
527                    id: uuid,
528                    sql_hash,
529                    name: name.clone(),
530                    session_id: *session_id,
531                    prepared_at: *prepared_at,
532                    kind: *kind,
533                };
534
535                // `mz_prepared_statement_history`
536                let mut mpsh_row = Row::default();
537                let mut mpsh_packer = mpsh_row.packer();
538                pack_statement_prepared_update(&record, &mut mpsh_packer);
539
540                // Read throttled_count from shared state
541                let throttled_count = self.throttling_state.get_throttled_count();
542                mpsh_packer.push(Datum::UInt64(CastFrom::cast_from(throttled_count)));
543
544                let sql_row = Row::pack([
545                    Datum::TimestampTz(
546                        to_datetime(*prepared_at)
547                            .truncate_day()
548                            .try_into()
549                            .expect("must fit"),
550                    ),
551                    Datum::Bytes(sql_hash.as_slice()),
552                    Datum::String(sql.as_str()),
553                    Datum::String(redacted_sql.as_str()),
554                ]);
555
556                let prepared_statement_event = PreparedStatementEvent {
557                    prepared_statement: mpsh_row,
558                    sql_text: sql_row,
559                    session_id: *session_id,
560                };
561
562                (Some(prepared_statement_event), uuid)
563            }
564        }
565    }
566
567    /// Marks a prepared statement as "already logged", so future executions only reference its
568    /// UUID rather than logging it again.
569    ///
570    /// This must only be called once we are committed to logging the prepared statement, i.e.
571    /// after the sampling and throttling checks in [`Self::begin_statement_execution`] have
572    /// passed. Mirrors `Coordinator::record_prepared_statement_as_logged`.
573    fn record_prepared_statement_as_logged(
574        &self,
575        uuid: Uuid,
576        session: &mut Session,
577        logging: &Arc<QCell<PreparedStatementLoggingInfo>>,
578    ) {
579        let logging = session.qcell_rw(&*logging);
580        if let PreparedStatementLoggingInfo::StillToLog { kind, .. } = logging {
581            let kind = *kind;
582            *logging = PreparedStatementLoggingInfo::AlreadyLogged { uuid, kind };
583        }
584    }
585
586    /// Begin statement execution logging from the frontend. (Corresponds to
587    /// `Coordinator::begin_statement_execution`, which logs the statements the coordinator
588    /// sequences.)
589    ///
590    /// This encapsulates all the statement logging setup:
591    /// - Retrieves system config values
592    /// - Performs sampling and throttling checks
593    /// - Creates statement logging records
594    /// - Attends to metrics.
595    ///
596    /// Returns `None` if the statement is not logged (due to sampling or throttling). Otherwise
597    /// the execution has begun in the log, and the caller owes it an end.
598    pub fn begin_statement_execution(
599        &self,
600        session: &mut Session,
601        params: &Params,
602        logging: &Arc<QCell<PreparedStatementLoggingInfo>>,
603        system_config: &SystemVars,
604        lifecycle_timestamps: Option<LifecycleTimestamps>,
605    ) -> Option<StatementLoggingId> {
606        // Skip logging for internal users unless explicitly enabled
607        let enable_internal_statement_logging = system_config.enable_internal_statement_logging();
608        if session.user().is_internal() && !enable_internal_statement_logging {
609            return None;
610        }
611
612        let sample_rate = effective_sample_rate(session, system_config);
613
614        let use_reproducible_rng = system_config.statement_logging_use_reproducible_rng();
615        let target_data_rate: Option<u64> = system_config
616            .statement_logging_target_data_rate()
617            .map(|rate| rate.cast_into());
618        let max_data_credit: Option<u64> = system_config
619            .statement_logging_max_data_credit()
620            .map(|credit| credit.cast_into());
621
622        // Only lock the RNG when we actually need reproducible sampling (tests only)
623        let sample = if use_reproducible_rng {
624            let mut rng = self.reproducible_rng.lock().expect("rng lock poisoned");
625            should_sample_statement(sample_rate, Some(&mut *rng))
626        } else {
627            should_sample_statement(sample_rate, None)
628        };
629
630        let sampled_label = sample.then_some("true").unwrap_or("false");
631        session
632            .metrics()
633            .statement_logging_records(&[sampled_label])
634            .inc_by(1);
635
636        // Clone only the metrics needed below, before the mutable borrow of session.
637        let unsampled_bytes_metric = session
638            .metrics()
639            .statement_logging_unsampled_bytes()
640            .clone();
641        let actual_bytes_metric = session.metrics().statement_logging_actual_bytes().clone();
642
643        // Handle the accounted flag and record byte metrics
644        let is_new_prepared_statement = if let Some((sql, accounted)) =
645            match session.qcell_rw(logging) {
646                PreparedStatementLoggingInfo::AlreadyLogged { .. } => None,
647                PreparedStatementLoggingInfo::StillToLog { sql, accounted, .. } => {
648                    Some((sql, accounted))
649                }
650            } {
651            if !*accounted {
652                unsampled_bytes_metric.inc_by(u64::cast_from(sql.len()));
653                if sample {
654                    actual_bytes_metric.inc_by(u64::cast_from(sql.len()));
655                }
656                *accounted = true;
657            }
658            true
659        } else {
660            false
661        };
662
663        if !sample {
664            return None;
665        }
666
667        // Capture the statement kind for the began-execution record, before
668        // `record_prepared_statement_as_logged` transitions the logging info to
669        // `AlreadyLogged`.
670        let kind = session.qcell_ro(logging).kind();
671
672        // Get prepared statement info.
673        let (prepared_statement_event, ps_uuid) =
674            self.get_prepared_statement_info(session, logging);
675
676        let began_at = if let Some(lifecycle_timestamps) = lifecycle_timestamps {
677            lifecycle_timestamps.received
678        } else {
679            (self.now)()
680        };
681
682        let current_time = (self.now)();
683        let execution_uuid = epoch_to_uuid_v7(&current_time);
684
685        // Create the execution record
686        let began_execution = create_began_execution_record(
687            execution_uuid,
688            ps_uuid,
689            sample_rate,
690            params,
691            session,
692            began_at,
693            self.build_info_human_version.clone(),
694            kind,
695        );
696
697        // Build rows to calculate cost for throttling
698        let mseh_update = pack_statement_began_execution_update(&began_execution);
699        let maybe_ps_prepared_statement = prepared_statement_event
700            .as_ref()
701            .map(|e| &e.prepared_statement);
702        let maybe_ps_sql_text = prepared_statement_event.as_ref().map(|e| &e.sql_text);
703
704        // Calculate cost of all rows we intend to log
705        let cost: usize = [
706            Some(&mseh_update),
707            maybe_ps_prepared_statement,
708            maybe_ps_sql_text,
709        ]
710        .into_iter()
711        .filter_map(|row_opt| row_opt.map(|row| row.byte_len()))
712        .fold(0_usize, |acc, x| acc.saturating_add(x));
713
714        // Do throttling check
715        let passed = if let Some(target_data_rate) = target_data_rate {
716            self.throttling_state.throttling_check(
717                cost.cast_into(),
718                target_data_rate,
719                max_data_credit,
720                &self.now,
721            )
722        } else {
723            true // No throttling configured
724        };
725
726        if !passed {
727            // Increment throttled_count in shared state
728            self.throttling_state.increment_throttled_count();
729            return None;
730        }
731
732        // Throttling passed, so we are now committed to mark the
733        // prepared statement as logged.
734        self.record_prepared_statement_as_logged(ps_uuid, session, logging);
735
736        // When we successfully log the first instance of a prepared statement
737        // (i.e., it is not throttled), reset the throttled count for future tracking.
738        if is_new_prepared_statement {
739            self.throttling_state.reset_throttled_count();
740        }
741
742        self.log
743            .begin_execution(began_execution, prepared_statement_event);
744        Some(StatementLoggingId(execution_uuid))
745    }
746}
747
748/// The effective rate at which statement execution should be sampled.
749/// This is the value of the session var `statement_logging_sample_rate`,
750/// constrained by the system var `statement_logging_max_sample_rate`.
751pub(crate) fn effective_sample_rate(session: &Session, system_vars: &SystemVars) -> f64 {
752    let system_max: f64 = system_vars
753        .statement_logging_max_sample_rate()
754        .try_into()
755        .expect("value constrained to be convertible to f64");
756    let user_rate: f64 = session
757        .vars()
758        .get_statement_logging_sample_rate()
759        .try_into()
760        .expect("value constrained to be convertible to f64");
761    f64::min(system_max, user_rate)
762}
763
764/// Helper function to decide whether to sample a statement execution.
765/// Returns `true` if the statement should be sampled based on the sample rate.
766///
767/// If `reproducible_rng` is `Some`, uses the provided RNG for reproducible sampling (used in tests).
768/// If `reproducible_rng` is `None`, uses the thread-local RNG.
769pub(crate) fn should_sample_statement(
770    sample_rate: f64,
771    reproducible_rng: Option<&mut rand::rngs::ChaCha8Rng>,
772) -> bool {
773    let distribution = Bernoulli::new(sample_rate).unwrap_or_else(|_| {
774        soft_panic_or_log!("statement_logging_sample_rate is out of range [0, 1]");
775        Bernoulli::new(0.0).expect("0.0 is valid for Bernoulli")
776    });
777    if let Some(rng) = reproducible_rng {
778        distribution.sample(rng)
779    } else {
780        distribution.sample(&mut rand::rng())
781    }
782}
783
784/// Serializes statement parameters for logging as UTF-8 strings.
785///
786/// Non-UTF-8 wire bytes are lossily replaced with `U+FFFD`.
787fn serialize_params(params: &Params) -> Vec<Option<String>> {
788    std::iter::zip(params.execute_types.iter(), params.datums.iter())
789        .enumerate()
790        .map(|(index, (r#type, datum))| {
791            mz_pgrepr::Value::from_datum(datum, r#type).map(|val| {
792                let mut buf = BytesMut::new();
793                val.encode_text(&mut buf, mz_pgrepr::TextEncodeSettings::STABLE);
794                // NOTE: `encode_text` can emit non-UTF-8 bytes for `"char"`
795                // (`PgLegacyChar`) params, which write their byte verbatim.
796                // Log the raw bytes so operators can recover what came in.
797                match String::from_utf8_lossy(&buf) {
798                    Cow::Borrowed(s) => s.to_owned(),
799                    Cow::Owned(s) => {
800                        let bytes_hex: String = buf.iter().map(|b| format!("{:02x}", b)).collect();
801                        tracing::warn!(
802                            index,
803                            ty = ?r#type,
804                            bytes_hex = %bytes_hex,
805                            "non-UTF-8 bytes in statement-logging param, replaced with U+FFFD"
806                        );
807                        s
808                    }
809                }
810            })
811        })
812        .collect()
813}
814
815/// Helper function to create a `StatementBeganExecutionRecord`.
816pub(crate) fn create_began_execution_record(
817    execution_uuid: Uuid,
818    prepared_statement_uuid: Uuid,
819    sample_rate: f64,
820    params: &Params,
821    session: &Session,
822    began_at: EpochMillis,
823    build_info_version: String,
824    kind: Option<StatementKind>,
825) -> StatementBeganExecutionRecord {
826    let params = serialize_params(params);
827    StatementBeganExecutionRecord {
828        id: execution_uuid,
829        prepared_statement_id: prepared_statement_uuid,
830        sample_rate,
831        params,
832        began_at,
833        application_name: session.application_name().to_string(),
834        transaction_isolation: session.vars().transaction_isolation().to_string(),
835        transaction_id: session
836            .transaction()
837            .inner()
838            .map(|t| t.id)
839            .unwrap_or_else(|| {
840                // This should never happen because every statement runs in an explicit or implicit
841                // transaction.
842                soft_panic_or_log!(
843                    "Statement logging got a statement with no associated transaction"
844                );
845                9999999
846            }),
847        mz_version: build_info_version,
848        kind,
849        // These are not known yet; we'll fill them in later.
850        cluster_id: None,
851        cluster_name: None,
852        execution_timestamp: None,
853        transient_index_id: None,
854        database_name: session.vars().database().into(),
855        search_path: session
856            .vars()
857            .search_path()
858            .iter()
859            .map(|s| s.as_str().to_string())
860            .collect(),
861    }
862}
863
864/// Statement log updates that await the next write to the statement log collections.
865#[derive(Debug, Default)]
866pub(crate) struct PendingStatementLog {
867    /// `mz_statement_execution_history`
868    pub(crate) statement_executions: Vec<(Row, Diff)>,
869    /// `mz_prepared_statement_history`
870    pub(crate) prepared_statements: Vec<(Row, Diff)>,
871    /// `mz_sql_text`
872    pub(crate) sql_texts: Vec<(Row, Diff)>,
873    /// `mz_session_history`
874    pub(crate) sessions: Vec<(Row, Diff)>,
875    /// `mz_statement_lifecycle_history`
876    pub(crate) statement_lifecycle_events: Vec<(Row, Diff)>,
877}
878
879/// An execution that has begun and not ended.
880///
881/// Its `mz_statement_execution_history` row is packed when the log is drained.
882/// An execution that begins and ends between two drains is therefore written
883/// once, as its final row.
884#[derive(Debug)]
885struct BegunExecution {
886    record: StatementBeganExecutionRecord,
887    /// The row that was last drained for this execution, which is retracted
888    /// when a newer one replaces it.
889    drained: Option<Row>,
890    /// Whether `record` has changed since `drained` was packed from it.
891    dirty: bool,
892}
893
894#[derive(Debug, Default)]
895struct StatementLogState {
896    /// Executions that have begun and not ended.
897    executions_begun: BTreeMap<Uuid, BegunExecution>,
898    /// Sessions that have started and are not yet in `mz_session_history`.
899    /// A session is logged with the first prepared statement logged for it.
900    unlogged_sessions: BTreeMap<Uuid, SessionHistoryEvent>,
901    pending: PendingStatementLog,
902}
903
904/// The statement log between the statements that are recorded in it and the
905/// collections it is periodically written to.
906///
907/// The coordinator and the session tasks record into it directly. A session
908/// task that executes a statement itself therefore logs it without sending the
909/// coordinator a message.
910///
911/// The lock is taken several times per logged statement by every session task,
912/// so no method holds it across more than a few map and vector operations on
913/// the hot path. Rows are packed outside it where the data allows.
914#[derive(Debug)]
915pub struct StatementLog {
916    state: Mutex<StatementLogState>,
917    lifecycle_logging_enabled: ConfigValHandle<bool>,
918}
919
920impl StatementLog {
921    /// `dyncfgs` must share its values with the catalog's system configuration.
922    pub(crate) fn new(dyncfgs: &ConfigSet) -> Self {
923        Self {
924            state: Mutex::new(StatementLogState::default()),
925            lifecycle_logging_enabled:
926                mz_adapter_types::dyncfgs::ENABLE_STATEMENT_LIFECYCLE_LOGGING.handle(dyncfgs),
927        }
928    }
929
930    fn state(&self) -> MutexGuard<'_, StatementLogState> {
931        self.state.lock().expect("statement log lock poisoned")
932    }
933
934    /// Records that the execution described by `record` began.
935    ///
936    /// `prepared_statement` is set if this is the first logged execution of
937    /// its prepared statement, which is then logged too, together with its
938    /// session if that is not logged yet.
939    pub(crate) fn begin_execution(
940        &self,
941        record: StatementBeganExecutionRecord,
942        prepared_statement: Option<PreparedStatementEvent>,
943    ) {
944        let lifecycle_update = self.pack_lifecycle_event(
945            StatementLoggingId(record.id),
946            &StatementLifecycleEvent::ExecutionBegan,
947            record.began_at,
948        );
949
950        let mut state = self.state();
951        state
952            .pending
953            .statement_lifecycle_events
954            .extend(lifecycle_update);
955        state.executions_begun.insert(
956            record.id,
957            BegunExecution {
958                record,
959                drained: None,
960                dirty: true,
961            },
962        );
963
964        if let Some(PreparedStatementEvent {
965            prepared_statement,
966            sql_text,
967            session_id,
968        }) = prepared_statement
969        {
970            state
971                .pending
972                .prepared_statements
973                .push((prepared_statement, Diff::ONE));
974            state.pending.sql_texts.push((sql_text, Diff::ONE));
975            if let Some(session) = state.unlogged_sessions.remove(&session_id) {
976                let update = pack_session_history_update(&session);
977                state.pending.sessions.push((update, Diff::ONE));
978            }
979        }
980    }
981
982    /// Sets the cluster that an execution runs on.
983    ///
984    /// Panics if the execution has ended.
985    pub(crate) fn set_execution_cluster(
986        &self,
987        id: StatementLoggingId,
988        cluster_id: ClusterId,
989        cluster_name: String,
990    ) {
991        let found = self.mutate_execution(id, |record| {
992            record.cluster_id = Some(cluster_id);
993            record.cluster_name = Some(cluster_name);
994        });
995        assert!(found, "cluster set after execution ended");
996    }
997
998    /// Sets the timestamp that an execution reads or writes at.
999    ///
1000    /// A duplicate end can race the asynchronous group-commit update, so an
1001    /// ended execution is skipped and not treated as corruption.
1002    pub(crate) fn set_execution_timestamp(&self, id: StatementLoggingId, timestamp: Timestamp) {
1003        let found = self.mutate_execution(id, |record| {
1004            record.execution_timestamp = Some(u64::from(timestamp));
1005        });
1006        if !found {
1007            tracing::warn!(
1008                statement_uuid = %id.0,
1009                "execution already ended, skipping execution timestamp update",
1010            );
1011        }
1012    }
1013
1014    /// Sets the transient index that an execution reads from.
1015    ///
1016    /// Panics if the execution has ended.
1017    pub(crate) fn set_execution_transient_index(
1018        &self,
1019        id: StatementLoggingId,
1020        transient_index_id: GlobalId,
1021    ) {
1022        let found = self.mutate_execution(id, |record| {
1023            record.transient_index_id = Some(transient_index_id);
1024        });
1025        assert!(found, "transient index set after execution ended");
1026    }
1027
1028    /// Applies `f` to the record of an execution that has begun. Returns
1029    /// whether the execution was found, which it is not once it has ended.
1030    fn mutate_execution<F>(&self, StatementLoggingId(id): StatementLoggingId, f: F) -> bool
1031    where
1032        F: FnOnce(&mut StatementBeganExecutionRecord),
1033    {
1034        let mut state = self.state();
1035        let Some(execution) = state.executions_begun.get_mut(&id) else {
1036            return false;
1037        };
1038        f(&mut execution.record);
1039        execution.dirty = true;
1040        true
1041    }
1042
1043    /// Records the end of an execution whose beginning was logged. Ends are
1044    /// idempotent: the first end wins and later ends for the same execution
1045    /// are ignored.
1046    pub(crate) fn end_execution(
1047        &self,
1048        id: StatementLoggingId,
1049        reason: StatementEndedExecutionReason,
1050        ended_at: EpochMillis,
1051    ) {
1052        let execution = self.state().executions_begun.remove(&id.0);
1053        let Some(BegunExecution {
1054            record: began_record,
1055            drained,
1056            dirty: _,
1057        }) = execution
1058        else {
1059            // The statement was already ended; the first end wins.
1060            //
1061            // A missing entry can only mean a duplicate end, never an end that
1062            // overtook its begin: a StatementLoggingId only exists once
1063            // `begin_execution` has returned.
1064            //
1065            // Duplicate ends are legitimate, if rare. Ownership of a
1066            // subscribe's end is handed from the frontend to the coordinator
1067            // while the subscribe is dispatched, and async cancellation can
1068            // strike mid-handoff: if a client disconnect drops the frontend
1069            // future after the coordinator created its guard but before the
1070            // frontend defused its own, both sides own the end and both emit
1071            // one. A peek's end stays with its lifecycle and has one owner.
1072            tracing::warn!(
1073                statement_uuid = %id.0,
1074                ?reason,
1075                "duplicate end of statement execution, keeping the first end",
1076            );
1077            return;
1078        };
1079        let ended_record = StatementEndedExecutionRecord {
1080            id: id.0,
1081            reason,
1082            ended_at,
1083        };
1084        let update = pack_full_statement_execution_update(&began_record, &ended_record);
1085        let lifecycle_update =
1086            self.pack_lifecycle_event(id, &StatementLifecycleEvent::ExecutionFinished, ended_at);
1087
1088        let mut state = self.state();
1089        let executions = &mut state.pending.statement_executions;
1090        executions.extend(drained.map(|row| (row, Diff::MINUS_ONE)));
1091        executions.push((update, Diff::ONE));
1092        state
1093            .pending
1094            .statement_lifecycle_events
1095            .extend(lifecycle_update);
1096    }
1097
1098    /// Records a lifecycle event of an execution, if lifecycle logging is on.
1099    pub(crate) fn record_lifecycle_event(
1100        &self,
1101        id: StatementLoggingId,
1102        event: &StatementLifecycleEvent,
1103        when: EpochMillis,
1104    ) {
1105        if let Some(update) = self.pack_lifecycle_event(id, event, when) {
1106            self.state().pending.statement_lifecycle_events.push(update);
1107        }
1108    }
1109
1110    fn pack_lifecycle_event(
1111        &self,
1112        StatementLoggingId(id): StatementLoggingId,
1113        event: &StatementLifecycleEvent,
1114        when: EpochMillis,
1115    ) -> Option<(Row, Diff)> {
1116        if !self.lifecycle_logging_enabled.get() {
1117            return None;
1118        }
1119        let row = Row::pack_slice(&[
1120            Datum::Uuid(id),
1121            Datum::String(event.as_str()),
1122            Datum::TimestampTz(to_datetime(when).try_into().expect("must fit")),
1123        ]);
1124        Some((row, Diff::ONE))
1125    }
1126
1127    pub(crate) fn begin_session(&self, event: SessionHistoryEvent) {
1128        self.state().unlogged_sessions.insert(event.id, event);
1129    }
1130
1131    pub(crate) fn end_session(&self, id: Uuid) {
1132        self.state().unlogged_sessions.remove(&id);
1133    }
1134
1135    /// Returns the `mz_session_history` row of a session that is not logged
1136    /// yet, without marking it as logged.
1137    pub(crate) fn unlogged_session_update(&self, id: Uuid) -> Option<Row> {
1138        self.state()
1139            .unlogged_sessions
1140            .get(&id)
1141            .map(pack_session_history_update)
1142    }
1143
1144    /// Takes the updates recorded since the last call.
1145    pub(crate) fn drain(&self) -> PendingStatementLog {
1146        let mut state = self.state();
1147        let StatementLogState {
1148            executions_begun,
1149            pending,
1150            ..
1151        } = &mut *state;
1152        // NOTE: This packs under the lock, once per execution that is in
1153        // flight and has changed, which is bounded by the number of
1154        // concurrently executing statements.
1155        for execution in executions_begun.values_mut().filter(|e| e.dirty) {
1156            let update = pack_statement_began_execution_update(&execution.record);
1157            let retraction = execution.drained.replace(update.clone());
1158            let executions = &mut pending.statement_executions;
1159            executions.extend(retraction.map(|row| (row, Diff::MINUS_ONE)));
1160            executions.push((update, Diff::ONE));
1161            execution.dirty = false;
1162        }
1163        std::mem::take(pending)
1164    }
1165}
1166
1167fn pack_full_statement_execution_update(
1168    began_record: &StatementBeganExecutionRecord,
1169    ended_record: &StatementEndedExecutionRecord,
1170) -> Row {
1171    let mut row = Row::default();
1172    let mut packer = row.packer();
1173    pack_statement_execution_inner(began_record, &mut packer);
1174    let (status, error_message, result_size, rows_returned, execution_strategy) =
1175        match &ended_record.reason {
1176            StatementEndedExecutionReason::Success {
1177                result_size,
1178                rows_returned,
1179                execution_strategy,
1180            } => (
1181                "success",
1182                None,
1183                result_size.map(|rs| i64::try_from(rs).expect("must fit")),
1184                rows_returned.map(|rr| i64::try_from(rr).expect("must fit")),
1185                execution_strategy.map(|es| es.name()),
1186            ),
1187            StatementEndedExecutionReason::Canceled => ("canceled", None, None, None, None),
1188            StatementEndedExecutionReason::Errored { error } => {
1189                // Backstop for SQL-435: `CREATE SECRET`/`ALTER SECRET` errors
1190                // can embed secret material (the rejected statement text, or a
1191                // value-bearing eval error). The per-site fixes redact the known
1192                // cases, but we never persist an unredacted error for these
1193                // kinds, regardless of which error variant fired. The client
1194                // still receives the real error over pgwire.
1195                let error = if began_record.kind.is_some_and(|kind| kind.is_secret()) {
1196                    "<error redacted for secret statement>"
1197                } else {
1198                    error.as_str()
1199                };
1200                ("error", Some(error), None, None, None)
1201            }
1202            StatementEndedExecutionReason::Aborted => ("aborted", None, None, None, None),
1203        };
1204    packer.extend([
1205        Datum::TimestampTz(
1206            to_datetime(ended_record.ended_at)
1207                .try_into()
1208                .expect("Sane system time"),
1209        ),
1210        status.into(),
1211        error_message.into(),
1212        result_size.into(),
1213        rows_returned.into(),
1214        execution_strategy.into(),
1215    ]);
1216    row
1217}
1218
1219fn pack_session_history_update(event: &SessionHistoryEvent) -> Row {
1220    let SessionHistoryEvent {
1221        id,
1222        connected_at,
1223        application_name,
1224        authenticated_user,
1225    } = event;
1226    Row::pack_slice(&[
1227        Datum::Uuid(*id),
1228        Datum::TimestampTz(to_datetime(*connected_at).try_into().expect("must fit")),
1229        Datum::String(&*application_name),
1230        Datum::String(&*authenticated_user),
1231    ])
1232}
1233
1234pub(crate) fn pack_statement_execution_inner(
1235    record: &StatementBeganExecutionRecord,
1236    packer: &mut RowPacker,
1237) {
1238    let StatementBeganExecutionRecord {
1239        id,
1240        prepared_statement_id,
1241        sample_rate,
1242        params,
1243        began_at,
1244        cluster_id,
1245        cluster_name,
1246        database_name,
1247        search_path,
1248        application_name,
1249        transaction_isolation,
1250        execution_timestamp,
1251        transaction_id,
1252        transient_index_id,
1253        mz_version,
1254        // Not packed into a column; only used to redact `error_message`.
1255        kind: _,
1256    } = record;
1257
1258    let cluster = cluster_id.map(|id| id.to_string());
1259    let transient_index_id = transient_index_id.map(|id| id.to_string());
1260    packer.extend([
1261        Datum::Uuid(*id),
1262        Datum::Uuid(*prepared_statement_id),
1263        Datum::Float64((*sample_rate).into()),
1264        match &cluster {
1265            None => Datum::Null,
1266            Some(cluster_id) => Datum::String(cluster_id),
1267        },
1268        Datum::String(&*application_name),
1269        cluster_name.as_ref().map(String::as_str).into(),
1270        Datum::String(database_name),
1271    ]);
1272    packer.push_list(search_path.iter().map(|s| Datum::String(s)));
1273    packer.extend([
1274        Datum::String(&*transaction_isolation),
1275        (*execution_timestamp).into(),
1276        Datum::UInt64(*transaction_id),
1277        match &transient_index_id {
1278            None => Datum::Null,
1279            Some(transient_index_id) => Datum::String(transient_index_id),
1280        },
1281    ]);
1282    packer
1283        .try_push_array(
1284            &[ArrayDimension {
1285                lower_bound: 1,
1286                length: params.len(),
1287            }],
1288            params
1289                .iter()
1290                .map(|p| Datum::from(p.as_ref().map(String::as_str))),
1291        )
1292        .expect("correct array dimensions");
1293    packer.push(Datum::from(mz_version.as_str()));
1294    packer.push(Datum::TimestampTz(
1295        to_datetime(*began_at).try_into().expect("Sane system time"),
1296    ));
1297}
1298
1299pub(crate) fn pack_statement_began_execution_update(record: &StatementBeganExecutionRecord) -> Row {
1300    let mut row = Row::default();
1301    let mut packer = row.packer();
1302    pack_statement_execution_inner(record, &mut packer);
1303    packer.extend([
1304        // finished_at
1305        Datum::Null,
1306        // finished_status
1307        Datum::Null,
1308        // error_message
1309        Datum::Null,
1310        // result_size
1311        Datum::Null,
1312        // rows_returned
1313        Datum::Null,
1314        // execution_status
1315        Datum::Null,
1316    ]);
1317    row
1318}
1319
1320pub(crate) fn pack_statement_prepared_update(
1321    record: &StatementPreparedRecord,
1322    packer: &mut RowPacker,
1323) {
1324    let StatementPreparedRecord {
1325        id,
1326        session_id,
1327        name,
1328        sql_hash,
1329        prepared_at,
1330        kind,
1331    } = record;
1332    packer.extend([
1333        Datum::Uuid(*id),
1334        Datum::Uuid(*session_id),
1335        Datum::String(name.as_str()),
1336        Datum::Bytes(sql_hash.as_slice()),
1337        Datum::TimestampTz(to_datetime(*prepared_at).try_into().expect("must fit")),
1338        kind.map(statement_kind_label_value).into(),
1339    ]);
1340}
1341
1342/// Bundles all information needed to install watch sets for statement lifecycle logging.
1343/// This includes the statement logging ID and the transitive dependencies to watch.
1344#[derive(Debug)]
1345pub struct WatchSetCreation {
1346    /// The statement logging ID for this execution.
1347    pub logging_id: StatementLoggingId,
1348    /// The timestamp at which to watch for dependencies becoming ready.
1349    pub timestamp: Timestamp,
1350    /// Transitive storage dependencies (tables, sources) to watch.
1351    pub storage_ids: BTreeSet<GlobalId>,
1352    /// Transitive compute dependencies (materialized views, indexes) to watch.
1353    pub compute_ids: BTreeSet<GlobalId>,
1354}
1355
1356impl WatchSetCreation {
1357    /// Compute transitive dependencies for watch sets from an input ID bundle, categorized into
1358    /// storage and compute IDs.
1359    pub fn new(
1360        logging_id: StatementLoggingId,
1361        catalog_state: &CatalogState,
1362        input_id_bundle: &CollectionIdBundle,
1363        timestamp: Timestamp,
1364    ) -> Self {
1365        let mut storage_ids = BTreeSet::new();
1366        let mut compute_ids = BTreeSet::new();
1367
1368        for item_id in input_id_bundle
1369            .iter()
1370            .map(|gid| catalog_state.get_entry_by_global_id(&gid).id())
1371            .flat_map(|id| catalog_state.transitive_uses(id))
1372        {
1373            let entry = catalog_state.get_entry(&item_id);
1374            match entry.item() {
1375                // TODO(alter_table): Adding all of the GlobalIds for an object is incorrect.
1376                // For example, this peek may depend on just a single version of a table, but
1377                // we would add dependencies on all versions of said table. Doing this is okay
1378                // for now since we can't yet version tables, but should get fixed.
1379                CatalogItem::Table(_) | CatalogItem::Source(_) => {
1380                    storage_ids.extend(entry.global_ids());
1381                }
1382                // Each catalog item is computed by at most one compute collection at a time,
1383                // which is also the most recent one.
1384                CatalogItem::MaterializedView(_) | CatalogItem::Index(_) => {
1385                    compute_ids.insert(entry.latest_global_id());
1386                }
1387                _ => {}
1388            }
1389        }
1390
1391        Self {
1392            logging_id,
1393            timestamp,
1394            storage_ids,
1395            compute_ids,
1396        }
1397    }
1398}
1399
1400#[cfg(test)]
1401mod tests {
1402    use differential_dataflow::consolidation::consolidate;
1403    use mz_dyncfg::ConfigSet;
1404    use mz_ore::now::to_datetime;
1405    use mz_repr::{Datum, Diff, Row, SqlScalarType, Timestamp};
1406    use mz_sql::plan::Params;
1407    use uuid::Uuid;
1408
1409    use super::{
1410        StatementBeganExecutionRecord, StatementEndedExecutionReason, StatementLog,
1411        StatementLoggingId, serialize_params,
1412    };
1413
1414    #[mz_ore::test]
1415    fn execution_changing_across_drains_leaves_one_final_row() {
1416        let dyncfgs = ConfigSet::default()
1417            .add(&mz_adapter_types::dyncfgs::ENABLE_STATEMENT_LIFECYCLE_LOGGING);
1418        let log = StatementLog::new(&dyncfgs);
1419        let id = Uuid::from_u128(1);
1420        let record = StatementBeganExecutionRecord {
1421            id,
1422            prepared_statement_id: Uuid::from_u128(2),
1423            sample_rate: 1.0,
1424            params: vec![],
1425            began_at: 1,
1426            cluster_id: None,
1427            cluster_name: None,
1428            database_name: "materialize".into(),
1429            search_path: vec![],
1430            application_name: "test".into(),
1431            transaction_isolation: "strict serializable".into(),
1432            execution_timestamp: None,
1433            transaction_id: 1,
1434            transient_index_id: None,
1435            mz_version: "test".into(),
1436            kind: None,
1437        };
1438        let id = StatementLoggingId(id);
1439        let mut written = vec![];
1440
1441        log.begin_execution(record, None);
1442        written.extend(log.drain().statement_executions);
1443        consolidate(&mut written);
1444        assert_eq!(written.len(), 1, "in-flight execution is visible");
1445        let in_flight = written[0].clone();
1446
1447        // An unchanged execution is not written again.
1448        assert!(log.drain().statement_executions.is_empty());
1449
1450        log.set_execution_timestamp(id, Timestamp::from(7));
1451        written.extend(log.drain().statement_executions);
1452        consolidate(&mut written);
1453        assert_eq!(written.len(), 1, "changed row replaces the drained one");
1454        assert_ne!(written[0], in_flight);
1455
1456        log.end_execution(id, StatementEndedExecutionReason::Canceled, 2);
1457        written.extend(log.drain().statement_executions);
1458        consolidate(&mut written);
1459        assert_eq!(written.len(), 1, "final row replaces the drained one");
1460        let (row, diff) = &written[0];
1461        assert_eq!(*diff, Diff::ONE);
1462        let finished_at = Datum::TimestampTz(to_datetime(2).try_into().expect("must fit"));
1463        assert!(row.iter().any(|datum| datum == Datum::String("canceled")));
1464        assert!(row.iter().any(|datum| datum == finished_at));
1465
1466        assert!(log.drain().statement_executions.is_empty());
1467    }
1468
1469    /// A `"char"` param whose byte is `>= 0x80` used to panic
1470    /// `String::from_utf8` on the statement-logging path. It should now
1471    /// round-trip through `from_utf8_lossy` and emit the replacement
1472    /// character instead.
1473    #[mz_ore::test]
1474    fn serialize_params_replaces_non_utf8_char() {
1475        let params = Params {
1476            datums: Row::pack_slice(&[Datum::UInt8(0xFF)]),
1477            execute_types: vec![SqlScalarType::PgLegacyChar],
1478            expected_types: vec![SqlScalarType::PgLegacyChar],
1479        };
1480        let out = serialize_params(&params);
1481        assert_eq!(out.len(), 1);
1482        assert_eq!(out[0].as_deref(), Some("\u{FFFD}"));
1483    }
1484
1485    /// An ASCII `"char"` param must render as its ASCII character, unchanged.
1486    #[mz_ore::test]
1487    fn serialize_params_ascii_char_unchanged() {
1488        let params = Params {
1489            datums: Row::pack_slice(&[Datum::UInt8(b'A')]),
1490            execute_types: vec![SqlScalarType::PgLegacyChar],
1491            expected_types: vec![SqlScalarType::PgLegacyChar],
1492        };
1493        let out = serialize_params(&params);
1494        assert_eq!(out[0].as_deref(), Some("A"));
1495    }
1496}