1use 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#[derive(Debug)]
45pub(crate) struct StatementLogging {
46 pub(crate) log: Arc<StatementLog>,
48
49 reproducible_rng: Arc<Mutex<rand::rngs::ChaCha8Rng>>,
54
55 pub(crate) throttling_state: Arc<ThrottlingState>,
57
58 pub(crate) now: NowFn,
60}
61
62impl StatementLogging {
63 const REPRODUCIBLE_RNG_SEED: u64 = 42;
64
65 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 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 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 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 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 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 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 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 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 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 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 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 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 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 self.statement_logging
433 .throttling_state
434 .increment_throttled_count();
435 return None;
436 }
437 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 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 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}