1use 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#[derive(Debug)]
46pub(crate) struct StatementLogging {
47 executions_begun: BTreeMap<Uuid, StatementBeganExecutionRecord>,
54
55 unlogged_sessions: BTreeMap<Uuid, SessionHistoryEvent>,
59
60 reproducible_rng: Arc<Mutex<rand_chacha::ChaCha8Rng>>,
65
66 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 pub(crate) throttling_state: Arc<ThrottlingState>,
74
75 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 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 fn write_began_execution_events(
119 &mut self,
120 record: StatementBeganExecutionRecord,
121 mseh_update: Row,
122 prepared_statement: Option<PreparedStatementEvent>,
123 ) {
124 self.statement_logging
126 .pending_statement_execution_events
127 .push((mseh_update, Diff::ONE));
128
129 self.statement_logging
131 .executions_begun
132 .insert(record.id, record);
133
134 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 self.statement_logging
724 .throttling_state
725 .increment_throttled_count();
726 return None;
727 }
728 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 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 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 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}