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::sync::{Arc, Mutex};
11use std::time::Duration;
12
13use mz_adapter_types::connection::ConnectionId;
14use mz_compute_client::controller::error::CollectionLookupError;
15use mz_controller_types::ClusterId;
16use mz_dyncfg::ConfigSet;
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, 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    PendingStatementLog, PreparedStatementEvent, PreparedStatementLoggingInfo, SessionHistoryEvent,
35    StatementEndedExecutionReason, StatementLifecycleEvent, StatementLog, StatementLoggingFrontend,
36    StatementLoggingId, StatementPreparedRecord, ThrottlingState, WatchSetCreation,
37    create_began_execution_record, effective_sample_rate, pack_statement_began_execution_update,
38    pack_statement_prepared_update, should_sample_statement,
39};
40
41use super::Message;
42
43/// Statement logging state in the Coordinator.
44#[derive(Debug)]
45pub(crate) struct StatementLogging {
46    /// The log that statements are recorded in, shared with the session tasks.
47    pub(crate) log: Arc<StatementLog>,
48
49    /// A reproducible RNG for deciding whether to sample statement executions.
50    /// Only used by tests; otherwise, `rand::rng()` is used.
51    /// Controlled by the system var `statement_logging_use_reproducible_rng`.
52    /// This same instance will be used by all frontend tasks.
53    reproducible_rng: Arc<Mutex<rand::rngs::ChaCha8Rng>>,
54
55    /// Shared throttling state for rate-limiting statement logging.
56    pub(crate) throttling_state: Arc<ThrottlingState>,
57
58    /// Function to get the current time.
59    pub(crate) now: NowFn,
60}
61
62impl StatementLogging {
63    const REPRODUCIBLE_RNG_SEED: u64 = 42;
64
65    /// `dyncfgs` must share its values with the catalog's system configuration.
66    pub(crate) fn new(now: NowFn, dyncfgs: &ConfigSet) -> Self {
67        Self {
68            log: Arc::new(StatementLog::new(dyncfgs)),
69            reproducible_rng: Arc::new(Mutex::new(rand::rngs::ChaCha8Rng::seed_from_u64(
70                Self::REPRODUCIBLE_RNG_SEED,
71            ))),
72            throttling_state: Arc::new(ThrottlingState::new(&now)),
73            now,
74        }
75    }
76
77    /// Create a `StatementLoggingFrontend` for use by frontend peek sequencing.
78    ///
79    /// This provides the frontend with all the state it needs to perform statement
80    /// logging without direct access to the Coordinator.
81    pub(crate) fn create_frontend(
82        &self,
83        build_info_human_version: String,
84    ) -> StatementLoggingFrontend {
85        StatementLoggingFrontend {
86            log: Arc::clone(&self.log),
87            throttling_state: Arc::clone(&self.throttling_state),
88            reproducible_rng: Arc::clone(&self.reproducible_rng),
89            build_info_human_version,
90            now: self.now.clone(),
91        }
92    }
93}
94
95impl Coordinator {
96    // TODO[btv] make this configurable via LD?
97    // Although... Logging every 5 seconds seems like it
98    // should have acceptable cost for now, since we do a
99    // group commit for tables every 1s anyway.
100    const STATEMENT_LOGGING_WRITE_INTERVAL: Duration = Duration::from_secs(5);
101
102    pub(crate) fn spawn_statement_logging_task(&self) {
103        let internal_cmd_tx = self.internal_cmd_tx.clone();
104        spawn(|| "statement_logging", async move {
105            let mut interval = tokio::time::interval(Coordinator::STATEMENT_LOGGING_WRITE_INTERVAL);
106            interval.set_missed_tick_behavior(MissedTickBehavior::Skip);
107            loop {
108                interval.tick().await;
109                let _ = internal_cmd_tx.send(Message::DrainStatementLog);
110            }
111        });
112    }
113
114    #[mz_ore::instrument(level = "debug")]
115    pub(crate) fn drain_statement_log(&mut self) {
116        let PendingStatementLog {
117            statement_executions,
118            prepared_statements,
119            sql_texts,
120            sessions,
121            statement_lifecycle_events,
122        } = self.statement_logging.log.drain();
123
124        use IntrospectionType::*;
125        for (type_, updates) in [
126            (SessionHistory, sessions),
127            (PreparedStatementHistory, prepared_statements),
128            (StatementExecutionHistory, statement_executions),
129            (StatementLifecycleHistory, statement_lifecycle_events),
130            (SqlText, sql_texts),
131        ] {
132            if !updates.is_empty() && !self.controller.read_only() {
133                self.controller
134                    .storage
135                    .append_introspection_updates(type_, updates);
136            }
137        }
138    }
139
140    /// Check whether we need to do throttling (i.e., whether `STATEMENT_LOGGING_TARGET_DATA_RATE` is set).
141    /// If so, actually do the check.
142    ///
143    /// We expect `rows` to be the list of rows we intend to record and calculate the cost by summing the
144    /// byte lengths of the rows.
145    ///
146    /// Returns `false` if we must throttle this statement, and `true` otherwise.
147    fn statement_logging_throttling_check<'a, I>(&self, rows: I) -> bool
148    where
149        I: IntoIterator<Item = Option<&'a Row>>,
150    {
151        let cost = rows
152            .into_iter()
153            .filter_map(|row_opt| row_opt.map(|row| row.byte_len()))
154            .fold(0_usize, |acc, x| acc.saturating_add(x));
155
156        let Some(target_data_rate) = self
157            .catalog
158            .system_config()
159            .statement_logging_target_data_rate()
160        else {
161            return true;
162        };
163        let max_data_credit = self
164            .catalog
165            .system_config()
166            .statement_logging_max_data_credit();
167
168        self.statement_logging.throttling_state.throttling_check(
169            cost.cast_into(),
170            target_data_rate.cast_into(),
171            max_data_credit.map(CastInto::cast_into),
172            &self.statement_logging.now,
173        )
174    }
175
176    /// Marks a prepared statement as "already logged".
177    /// Mutates the `PreparedStatementLoggingInfo` metadata.
178    fn record_prepared_statement_as_logged(
179        &self,
180        uuid: Uuid,
181        session: &mut Session,
182        logging: &Arc<QCell<PreparedStatementLoggingInfo>>,
183    ) {
184        let logging = session.qcell_rw(&*logging);
185        if let PreparedStatementLoggingInfo::StillToLog { kind, .. } = logging {
186            let kind = *kind;
187            *logging = PreparedStatementLoggingInfo::AlreadyLogged { uuid, kind };
188        }
189    }
190
191    /// Returns any statement logging events needed for a particular
192    /// prepared statement. This is a read-only operation that does not mutate
193    /// the `PreparedStatementLoggingInfo` metadata.
194    ///
195    /// This function does not do a sampling check, and assumes we did so in a higher layer.
196    /// It also does not do a throttling check - that is done separately in `begin_statement_execution`.
197    ///
198    /// Returns a tuple containing:
199    /// - `Option<(StatementPreparedRecord, PreparedStatementEvent)>`: If the prepared statement
200    ///   has not yet been logged, returns the prepared statement record and the packed rows.
201    /// - `Uuid`: The UUID of the prepared statement.
202    pub(crate) fn get_prepared_statement_info(
203        &self,
204        session: &Session,
205        logging: &Arc<QCell<PreparedStatementLoggingInfo>>,
206    ) -> (
207        Option<(StatementPreparedRecord, PreparedStatementEvent)>,
208        Uuid,
209    ) {
210        let logging = session.qcell_ro(&*logging);
211
212        match logging {
213            PreparedStatementLoggingInfo::AlreadyLogged { uuid, .. } => (None, *uuid),
214            PreparedStatementLoggingInfo::StillToLog {
215                sql,
216                redacted_sql,
217                prepared_at,
218                name,
219                session_id,
220                accounted,
221                kind,
222                _sealed: _,
223            } => {
224                assert!(
225                    *accounted,
226                    "accounting for logging should be done in `begin_statement_execution`"
227                );
228                let uuid = epoch_to_uuid_v7(prepared_at);
229                let sql_hash: [u8; 32] = Sha256::digest(sql.as_bytes()).into();
230                let record = StatementPreparedRecord {
231                    id: uuid,
232                    sql_hash,
233                    name: name.to_string(),
234                    session_id: *session_id,
235                    prepared_at: *prepared_at,
236                    kind: *kind,
237                };
238
239                // `mz_prepared_statement_history`
240                let mut mpsh_row = Row::default();
241                let mut mpsh_packer = mpsh_row.packer();
242                pack_statement_prepared_update(&record, &mut mpsh_packer);
243                let throttled_count = self
244                    .statement_logging
245                    .throttling_state
246                    .get_throttled_count();
247                mpsh_packer.push(Datum::UInt64(CastFrom::cast_from(throttled_count)));
248
249                let sql_row = Row::pack([
250                    Datum::TimestampTz(
251                        to_datetime(*prepared_at)
252                            .truncate_day()
253                            .try_into()
254                            .expect("must fit"),
255                    ),
256                    Datum::Bytes(sql_hash.as_slice()),
257                    Datum::String(sql.as_str()),
258                    Datum::String(redacted_sql.as_str()),
259                ]);
260
261                (
262                    Some((
263                        record,
264                        PreparedStatementEvent {
265                            prepared_statement: mpsh_row,
266                            sql_text: sql_row,
267                            session_id: *session_id,
268                        },
269                    )),
270                    uuid,
271                )
272            }
273        }
274    }
275
276    /// Records the end of a statement execution, see [`StatementLog::end_execution`].
277    pub(crate) fn end_statement_execution(
278        &self,
279        id: StatementLoggingId,
280        reason: StatementEndedExecutionReason,
281        ended_at: EpochMillis,
282    ) {
283        self.statement_logging
284            .log
285            .end_execution(id, reason, ended_at);
286    }
287
288    /// Set the `cluster_id` and `cluster_name` for a statement, once they're known.
289    ///
290    /// The name is resolved by the caller (from the same catalog snapshot that selected the
291    /// cluster), rather than re-resolved here from `cluster_id`. This avoids a panic when the
292    /// cluster was concurrently dropped, and logs the name as it was at selection time.
293    pub(crate) fn set_statement_execution_cluster(
294        &self,
295        id: StatementLoggingId,
296        cluster_id: ClusterId,
297        cluster_name: String,
298    ) {
299        self.statement_logging
300            .log
301            .set_execution_cluster(id, cluster_id, cluster_name);
302    }
303
304    /// Sets the execution timestamp if the statement is still active.
305    pub(crate) fn set_statement_execution_timestamp(
306        &self,
307        id: StatementLoggingId,
308        timestamp: Timestamp,
309    ) {
310        self.statement_logging
311            .log
312            .set_execution_timestamp(id, timestamp);
313    }
314
315    /// Possibly record the beginning of statement execution, depending on a randomly-chosen value.
316    /// If the execution beginning was indeed logged, returns a `StatementLoggingId` that must be
317    /// passed to `end_statement_execution` to record when it ends.
318    ///
319    /// `lifecycle_timestamps` has timestamps that come from the Adapter frontend (`mz-pgwire`) part
320    /// of the lifecycle.
321    pub(crate) fn begin_statement_execution(
322        &self,
323        session: &mut Session,
324        params: &Params,
325        logging: &Arc<QCell<PreparedStatementLoggingInfo>>,
326        lifecycle_timestamps: Option<LifecycleTimestamps>,
327    ) -> Option<StatementLoggingId> {
328        let enable_internal_statement_logging = self
329            .catalog()
330            .system_config()
331            .enable_internal_statement_logging();
332        if session.user().is_internal() && !enable_internal_statement_logging {
333            return None;
334        }
335
336        let sample_rate = effective_sample_rate(session, self.catalog().system_config());
337        let use_reproducible_rng = self
338            .catalog()
339            .system_config()
340            .statement_logging_use_reproducible_rng();
341        // Only lock the RNG when we actually need reproducible sampling (tests only)
342        let sample = if use_reproducible_rng {
343            let mut rng = self
344                .statement_logging
345                .reproducible_rng
346                .lock()
347                .expect("rng lock poisoned");
348            should_sample_statement(sample_rate, Some(&mut *rng))
349        } else {
350            should_sample_statement(sample_rate, None)
351        };
352
353        // Figure out the cost of everything before we log.
354
355        // Track how many statements we're recording.
356        let sampled_label = sample.then_some("true").unwrap_or("false");
357        self.metrics
358            .statement_logging_records
359            .with_label_values(&[sampled_label])
360            .inc_by(1);
361
362        if let Some((sql, accounted)) = match session.qcell_rw(logging) {
363            PreparedStatementLoggingInfo::AlreadyLogged { .. } => None,
364            PreparedStatementLoggingInfo::StillToLog { sql, accounted, .. } => {
365                Some((sql, accounted))
366            }
367        } {
368            if !*accounted {
369                self.metrics
370                    .statement_logging_unsampled_bytes
371                    .inc_by(u64::cast_from(sql.len()));
372                if sample {
373                    self.metrics
374                        .statement_logging_actual_bytes
375                        .inc_by(u64::cast_from(sql.len()));
376                }
377                *accounted = true;
378            }
379        }
380        if !sample {
381            return None;
382        }
383
384        let (maybe_ps, ps_uuid) = self.get_prepared_statement_info(session, logging);
385
386        let began_at = if let Some(lifecycle_timestamps) = lifecycle_timestamps {
387            lifecycle_timestamps.received
388        } else {
389            self.now()
390        };
391        let now = self.now();
392        let execution_uuid = epoch_to_uuid_v7(&now);
393
394        let build_info_version = self
395            .catalog()
396            .state()
397            .config()
398            .build_info
399            .human_version(None);
400        let kind = session.qcell_ro(logging).kind();
401        let record = create_began_execution_record(
402            execution_uuid,
403            ps_uuid,
404            sample_rate,
405            params,
406            session,
407            began_at,
408            build_info_version,
409            kind,
410        );
411
412        // `mz_statement_execution_history`
413        let mseh_update = pack_statement_began_execution_update(&record);
414
415        let maybe_ps_event = maybe_ps.map(|(_record, event)| event);
416        let maybe_sh_update = maybe_ps_event.as_ref().and_then(|event| {
417            self.statement_logging
418                .log
419                .unlogged_session_update(event.session_id)
420        });
421
422        let maybe_ps_prepared_statement = maybe_ps_event.as_ref().map(|e| &e.prepared_statement);
423        let maybe_ps_sql_text = maybe_ps_event.as_ref().map(|e| &e.sql_text);
424
425        if !self.statement_logging_throttling_check([
426            Some(&mseh_update),
427            maybe_ps_prepared_statement,
428            maybe_ps_sql_text,
429            maybe_sh_update.as_ref(),
430        ]) {
431            // Increment throttled_count in shared state
432            self.statement_logging
433                .throttling_state
434                .increment_throttled_count();
435            return None;
436        }
437        // When we successfully log the first instance of a prepared statement
438        // (i.e., it is not throttled), we also capture the number of previously
439        // throttled statement executions in the builtin prepared statement history table above,
440        // and then reset the throttled count for future tracking.
441        else if let PreparedStatementLoggingInfo::StillToLog { .. } = session.qcell_ro(logging) {
442            self.statement_logging
443                .throttling_state
444                .reset_throttled_count();
445        }
446
447        self.record_prepared_statement_as_logged(ps_uuid, session, logging);
448
449        self.statement_logging
450            .log
451            .begin_execution(record, maybe_ps_event);
452
453        Some(StatementLoggingId(execution_uuid))
454    }
455
456    /// Record a new connection event
457    pub(crate) fn begin_session_for_statement_logging(&self, session: &ConnMeta) {
458        let id = session.uuid();
459        let session_role = session.authenticated_role_id();
460        let event = SessionHistoryEvent {
461            id,
462            connected_at: session.connected_at(),
463            application_name: session.application_name().to_owned(),
464            authenticated_user: self.catalog.get_role(session_role).name.clone(),
465        };
466        self.statement_logging.log.begin_session(event);
467    }
468
469    pub(crate) fn end_session_for_statement_logging(&self, uuid: Uuid) {
470        self.statement_logging.log.end_session(uuid);
471    }
472
473    pub(crate) fn record_statement_lifecycle_event(
474        &self,
475        id: &StatementLoggingId,
476        event: &StatementLifecycleEvent,
477        when: EpochMillis,
478    ) {
479        self.statement_logging
480            .log
481            .record_lifecycle_event(*id, event, when);
482    }
483
484    /// Install watch sets for statement lifecycle logging.
485    ///
486    /// This installs both storage and compute watch sets that will fire
487    /// `StatementLifecycleEvent::StorageDependenciesFinished` and
488    /// `StatementLifecycleEvent::ComputeDependenciesFinished` respectively
489    /// when the dependencies are ready at the given timestamp.
490    pub(crate) fn install_peek_watch_sets(
491        &mut self,
492        conn_id: ConnectionId,
493        watch_set: WatchSetCreation,
494    ) -> Result<(), CollectionLookupError> {
495        let WatchSetCreation {
496            logging_id,
497            timestamp,
498            storage_ids,
499            compute_ids,
500        } = watch_set;
501
502        self.install_storage_watch_set(
503            conn_id.clone(),
504            storage_ids,
505            timestamp,
506            WatchSetResponse::StatementDependenciesReady(
507                logging_id,
508                StatementLifecycleEvent::StorageDependenciesFinished,
509            ),
510        )?;
511        self.install_compute_watch_set(
512            conn_id,
513            compute_ids,
514            timestamp,
515            WatchSetResponse::StatementDependenciesReady(
516                logging_id,
517                StatementLifecycleEvent::ComputeDependenciesFinished,
518            ),
519        )?;
520        Ok(())
521    }
522}