Skip to main content

mz_adapter/coord/
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::collections::BTreeMap;
11use std::sync::{Arc, Mutex};
12use std::time::Duration;
13
14use mz_adapter_types::connection::ConnectionId;
15use mz_compute_client::controller::error::CollectionLookupError;
16use mz_controller_types::ClusterId;
17use mz_ore::now::{EpochMillis, NowFn, epoch_to_uuid_v7, to_datetime};
18use mz_ore::task::spawn;
19use mz_ore::{cast::CastFrom, cast::CastInto};
20use mz_repr::adt::timestamp::TimestampLike;
21use mz_repr::{Datum, Diff, GlobalId, Row, Timestamp};
22use mz_sql::plan::Params;
23use mz_sql::session::metadata::SessionMetadata;
24use mz_storage_client::controller::IntrospectionType;
25use qcell::QCell;
26use rand::SeedableRng;
27use sha2::{Digest, Sha256};
28use tokio::time::MissedTickBehavior;
29use uuid::Uuid;
30
31use crate::coord::{ConnMeta, Coordinator, WatchSetResponse};
32use crate::session::{LifecycleTimestamps, Session};
33use crate::statement_logging::{
34    FrontendStatementLoggingEvent, PreparedStatementEvent, PreparedStatementLoggingInfo,
35    SessionHistoryEvent, StatementBeganExecutionRecord, StatementEndedExecutionReason,
36    StatementEndedExecutionRecord, StatementLifecycleEvent, StatementLoggingFrontend,
37    StatementLoggingId, StatementPreparedRecord, ThrottlingState, WatchSetCreation,
38    create_began_execution_record, effective_sample_rate, pack_statement_began_execution_update,
39    pack_statement_execution_inner, pack_statement_prepared_update, should_sample_statement,
40};
41
42use super::Message;
43
44/// Statement logging state in the Coordinator.
45#[derive(Debug)]
46pub(crate) struct StatementLogging {
47    /// Information about statement executions that have been logged
48    /// but not finished.
49    ///
50    /// This map needs to have enough state left over to later retract
51    /// the system table entries (so that we can update them when the
52    /// execution finished.)
53    executions_begun: BTreeMap<Uuid, StatementBeganExecutionRecord>,
54
55    /// Information about sessions that have been started, but which
56    /// have not yet been logged in `mz_session_history`.
57    /// They may be logged as part of a statement being executed (and chosen for logging).
58    unlogged_sessions: BTreeMap<Uuid, SessionHistoryEvent>,
59
60    /// A reproducible RNG for deciding whether to sample statement executions.
61    /// Only used by tests; otherwise, `rand::rng()` is used.
62    /// Controlled by the system var `statement_logging_use_reproducible_rng`.
63    /// This same instance will be used by all frontend tasks.
64    reproducible_rng: Arc<Mutex<rand_chacha::ChaCha8Rng>>,
65
66    /// Events to be persisted periodically.
67    pending_statement_execution_events: Vec<(Row, Diff)>,
68    pending_prepared_statement_events: Vec<PreparedStatementEvent>,
69    pending_session_events: Vec<Row>,
70    pending_statement_lifecycle_events: Vec<Row>,
71
72    /// Shared throttling state for rate-limiting statement logging.
73    pub(crate) throttling_state: Arc<ThrottlingState>,
74
75    /// Function to get the current time.
76    pub(crate) now: NowFn,
77}
78
79impl StatementLogging {
80    const REPRODUCIBLE_RNG_SEED: u64 = 42;
81
82    pub(crate) fn new(now: NowFn) -> Self {
83        Self {
84            executions_begun: BTreeMap::new(),
85            unlogged_sessions: BTreeMap::new(),
86            reproducible_rng: Arc::new(Mutex::new(rand_chacha::ChaCha8Rng::seed_from_u64(
87                Self::REPRODUCIBLE_RNG_SEED,
88            ))),
89            pending_statement_execution_events: Vec::new(),
90            pending_prepared_statement_events: Vec::new(),
91            pending_session_events: Vec::new(),
92            pending_statement_lifecycle_events: Vec::new(),
93            throttling_state: Arc::new(ThrottlingState::new(&now)),
94            now,
95        }
96    }
97
98    /// Create a `StatementLoggingFrontend` for use by frontend peek sequencing.
99    ///
100    /// This provides the frontend with all the state it needs to perform statement
101    /// logging without direct access to the Coordinator.
102    pub(crate) fn create_frontend(
103        &self,
104        build_info_human_version: String,
105    ) -> StatementLoggingFrontend {
106        StatementLoggingFrontend {
107            throttling_state: Arc::clone(&self.throttling_state),
108            reproducible_rng: Arc::clone(&self.reproducible_rng),
109            build_info_human_version,
110            now: self.now.clone(),
111        }
112    }
113}
114
115impl Coordinator {
116    /// Helper to write began execution events to pending buffers.
117    /// Can be called from both old and new peek sequencing.
118    fn write_began_execution_events(
119        &mut self,
120        record: StatementBeganExecutionRecord,
121        mseh_update: Row,
122        prepared_statement: Option<PreparedStatementEvent>,
123    ) {
124        // `mz_statement_execution_history`
125        self.statement_logging
126            .pending_statement_execution_events
127            .push((mseh_update, Diff::ONE));
128
129        // Track the execution for later updates
130        self.statement_logging
131            .executions_begun
132            .insert(record.id, record);
133
134        // If we have a prepared statement, log it and possibly its session
135        if let Some(ps_event) = prepared_statement {
136            let session_id = ps_event.session_id;
137            self.statement_logging
138                .pending_prepared_statement_events
139                .push(ps_event);
140
141            // Check if we need to log the session for this prepared statement
142            if let Some(sh) = self.statement_logging.unlogged_sessions.remove(&session_id) {
143                let sh_update = Self::pack_session_history_update(&sh);
144                self.statement_logging
145                    .pending_session_events
146                    .push(sh_update);
147            }
148        }
149    }
150
151    /// Handle a statement logging event from frontend peek sequencing.
152    pub(crate) fn handle_frontend_statement_logging_event(
153        &mut self,
154        event: FrontendStatementLoggingEvent,
155    ) {
156        match event {
157            FrontendStatementLoggingEvent::BeganExecution {
158                record,
159                mseh_update,
160                prepared_statement,
161            } => {
162                self.record_statement_lifecycle_event(
163                    &StatementLoggingId(record.id),
164                    &StatementLifecycleEvent::ExecutionBegan,
165                    record.began_at,
166                );
167                self.write_began_execution_events(record, mseh_update, prepared_statement);
168            }
169            FrontendStatementLoggingEvent::EndedExecution(ended_record) => {
170                self.end_statement_execution(
171                    StatementLoggingId(ended_record.id),
172                    ended_record.reason,
173                );
174            }
175            FrontendStatementLoggingEvent::SetCluster {
176                id,
177                cluster_id,
178                cluster_name,
179            } => {
180                self.set_statement_execution_cluster(id, cluster_id, cluster_name);
181            }
182            FrontendStatementLoggingEvent::SetTimestamp { id, timestamp } => {
183                self.set_statement_execution_timestamp(id, timestamp);
184            }
185            FrontendStatementLoggingEvent::SetTransientIndex {
186                id,
187                transient_index_id,
188            } => {
189                self.set_transient_index_id(id, transient_index_id);
190            }
191            FrontendStatementLoggingEvent::Lifecycle { id, event, when } => {
192                self.record_statement_lifecycle_event(&id, &event, when);
193            }
194        }
195    }
196
197    // TODO[btv] make this configurable via LD?
198    // Although... Logging every 5 seconds seems like it
199    // should have acceptable cost for now, since we do a
200    // group commit for tables every 1s anyway.
201    const STATEMENT_LOGGING_WRITE_INTERVAL: Duration = Duration::from_secs(5);
202
203    pub(crate) fn spawn_statement_logging_task(&self) {
204        let internal_cmd_tx = self.internal_cmd_tx.clone();
205        spawn(|| "statement_logging", async move {
206            let mut interval = tokio::time::interval(Coordinator::STATEMENT_LOGGING_WRITE_INTERVAL);
207            interval.set_missed_tick_behavior(MissedTickBehavior::Skip);
208            loop {
209                interval.tick().await;
210                let _ = internal_cmd_tx.send(Message::DrainStatementLog);
211            }
212        });
213    }
214
215    #[mz_ore::instrument(level = "debug")]
216    pub(crate) fn drain_statement_log(&mut self) {
217        let session_updates = std::mem::take(&mut self.statement_logging.pending_session_events)
218            .into_iter()
219            .map(|update| (update, Diff::ONE))
220            .collect();
221        let (prepared_statement_updates, sql_text_updates) =
222            std::mem::take(&mut self.statement_logging.pending_prepared_statement_events)
223                .into_iter()
224                .map(
225                    |PreparedStatementEvent {
226                         prepared_statement,
227                         sql_text,
228                         ..
229                     }| {
230                        ((prepared_statement, Diff::ONE), (sql_text, Diff::ONE))
231                    },
232                )
233                .unzip::<_, _, Vec<_>, Vec<_>>();
234        let statement_execution_updates =
235            std::mem::take(&mut self.statement_logging.pending_statement_execution_events);
236        let statement_lifecycle_updates =
237            std::mem::take(&mut self.statement_logging.pending_statement_lifecycle_events)
238                .into_iter()
239                .map(|update| (update, Diff::ONE))
240                .collect();
241
242        use IntrospectionType::*;
243        for (type_, updates) in [
244            (SessionHistory, session_updates),
245            (PreparedStatementHistory, prepared_statement_updates),
246            (StatementExecutionHistory, statement_execution_updates),
247            (StatementLifecycleHistory, statement_lifecycle_updates),
248            (SqlText, sql_text_updates),
249        ] {
250            if !updates.is_empty() && !self.controller.read_only() {
251                self.controller
252                    .storage
253                    .append_introspection_updates(type_, updates);
254            }
255        }
256    }
257
258    /// Check whether we need to do throttling (i.e., whether `STATEMENT_LOGGING_TARGET_DATA_RATE` is set).
259    /// If so, actually do the check.
260    ///
261    /// We expect `rows` to be the list of rows we intend to record and calculate the cost by summing the
262    /// byte lengths of the rows.
263    ///
264    /// Returns `false` if we must throttle this statement, and `true` otherwise.
265    fn statement_logging_throttling_check<'a, I>(&self, rows: I) -> bool
266    where
267        I: IntoIterator<Item = Option<&'a Row>>,
268    {
269        let cost = rows
270            .into_iter()
271            .filter_map(|row_opt| row_opt.map(|row| row.byte_len()))
272            .fold(0_usize, |acc, x| acc.saturating_add(x));
273
274        let Some(target_data_rate) = self
275            .catalog
276            .system_config()
277            .statement_logging_target_data_rate()
278        else {
279            return true;
280        };
281        let max_data_credit = self
282            .catalog
283            .system_config()
284            .statement_logging_max_data_credit();
285
286        self.statement_logging.throttling_state.throttling_check(
287            cost.cast_into(),
288            target_data_rate.cast_into(),
289            max_data_credit.map(CastInto::cast_into),
290            &self.statement_logging.now,
291        )
292    }
293
294    /// Marks a prepared statement as "already logged".
295    /// Mutates the `PreparedStatementLoggingInfo` metadata.
296    fn record_prepared_statement_as_logged(
297        &self,
298        uuid: Uuid,
299        session: &mut Session,
300        logging: &Arc<QCell<PreparedStatementLoggingInfo>>,
301    ) {
302        let logging = session.qcell_rw(&*logging);
303        if let PreparedStatementLoggingInfo::StillToLog { kind, .. } = logging {
304            let kind = *kind;
305            *logging = PreparedStatementLoggingInfo::AlreadyLogged { uuid, kind };
306        }
307    }
308
309    /// Returns any statement logging events needed for a particular
310    /// prepared statement. This is a read-only operation that does not mutate
311    /// the `PreparedStatementLoggingInfo` metadata.
312    ///
313    /// This function does not do a sampling check, and assumes we did so in a higher layer.
314    /// It also does not do a throttling check - that is done separately in `begin_statement_execution`.
315    ///
316    /// Returns a tuple containing:
317    /// - `Option<(StatementPreparedRecord, PreparedStatementEvent)>`: If the prepared statement
318    ///   has not yet been logged, returns the prepared statement record and the packed rows.
319    /// - `Uuid`: The UUID of the prepared statement.
320    pub(crate) fn get_prepared_statement_info(
321        &self,
322        session: &Session,
323        logging: &Arc<QCell<PreparedStatementLoggingInfo>>,
324    ) -> (
325        Option<(StatementPreparedRecord, PreparedStatementEvent)>,
326        Uuid,
327    ) {
328        let logging = session.qcell_ro(&*logging);
329
330        match logging {
331            PreparedStatementLoggingInfo::AlreadyLogged { uuid, .. } => (None, *uuid),
332            PreparedStatementLoggingInfo::StillToLog {
333                sql,
334                redacted_sql,
335                prepared_at,
336                name,
337                session_id,
338                accounted,
339                kind,
340                _sealed: _,
341            } => {
342                assert!(
343                    *accounted,
344                    "accounting for logging should be done in `begin_statement_execution`"
345                );
346                let uuid = epoch_to_uuid_v7(prepared_at);
347                let sql_hash: [u8; 32] = Sha256::digest(sql.as_bytes()).into();
348                let record = StatementPreparedRecord {
349                    id: uuid,
350                    sql_hash,
351                    name: name.to_string(),
352                    session_id: *session_id,
353                    prepared_at: *prepared_at,
354                    kind: *kind,
355                };
356
357                // `mz_prepared_statement_history`
358                let mut mpsh_row = Row::default();
359                let mut mpsh_packer = mpsh_row.packer();
360                pack_statement_prepared_update(&record, &mut mpsh_packer);
361                let throttled_count = self
362                    .statement_logging
363                    .throttling_state
364                    .get_throttled_count();
365                mpsh_packer.push(Datum::UInt64(CastFrom::cast_from(throttled_count)));
366
367                let sql_row = Row::pack([
368                    Datum::TimestampTz(
369                        to_datetime(*prepared_at)
370                            .truncate_day()
371                            .try_into()
372                            .expect("must fit"),
373                    ),
374                    Datum::Bytes(sql_hash.as_slice()),
375                    Datum::String(sql.as_str()),
376                    Datum::String(redacted_sql.as_str()),
377                ]);
378
379                (
380                    Some((
381                        record,
382                        PreparedStatementEvent {
383                            prepared_statement: mpsh_row,
384                            sql_text: sql_row,
385                            session_id: *session_id,
386                        },
387                    )),
388                    uuid,
389                )
390            }
391        }
392    }
393
394    /// Record the end of statement execution for a statement whose beginning
395    /// was logged. Ends are idempotent: the first end wins and later ends for
396    /// the same statement are ignored.
397    pub(crate) fn end_statement_execution(
398        &mut self,
399        id: StatementLoggingId,
400        reason: StatementEndedExecutionReason,
401    ) {
402        let StatementLoggingId(uuid) = id;
403        let now = self.now();
404        let ended_record = StatementEndedExecutionRecord {
405            id: uuid,
406            reason,
407            ended_at: now,
408        };
409
410        let Some(began_record) = self.statement_logging.executions_begun.remove(&uuid) else {
411            // The statement was already ended; the first end wins.
412            //
413            // A missing entry can only mean a duplicate end, never an end that
414            // overtook its begin: a StatementLoggingId is only minted when a
415            // begin is logged, and begins travel the same FIFO command channel
416            // as the commands that hand statements to the coordinator, so the
417            // coordinator never ends a statement before processing its begin.
418            //
419            // Duplicate ends are legitimate, if rare. Ownership of the end is
420            // handed from the frontend to the coordinator while a statement is
421            // dispatched, and async cancellation can strike mid-handoff: if a
422            // client disconnect drops the frontend future after the
423            // coordinator registered a peek but before the frontend defused
424            // its logging guard, both sides own the end and both emit one.
425            tracing::warn!(
426                statement_uuid = %uuid,
427                reason = ?ended_record.reason,
428                "duplicate end_statement_execution, keeping the first end",
429            );
430            return;
431        };
432        for (row, diff) in
433            Self::pack_statement_ended_execution_updates(&began_record, &ended_record)
434        {
435            self.statement_logging
436                .pending_statement_execution_events
437                .push((row, diff));
438        }
439        self.record_statement_lifecycle_event(
440            &id,
441            &StatementLifecycleEvent::ExecutionFinished,
442            now,
443        );
444    }
445
446    fn pack_session_history_update(event: &SessionHistoryEvent) -> Row {
447        let SessionHistoryEvent {
448            id,
449            connected_at,
450            application_name,
451            authenticated_user,
452        } = event;
453        Row::pack_slice(&[
454            Datum::Uuid(*id),
455            Datum::TimestampTz(to_datetime(*connected_at).try_into().expect("must fit")),
456            Datum::String(&*application_name),
457            Datum::String(&*authenticated_user),
458        ])
459    }
460
461    fn pack_statement_lifecycle_event(
462        StatementLoggingId(uuid): &StatementLoggingId,
463        event: &StatementLifecycleEvent,
464        when: EpochMillis,
465    ) -> Row {
466        Row::pack_slice(&[
467            Datum::Uuid(*uuid),
468            Datum::String(event.as_str()),
469            Datum::TimestampTz(to_datetime(when).try_into().expect("must fit")),
470        ])
471    }
472
473    fn pack_full_statement_execution_update(
474        began_record: &StatementBeganExecutionRecord,
475        ended_record: &StatementEndedExecutionRecord,
476    ) -> Row {
477        let mut row = Row::default();
478        let mut packer = row.packer();
479        pack_statement_execution_inner(began_record, &mut packer);
480        let (status, error_message, result_size, rows_returned, execution_strategy) =
481            match &ended_record.reason {
482                StatementEndedExecutionReason::Success {
483                    result_size,
484                    rows_returned,
485                    execution_strategy,
486                } => (
487                    "success",
488                    None,
489                    result_size.map(|rs| i64::try_from(rs).expect("must fit")),
490                    rows_returned.map(|rr| i64::try_from(rr).expect("must fit")),
491                    execution_strategy.map(|es| es.name()),
492                ),
493                StatementEndedExecutionReason::Canceled => ("canceled", None, None, None, None),
494                StatementEndedExecutionReason::Errored { error } => {
495                    // Backstop for SQL-435: `CREATE SECRET`/`ALTER SECRET` errors
496                    // can embed secret material (the rejected statement text, or a
497                    // value-bearing eval error). The per-site fixes redact the known
498                    // cases, but we never persist an unredacted error for these
499                    // kinds, regardless of which error variant fired. The client
500                    // still receives the real error over pgwire.
501                    let error = if began_record.kind.is_some_and(|kind| kind.is_secret()) {
502                        "<error redacted for secret statement>"
503                    } else {
504                        error.as_str()
505                    };
506                    ("error", Some(error), None, None, None)
507                }
508                StatementEndedExecutionReason::Aborted => ("aborted", None, None, None, None),
509            };
510        packer.extend([
511            Datum::TimestampTz(
512                to_datetime(ended_record.ended_at)
513                    .try_into()
514                    .expect("Sane system time"),
515            ),
516            status.into(),
517            error_message.into(),
518            result_size.into(),
519            rows_returned.into(),
520            execution_strategy.into(),
521        ]);
522        row
523    }
524
525    fn pack_statement_ended_execution_updates(
526        began_record: &StatementBeganExecutionRecord,
527        ended_record: &StatementEndedExecutionRecord,
528    ) -> [(Row, Diff); 2] {
529        let retraction = pack_statement_began_execution_update(began_record);
530        let new = Self::pack_full_statement_execution_update(began_record, ended_record);
531        [(retraction, Diff::MINUS_ONE), (new, Diff::ONE)]
532    }
533
534    /// Mutate a statement execution record via the given function `f`.
535    fn mutate_record<F: FnOnce(&mut StatementBeganExecutionRecord)>(
536        &mut self,
537        StatementLoggingId(id): StatementLoggingId,
538        f: F,
539    ) {
540        let record = self
541            .statement_logging
542            .executions_begun
543            .get_mut(&id)
544            .expect("mutate_record must not be called after execution ends");
545        let retraction = pack_statement_began_execution_update(record);
546        self.statement_logging
547            .pending_statement_execution_events
548            .push((retraction, Diff::MINUS_ONE));
549        f(record);
550        let update = pack_statement_began_execution_update(record);
551        self.statement_logging
552            .pending_statement_execution_events
553            .push((update, Diff::ONE));
554    }
555
556    /// Set the `cluster_id` and `cluster_name` for a statement, once they're known.
557    ///
558    /// The name is resolved by the caller (from the same catalog snapshot that selected the
559    /// cluster), rather than re-resolved here from `cluster_id`. This avoids a panic when the
560    /// cluster was concurrently dropped, and logs the name as it was at selection time.
561    ///
562    /// TODO(peek-seq): We could do the packing in the frontend task, and just send over the rows.
563    pub(crate) fn set_statement_execution_cluster(
564        &mut self,
565        id: StatementLoggingId,
566        cluster_id: ClusterId,
567        cluster_name: String,
568    ) {
569        self.mutate_record(id, |record| {
570            record.cluster_name = Some(cluster_name);
571            record.cluster_id = Some(cluster_id);
572        });
573    }
574
575    /// Set the `execution_timestamp` for a statement, once it's known
576    pub(crate) fn set_statement_execution_timestamp(
577        &mut self,
578        id: StatementLoggingId,
579        timestamp: Timestamp,
580    ) {
581        self.mutate_record(id, |record| {
582            record.execution_timestamp = Some(u64::from(timestamp));
583        });
584    }
585
586    pub(crate) fn set_transient_index_id(
587        &mut self,
588        id: StatementLoggingId,
589        transient_index_id: GlobalId,
590    ) {
591        self.mutate_record(id, |record| {
592            record.transient_index_id = Some(transient_index_id)
593        });
594    }
595
596    /// Possibly record the beginning of statement execution, depending on a randomly-chosen value.
597    /// If the execution beginning was indeed logged, returns a `StatementLoggingId` that must be
598    /// passed to `end_statement_execution` to record when it ends.
599    ///
600    /// `lifecycle_timestamps` has timestamps that come from the Adapter frontend (`mz-pgwire`) part
601    /// of the lifecycle.
602    pub(crate) fn begin_statement_execution(
603        &mut self,
604        session: &mut Session,
605        params: &Params,
606        logging: &Arc<QCell<PreparedStatementLoggingInfo>>,
607        lifecycle_timestamps: Option<LifecycleTimestamps>,
608    ) -> Option<StatementLoggingId> {
609        let enable_internal_statement_logging = self
610            .catalog()
611            .system_config()
612            .enable_internal_statement_logging();
613        if session.user().is_internal() && !enable_internal_statement_logging {
614            return None;
615        }
616
617        let sample_rate = effective_sample_rate(session, self.catalog().system_config());
618        let use_reproducible_rng = self
619            .catalog()
620            .system_config()
621            .statement_logging_use_reproducible_rng();
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
625                .statement_logging
626                .reproducible_rng
627                .lock()
628                .expect("rng lock poisoned");
629            should_sample_statement(sample_rate, Some(&mut *rng))
630        } else {
631            should_sample_statement(sample_rate, None)
632        };
633
634        // Figure out the cost of everything before we log.
635
636        // Track how many statements we're recording.
637        let sampled_label = sample.then_some("true").unwrap_or("false");
638        self.metrics
639            .statement_logging_records
640            .with_label_values(&[sampled_label])
641            .inc_by(1);
642
643        if let Some((sql, accounted)) = match session.qcell_rw(logging) {
644            PreparedStatementLoggingInfo::AlreadyLogged { .. } => None,
645            PreparedStatementLoggingInfo::StillToLog { sql, accounted, .. } => {
646                Some((sql, accounted))
647            }
648        } {
649            if !*accounted {
650                self.metrics
651                    .statement_logging_unsampled_bytes
652                    .inc_by(u64::cast_from(sql.len()));
653                if sample {
654                    self.metrics
655                        .statement_logging_actual_bytes
656                        .inc_by(u64::cast_from(sql.len()));
657                }
658                *accounted = true;
659            }
660        }
661        if !sample {
662            return None;
663        }
664
665        let (maybe_ps, ps_uuid) = self.get_prepared_statement_info(session, logging);
666
667        let began_at = if let Some(lifecycle_timestamps) = lifecycle_timestamps {
668            lifecycle_timestamps.received
669        } else {
670            self.now()
671        };
672        let now = self.now();
673        let execution_uuid = epoch_to_uuid_v7(&now);
674
675        let build_info_version = self
676            .catalog()
677            .state()
678            .config()
679            .build_info
680            .human_version(None);
681        let kind = session.qcell_ro(logging).kind();
682        let record = create_began_execution_record(
683            execution_uuid,
684            ps_uuid,
685            sample_rate,
686            params,
687            session,
688            began_at,
689            build_info_version,
690            kind,
691        );
692
693        // `mz_statement_execution_history`
694        let mseh_update = pack_statement_began_execution_update(&record);
695
696        let (maybe_ps_event, maybe_sh_event) = if let Some((ps_record, ps_event)) = maybe_ps {
697            if let Some(sh) = self
698                .statement_logging
699                .unlogged_sessions
700                .get(&ps_record.session_id)
701            {
702                (
703                    Some(ps_event),
704                    Some((Self::pack_session_history_update(sh), ps_record.session_id)),
705                )
706            } else {
707                (Some(ps_event), None)
708            }
709        } else {
710            (None, None)
711        };
712
713        let maybe_ps_prepared_statement = maybe_ps_event.as_ref().map(|e| &e.prepared_statement);
714        let maybe_ps_sql_text = maybe_ps_event.as_ref().map(|e| &e.sql_text);
715
716        if !self.statement_logging_throttling_check([
717            Some(&mseh_update),
718            maybe_ps_prepared_statement,
719            maybe_ps_sql_text,
720            maybe_sh_event.as_ref().map(|(row, _)| row),
721        ]) {
722            // Increment throttled_count in shared state
723            self.statement_logging
724                .throttling_state
725                .increment_throttled_count();
726            return None;
727        }
728        // When we successfully log the first instance of a prepared statement
729        // (i.e., it is not throttled), we also capture the number of previously
730        // throttled statement executions in the builtin prepared statement history table above,
731        // and then reset the throttled count for future tracking.
732        else if let PreparedStatementLoggingInfo::StillToLog { .. } = session.qcell_ro(logging) {
733            self.statement_logging
734                .throttling_state
735                .reset_throttled_count();
736        }
737
738        self.record_prepared_statement_as_logged(ps_uuid, session, logging);
739
740        self.record_statement_lifecycle_event(
741            &StatementLoggingId(execution_uuid),
742            &StatementLifecycleEvent::ExecutionBegan,
743            began_at,
744        );
745
746        self.statement_logging
747            .pending_statement_execution_events
748            .push((mseh_update, Diff::ONE));
749        self.statement_logging
750            .executions_begun
751            .insert(execution_uuid, record);
752
753        if let Some((sh_update, session_id)) = maybe_sh_event {
754            self.statement_logging
755                .pending_session_events
756                .push(sh_update);
757            // Mark the session as logged to avoid logging it again in the future
758            self.statement_logging.unlogged_sessions.remove(&session_id);
759        }
760        if let Some(ps_event) = maybe_ps_event {
761            self.statement_logging
762                .pending_prepared_statement_events
763                .push(ps_event);
764        }
765
766        Some(StatementLoggingId(execution_uuid))
767    }
768
769    /// Record a new connection event
770    pub(crate) fn begin_session_for_statement_logging(&mut self, session: &ConnMeta) {
771        let id = session.uuid();
772        let session_role = session.authenticated_role_id();
773        let event = SessionHistoryEvent {
774            id,
775            connected_at: session.connected_at(),
776            application_name: session.application_name().to_owned(),
777            authenticated_user: self.catalog.get_role(session_role).name.clone(),
778        };
779        self.statement_logging.unlogged_sessions.insert(id, event);
780    }
781
782    pub(crate) fn end_session_for_statement_logging(&mut self, uuid: Uuid) {
783        self.statement_logging.unlogged_sessions.remove(&uuid);
784    }
785
786    pub(crate) fn record_statement_lifecycle_event(
787        &mut self,
788        id: &StatementLoggingId,
789        event: &StatementLifecycleEvent,
790        when: EpochMillis,
791    ) {
792        if mz_adapter_types::dyncfgs::ENABLE_STATEMENT_LIFECYCLE_LOGGING
793            .get(self.catalog().system_config().dyncfgs())
794        {
795            let row = Self::pack_statement_lifecycle_event(id, event, when);
796            self.statement_logging
797                .pending_statement_lifecycle_events
798                .push(row);
799        }
800    }
801
802    /// Install watch sets for statement lifecycle logging.
803    ///
804    /// This installs both storage and compute watch sets that will fire
805    /// `StatementLifecycleEvent::StorageDependenciesFinished` and
806    /// `StatementLifecycleEvent::ComputeDependenciesFinished` respectively
807    /// when the dependencies are ready at the given timestamp.
808    pub(crate) fn install_peek_watch_sets(
809        &mut self,
810        conn_id: ConnectionId,
811        watch_set: WatchSetCreation,
812    ) -> Result<(), CollectionLookupError> {
813        let WatchSetCreation {
814            logging_id,
815            timestamp,
816            storage_ids,
817            compute_ids,
818        } = watch_set;
819
820        self.install_storage_watch_set(
821            conn_id.clone(),
822            storage_ids,
823            timestamp,
824            WatchSetResponse::StatementDependenciesReady(
825                logging_id,
826                StatementLifecycleEvent::StorageDependenciesFinished,
827            ),
828        )?;
829        self.install_compute_watch_set(
830            conn_id,
831            compute_ids,
832            timestamp,
833            WatchSetResponse::StatementDependenciesReady(
834                logging_id,
835                StatementLifecycleEvent::ComputeDependenciesFinished,
836            ),
837        )?;
838        Ok(())
839    }
840}