1use 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#[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 pub kind: Option<StatementKind>,
84}
85
86#[derive(Clone, Copy, Debug)]
87pub enum StatementExecutionStrategy {
88 Standard,
90 FastPath,
93 PersistFastPath,
96 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 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#[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 ExecuteResponse::SendingRowsImmediate { rows, .. } => {
174 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 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 #[derive(Debug, Copy, Clone)]
281 pub struct Private;
282}
283
284#[derive(Debug)]
286pub enum PreparedStatementLoggingInfo {
287 AlreadyLogged {
291 uuid: Uuid,
292 kind: Option<StatementKind>,
293 },
294 StillToLog {
297 sql: String,
299 redacted_sql: String,
302 prepared_at: EpochMillis,
304 name: String,
306 session_id: Uuid,
308 accounted: bool,
310 kind: Option<StatementKind>,
312
313 _sealed: sealed::Private,
316 },
317}
318
319impl PreparedStatementLoggingInfo {
320 pub fn kind(&self) -> Option<StatementKind> {
323 match self {
324 PreparedStatementLoggingInfo::StillToLog { kind, .. } => *kind,
325 PreparedStatementLoggingInfo::AlreadyLogged { kind, .. } => *kind,
326 }
327 }
328
329 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 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#[derive(Debug, Clone)]
368pub struct PreparedStatementEvent {
369 pub prepared_statement: Row,
370 pub sql_text: Row,
371 pub session_id: Uuid,
372}
373
374#[derive(Debug)]
376pub struct ThrottlingState {
377 inner: Mutex<ThrottlingStateInner>,
385 throttled_count: std::sync::atomic::AtomicUsize,
389}
390
391#[derive(Debug)]
392struct ThrottlingStateInner {
393 tokens: u64,
397 last_logged_ts_seconds: u64,
399}
400
401impl ThrottlingState {
402 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 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 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#[derive(Debug, Clone)]
470pub struct StatementLoggingFrontend {
471 pub log: Arc<StatementLog>,
473 pub throttling_state: Arc<ThrottlingState>,
475 pub reproducible_rng: Arc<Mutex<rand::rngs::ChaCha8Rng>>,
477 pub build_info_human_version: String,
479 pub now: NowFn,
481}
482
483impl StatementLoggingFrontend {
484 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 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 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 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 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 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 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 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 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 let kind = session.qcell_ro(logging).kind();
671
672 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(¤t_time);
684
685 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 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 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 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 };
725
726 if !passed {
727 self.throttling_state.increment_throttled_count();
729 return None;
730 }
731
732 self.record_prepared_statement_as_logged(ps_uuid, session, logging);
735
736 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
748pub(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
764pub(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
784fn 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 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
815pub(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 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 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#[derive(Debug, Default)]
866pub(crate) struct PendingStatementLog {
867 pub(crate) statement_executions: Vec<(Row, Diff)>,
869 pub(crate) prepared_statements: Vec<(Row, Diff)>,
871 pub(crate) sql_texts: Vec<(Row, Diff)>,
873 pub(crate) sessions: Vec<(Row, Diff)>,
875 pub(crate) statement_lifecycle_events: Vec<(Row, Diff)>,
877}
878
879#[derive(Debug)]
885struct BegunExecution {
886 record: StatementBeganExecutionRecord,
887 drained: Option<Row>,
890 dirty: bool,
892}
893
894#[derive(Debug, Default)]
895struct StatementLogState {
896 executions_begun: BTreeMap<Uuid, BegunExecution>,
898 unlogged_sessions: BTreeMap<Uuid, SessionHistoryEvent>,
901 pending: PendingStatementLog,
902}
903
904#[derive(Debug)]
915pub struct StatementLog {
916 state: Mutex<StatementLogState>,
917 lifecycle_logging_enabled: ConfigValHandle<bool>,
918}
919
920impl StatementLog {
921 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 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 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 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 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 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 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 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 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 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 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 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 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 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 Datum::Null,
1306 Datum::Null,
1308 Datum::Null,
1310 Datum::Null,
1312 Datum::Null,
1314 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#[derive(Debug)]
1345pub struct WatchSetCreation {
1346 pub logging_id: StatementLoggingId,
1348 pub timestamp: Timestamp,
1350 pub storage_ids: BTreeSet<GlobalId>,
1352 pub compute_ids: BTreeSet<GlobalId>,
1354}
1355
1356impl WatchSetCreation {
1357 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 CatalogItem::Table(_) | CatalogItem::Source(_) => {
1380 storage_ids.extend(entry.global_ids());
1381 }
1382 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 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 #[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(¶ms);
1481 assert_eq!(out.len(), 1);
1482 assert_eq!(out[0].as_deref(), Some("\u{FFFD}"));
1483 }
1484
1485 #[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(¶ms);
1494 assert_eq!(out[0].as_deref(), Some("A"));
1495 }
1496}