1use std::collections::{BTreeMap, BTreeSet};
11use std::num::NonZeroUsize;
12use std::sync::atomic::{AtomicBool, Ordering};
13use std::sync::{Arc, Weak};
14
15use differential_dataflow::consolidation::consolidate;
16use itertools::Itertools;
17use mz_compute_client::controller::PeekNotification;
18use mz_compute_client::controller::error::{CollectionMissing, InstanceMissing};
19use mz_compute_client::controller::instance_client::InstanceClient;
20use mz_compute_client::controller::instance_client::{AcquireReadHoldsError, InstanceShutDown};
21use mz_compute_client::controller::peek_lifecycle::PeekLifecycle;
22use mz_compute_client::protocol::command::PeekTarget;
23use mz_compute_client::protocol::response::PeekResponse;
24use mz_compute_types::ComputeInstanceId;
25use mz_expr::row::RowCollection;
26use mz_expr::{RowSetFinishing, RowSetFinishingIncremental};
27use mz_ore::cast::CastFrom;
28use mz_ore::soft_panic_or_log;
29use mz_persist_client::{PersistClient, Schemas};
30use mz_persist_types::codec_impls::UnitSchema;
31use mz_repr::GlobalId;
32use mz_repr::Timestamp;
33use mz_repr::global_id::TransientIdGen;
34use mz_repr::{IntoRowIterator, RelationDesc};
35use mz_sql::ast::{Raw, Statement};
36use mz_sql::optimizer_metrics::OptimizerMetrics;
37use mz_sql::plan::Params;
38use mz_sql::session::hint::ApplicationNameHint;
39use mz_sql::session::metadata::SessionMetadata;
40use mz_sql_parser::ast::{CopyRelation, CopyStatement, SubscribeStatement};
41use mz_storage_types::sources::{SourceData, Timeline};
42use mz_timestamp_oracle::TimestampOracle;
43use prometheus::Histogram;
44use qcell::QCell;
45use thiserror::Error;
46use timely::progress::Antichain;
47use tokio::sync::{Semaphore, oneshot};
48use uuid::Uuid;
49
50use crate::catalog::{Catalog, CatalogState};
51use crate::command::{CatalogSnapshot, Command, ExecuteResponse};
52use crate::coord::appends::GroupCommitNotifier;
53use crate::coord::peek::{FastPathPlan, PeekResponseUnary};
54use crate::coord::timestamp_selection::TimestampDetermination;
55use crate::coord::{Coordinator, ExecuteContextExtra, ExecuteContextGuard, Message};
56use crate::metrics::Metrics;
57use crate::peek_registry::{ConnectionPeeks, RegisterError, RegisteredPeek};
58use crate::session::{LifecycleTimestamps, Session};
59use crate::statement_logging::{
60 PreparedStatementLoggingInfo, StatementLog, StatementLoggingFrontend, StatementLoggingId,
61 WatchSetCreation,
62};
63use crate::{
64 AdapterError, AdapterNotice, Client, CollectionIdBundle, ReadHolds, metrics, statement_logging,
65};
66
67pub type StorageCollectionsHandle =
69 Arc<dyn mz_storage_client::storage_collections::StorageCollections + Send + Sync>;
70
71#[derive(Debug, Clone)]
73pub struct PeekClient {
74 connection_peeks: Arc<ConnectionPeeks>,
76 coordinator_client: CoordinatorClient,
77 catalog_cache: Weak<Catalog>,
84 compute_instances: BTreeMap<ComputeInstanceId, InstanceClient>,
89 pub storage_collections: StorageCollectionsHandle,
91 pub transient_id_gen: Arc<TransientIdGen>,
93 pub optimizer_metrics: OptimizerMetrics,
94 oracles: BTreeMap<Timeline, Arc<dyn TimestampOracle<Timestamp> + Send + Sync>>,
96 persist_client: PersistClient,
97 pub statement_logging_frontend: StatementLoggingFrontend,
99 pub occ_write_semaphore: Arc<Semaphore>,
101 pub(crate) group_commit_notifier: GroupCommitNotifier,
104 pub read_only: bool,
106}
107
108#[derive(Debug, Clone)]
110pub(crate) enum CoordinatorClient {
111 Session(Client),
112 Background {
113 tx: tokio::sync::mpsc::UnboundedSender<Message>,
114 metrics: Metrics,
115 },
116}
117
118impl CoordinatorClient {
119 pub(crate) fn send(&self, command: Command) {
128 if self.try_send(command) {
129 return;
130 }
131 match self {
132 CoordinatorClient::Session(_) => panic!("coordinator unexpectedly gone"),
133 CoordinatorClient::Background { .. } => {
134 tracing::debug!("dropping background command, coordinator is gone")
135 }
136 }
137 }
138
139 pub(crate) fn try_send(&self, command: Command) -> bool {
140 match self {
141 CoordinatorClient::Session(client) => client.try_send(command),
142 CoordinatorClient::Background { tx, .. } => tx
143 .send(Message::Command(
144 mz_ore::tracing::OpenTelemetryContext::obtain(),
145 command,
146 ))
147 .is_ok(),
148 }
149 }
150
151 pub(crate) fn metrics(&self) -> &Metrics {
152 match self {
153 CoordinatorClient::Session(client) => client.metrics(),
154 CoordinatorClient::Background { metrics, .. } => metrics,
155 }
156 }
157}
158
159impl PeekClient {
160 pub(crate) fn connection_peeks(&self) -> &Arc<ConnectionPeeks> {
161 &self.connection_peeks
162 }
163
164 pub(crate) async fn register_peek(
170 &mut self,
171 cluster_id: ComputeInstanceId,
172 depends_on: BTreeSet<GlobalId>,
173 mut catalog: Arc<Catalog>,
174 cancellation_epoch: u64,
175 logging: &mut ExecutionLogging,
176 is_fast_path: bool,
177 ) -> Result<PeekHandle, AdapterError> {
178 let connection = Arc::clone(&self.connection_peeks);
179 let uuid = Uuid::new_v4();
180 let retired = Arc::clone(&connection);
181 let logging = logging.hand_off();
182 let lifecycle = Arc::new(PeekLifecycle::new(move |notification| {
183 retired.remove(&uuid);
184 if let Some(logging) = logging {
185 let reason = match notification {
186 PeekNotification::Success { rows, result_size } => {
187 statement_logging::StatementEndedExecutionReason::Success {
188 result_size: Some(result_size),
189 rows_returned: Some(rows),
190 execution_strategy: Some(if is_fast_path {
191 statement_logging::StatementExecutionStrategy::FastPath
192 } else {
193 statement_logging::StatementExecutionStrategy::Standard
194 }),
195 }
196 }
197 PeekNotification::Error(error) => {
198 statement_logging::StatementEndedExecutionReason::Errored { error }
199 }
200 PeekNotification::Canceled => {
201 statement_logging::StatementEndedExecutionReason::Canceled
202 }
203 };
204 logging.retire(reason);
205 }
206 }));
207 let peek = PeekHandle { uuid, lifecycle };
208 loop {
209 match connection.register(
210 uuid,
211 RegisteredPeek {
212 cluster_id,
213 depends_on: depends_on.clone(),
214 lifecycle: Arc::downgrade(&peek.lifecycle),
215 },
216 cancellation_epoch,
217 || catalog.transient_revision_is_current(),
218 ) {
219 Ok(()) => return Ok(peek),
220 Err(RegisterError::Canceled) => {
221 peek.lifecycle.cancel(PeekResponse::Canceled);
222 return Err(AdapterError::Canceled);
223 }
224 Err(RegisterError::CatalogChanged) => {
225 let refreshed = self
229 .call_coordinator(|tx| Command::CatalogSnapshot { tx })
230 .await;
231 catalog = match refreshed {
232 Ok(CatalogSnapshot { catalog }) => catalog,
233 Err(error) => {
234 peek.lifecycle
235 .complete(PeekNotification::Error(error.to_string()));
236 return Err(error);
237 }
238 };
239 self.catalog_cache = Arc::downgrade(&catalog);
240 let error = if catalog.try_get_cluster(cluster_id).is_none() {
241 Some(AdapterError::ConcurrentDependencyDrop {
242 dependency_kind: "cluster",
243 dependency_id: cluster_id.to_string(),
244 })
245 } else {
246 depends_on.iter().find_map(|id| {
247 catalog.try_get_entry_by_global_id(id).is_none().then(|| {
248 AdapterError::ConcurrentDependencyDrop {
249 dependency_kind: "collection",
250 dependency_id: id.to_string(),
251 }
252 })
253 })
254 };
255 if let Some(error) = error {
256 peek.lifecycle
257 .complete(PeekNotification::Error(error.to_string()));
258 return Err(error);
259 }
260 }
261 }
262 }
263 }
264
265 #[allow(clippy::too_many_arguments)]
270 pub(crate) fn new(
271 coordinator_client: CoordinatorClient,
272 connection_peeks: Arc<ConnectionPeeks>,
273 catalog: &Arc<Catalog>,
274 storage_collections: StorageCollectionsHandle,
275 transient_id_gen: Arc<TransientIdGen>,
276 optimizer_metrics: OptimizerMetrics,
277 persist_client: PersistClient,
278 statement_logging_frontend: StatementLoggingFrontend,
279 occ_write_semaphore: Arc<Semaphore>,
280 group_commit_notifier: GroupCommitNotifier,
281 read_only: bool,
282 ) -> Self {
283 Self {
284 connection_peeks,
285 coordinator_client,
286 catalog_cache: Arc::downgrade(catalog),
287 compute_instances: Default::default(), storage_collections,
289 transient_id_gen,
290 optimizer_metrics,
291 statement_logging_frontend,
292 oracles: Default::default(), persist_client,
294 occ_write_semaphore,
295 group_commit_notifier,
296 read_only,
297 }
298 }
299
300 pub async fn ensure_compute_instance_client(
301 &mut self,
302 compute_instance: ComputeInstanceId,
303 ) -> Result<InstanceClient, CollectionLookupError> {
304 if !self.compute_instances.contains_key(&compute_instance) {
305 let client = self
306 .call_coordinator(|tx| Command::GetComputeInstanceClient {
307 instance_id: compute_instance,
308 tx,
309 })
310 .await
311 .map_err(|_| CollectionLookupError::InstanceShutDown)??;
312 self.compute_instances.insert(compute_instance, client);
313 }
314 Ok(self
315 .compute_instances
316 .get(&compute_instance)
317 .expect("ensured above")
318 .clone())
319 }
320
321 pub async fn ensure_oracle(
322 &mut self,
323 timeline: Timeline,
324 ) -> Result<&mut Arc<dyn TimestampOracle<Timestamp> + Send + Sync>, AdapterError> {
325 if !self.oracles.contains_key(&timeline) {
326 let oracle = self
327 .call_coordinator(|tx| Command::GetOracle {
328 timeline: timeline.clone(),
329 tx,
330 })
331 .await??;
332 self.oracles.insert(timeline.clone(), oracle);
333 }
334 Ok(self.oracles.get_mut(&timeline).expect("ensured above"))
335 }
336
337 pub async fn catalog_snapshot(&mut self, context: &str) -> Arc<Catalog> {
350 let cached = self
356 .catalog_cache
357 .upgrade()
358 .filter(|catalog| catalog.transient_revision_is_current());
359 if let Some(catalog) = cached {
360 self.coordinator_client
361 .metrics()
362 .catalog_snapshot_cache
363 .with_label_values(&[context, "hit"])
364 .inc();
365 return catalog;
366 }
367
368 let start = std::time::Instant::now();
371 let CatalogSnapshot { catalog } = self
375 .call_coordinator(|tx| Command::CatalogSnapshot { tx })
376 .await
377 .expect("coordinator unexpectedly dropped catalog snapshot response");
378 let metrics = self.coordinator_client.metrics();
379 metrics
380 .catalog_snapshot_seconds
381 .with_label_values(&[context])
382 .observe(start.elapsed().as_secs_f64());
383 metrics
384 .catalog_snapshot_cache
385 .with_label_values(&[context, "miss"])
386 .inc();
387 self.catalog_cache = Arc::downgrade(&catalog);
388 catalog
389 }
390
391 pub(crate) async fn call_coordinator<T, F>(&self, f: F) -> Result<T, AdapterError>
393 where
394 F: FnOnce(oneshot::Sender<T>) -> Command,
395 {
396 let (tx, rx) = oneshot::channel();
397 self.coordinator_client.send(f(tx));
398 Ok(rx.await?)
399 }
400
401 pub(crate) async fn add_timestamp_notice(
408 &self,
409 session: &Session,
410 cluster_id: ComputeInstanceId,
411 id_bundle: CollectionIdBundle,
412 determination: TimestampDetermination,
413 ) -> Result<(), AdapterError> {
414 fail::fail_point!("timestamp_notice_before_dispatch");
418 let request = self.call_coordinator(|tx| Command::ExplainTimestamp {
419 conn_id: session.conn_id().clone(),
420 session_wall_time: session.pcx().wall_time,
421 cluster_id,
422 id_bundle,
423 determination,
424 tx,
425 });
426 match request.await? {
427 Ok(explanation) => session.add_notice(AdapterNotice::QueryTimestamp { explanation }),
428 Err(AdapterError::ConcurrentDependencyDrop { .. }) => {}
429 Err(e) => return Err(e),
430 }
431 Ok(())
432 }
433
434 pub(crate) fn coordinator_client(&self) -> &CoordinatorClient {
436 &self.coordinator_client
437 }
438
439 pub async fn acquire_read_holds_and_least_valid_write(
452 &mut self,
453 id_bundle: &CollectionIdBundle,
454 ) -> Result<(ReadHolds, Antichain<Timestamp>), CollectionLookupError> {
455 let mut read_holds = ReadHolds::new();
456 let mut upper = Antichain::new();
457
458 if !id_bundle.storage_ids.is_empty() {
459 let desired_storage: Vec<_> = id_bundle.storage_ids.iter().copied().collect();
460 let storage_read_holds = self
461 .storage_collections
462 .acquire_read_holds(desired_storage)?;
463 read_holds.storage_holds = storage_read_holds
464 .into_iter()
465 .map(|hold| (hold.id(), hold))
466 .collect();
467
468 let storage_ids: Vec<_> = id_bundle.storage_ids.iter().copied().collect();
469 for f in self
470 .storage_collections
471 .collections_frontiers(storage_ids)?
472 {
473 upper.extend(f.write_frontier);
474 }
475 }
476
477 for (&instance_id, collection_ids) in &id_bundle.compute_ids {
478 let client = self.ensure_compute_instance_client(instance_id).await?;
479
480 for (id, read_hold, write_frontier) in client
481 .acquire_read_holds_and_collection_write_frontiers(
482 collection_ids.iter().copied().collect(),
483 )
484 .await?
485 {
486 let prev = read_holds
487 .compute_holds
488 .insert((instance_id, id), read_hold);
489 assert!(
490 prev.is_none(),
491 "duplicate compute ID in id_bundle {id_bundle:?}"
492 );
493
494 upper.extend(write_frontier);
495 }
496 }
497
498 Ok((read_holds, upper))
499 }
500
501 pub(crate) async fn implement_fast_path_peek_plan(
513 &mut self,
514 fast_path: FastPathPlan,
515 timestamp: Timestamp,
516 finishing: mz_expr::RowSetFinishing,
517 compute_instance: ComputeInstanceId,
518 target_replica: Option<mz_cluster_client::ReplicaId>,
519 intermediate_result_type: mz_repr::SqlRelationType,
520 max_result_size: u64,
521 max_returned_query_size: Option<u64>,
522 row_set_finishing_seconds: Histogram,
523 input_read_holds: ReadHolds,
524 peek_stash_read_batch_size_bytes: usize,
525 peek_stash_read_memory_budget_bytes: usize,
526 conn_id: mz_adapter_types::connection::ConnectionId,
527 depends_on: std::collections::BTreeSet<mz_repr::GlobalId>,
528 watch_set: Option<WatchSetCreation>,
529 logging: &mut ExecutionLogging,
530 catalog: Arc<Catalog>,
531 cancellation_epoch: u64,
532 ) -> Result<crate::ExecuteResponse, AdapterError> {
533 if let FastPathPlan::Constant(rows_res, _) = fast_path {
535 if let Some(ref ws) = watch_set {
538 self.log_lifecycle_event(
539 ws.logging_id,
540 statement_logging::StatementLifecycleEvent::StorageDependenciesFinished,
541 );
542 self.log_lifecycle_event(
543 ws.logging_id,
544 statement_logging::StatementLifecycleEvent::ComputeDependenciesFinished,
545 );
546 }
547
548 let mut rows = match rows_res {
549 Ok(rows) => rows,
550 Err(e) => return Err(e.into()),
551 };
552 consolidate(&mut rows);
553
554 let mut results = Vec::new();
555 for (row, count) in rows {
556 let count = match u64::try_from(count.into_inner()) {
557 Ok(u) => usize::cast_from(u),
558 Err(_) => {
559 return Err(AdapterError::Unstructured(anyhow::anyhow!(
560 "Negative multiplicity in constant result: {}",
561 count
562 )));
563 }
564 };
565 match std::num::NonZeroUsize::new(count) {
566 Some(nzu) => {
567 results.push((row, nzu));
568 }
569 None => {
570 }
572 };
573 }
574 let row_collection = RowCollection::new(results, &finishing.order_by);
575 return match finishing.finish(
576 row_collection,
577 max_result_size,
578 max_returned_query_size,
579 &row_set_finishing_seconds,
580 ) {
581 Ok((rows, _bytes)) => Ok(Coordinator::send_immediate_rows(rows)),
582 Err(e) => Err(AdapterError::ResultSize(e)),
584 };
585 }
586
587 let (peek_target, target_read_hold, literal_constraints, mfp, strategy) = match fast_path {
588 FastPathPlan::PeekExisting(_coll_id, idx_id, literal_constraints, mfp) => {
589 let peek_target = PeekTarget::Index { id: idx_id };
590 let target_read_hold = input_read_holds
591 .compute_holds
592 .get(&(compute_instance, idx_id))
593 .expect("missing compute read hold on PeekExisting peek target")
594 .clone();
595 let strategy = statement_logging::StatementExecutionStrategy::FastPath;
596 (
597 peek_target,
598 target_read_hold,
599 literal_constraints,
600 mfp,
601 strategy,
602 )
603 }
604 FastPathPlan::PeekPersist(coll_id, literal_constraint, mfp) => {
605 let literal_constraints = literal_constraint.map(|r| vec![r]);
606 let metadata = self
607 .storage_collections
608 .collection_metadata(coll_id)
609 .map_err(AdapterError::concurrent_dependency_drop_from_collection_missing)?
610 .clone();
611 let peek_target = PeekTarget::Persist {
612 id: coll_id,
613 metadata,
614 };
615 let target_read_hold = input_read_holds
616 .storage_holds
617 .get(&coll_id)
618 .expect("missing storage read hold on PeekPersist peek target")
619 .clone();
620 let strategy = statement_logging::StatementExecutionStrategy::PersistFastPath;
621 (
622 peek_target,
623 target_read_hold,
624 literal_constraints,
625 mfp,
626 strategy,
627 )
628 }
629 FastPathPlan::Constant(..) => {
630 unreachable!()
632 }
633 };
634
635 let (rows_tx, rows_rx) = oneshot::channel();
636
637 let cols = (0..intermediate_result_type.arity()).map(|i| format!("peek_{i}"));
640 let result_desc = RelationDesc::new(intermediate_result_type.clone(), cols);
641
642 let client = self
643 .ensure_compute_instance_client(compute_instance)
644 .await
645 .map_err(|error| {
646 AdapterError::concurrent_dependency_drop_from_collection_lookup_error(
647 error,
648 compute_instance,
649 )
650 })?;
651
652 if let Some(watch_set) = watch_set {
653 self.call_coordinator(|tx| Command::InstallPeekWatchSets {
654 conn_id: conn_id.clone(),
655 watch_set,
656 tx,
657 })
658 .await??;
659 }
660 let peek = self
661 .register_peek(
662 compute_instance,
663 depends_on,
664 catalog,
665 cancellation_epoch,
666 logging,
667 true,
668 )
669 .await?;
670
671 fail::fail_point!("peek_after_register_before_issue");
676
677 let finishing_for_instance = finishing.clone();
678 let peek_result = client
679 .peek(
680 peek_target,
681 literal_constraints,
682 peek.uuid,
683 timestamp,
684 result_desc,
685 finishing_for_instance,
686 mfp,
687 target_read_hold,
688 target_replica,
689 rows_tx,
690 Some(Arc::clone(&peek.lifecycle)),
691 )
692 .await;
693
694 if let Err(err) = peek_result {
695 let err = AdapterError::concurrent_dependency_drop_from_instance_peek_error(
696 err,
697 compute_instance,
698 );
699 peek.lifecycle
700 .complete(PeekNotification::Error(err.to_string()));
701 return Err(err);
702 }
703
704 let peek_response_stream = create_peek_response_stream(
705 rows_rx,
706 finishing,
707 max_result_size,
708 max_returned_query_size,
709 row_set_finishing_seconds,
710 self.persist_client.clone(),
711 peek_stash_read_batch_size_bytes,
712 peek_stash_read_memory_budget_bytes,
713 );
714
715 Ok(crate::ExecuteResponse::SendingRowsStreaming {
716 rows: Box::pin(peek.guard_stream(peek_response_stream)),
717 instance_id: compute_instance,
718 strategy,
719 })
720 }
721
722 fn begin_statement_logging(
727 &self,
728 session: &mut Session,
729 params: &Params,
730 logging: &Arc<QCell<PreparedStatementLoggingInfo>>,
731 catalog: &Catalog,
732 lifecycle_timestamps: Option<LifecycleTimestamps>,
733 ) -> StatementLoggingGuard {
734 let id = self.statement_logging_frontend.begin_statement_execution(
735 session,
736 params,
737 logging,
738 catalog.system_config(),
739 lifecycle_timestamps,
740 );
741
742 StatementLoggingGuard {
743 id,
744 log: Arc::clone(&self.statement_logging_frontend.log),
745 now: self.statement_logging_frontend.now.clone(),
746 }
747 }
748
749 pub(crate) fn log_set_cluster(
751 &self,
752 id: StatementLoggingId,
753 cluster_id: mz_controller_types::ClusterId,
754 cluster_name: String,
755 ) {
756 self.statement_logging_frontend
757 .log
758 .set_execution_cluster(id, cluster_id, cluster_name);
759 }
760
761 pub(crate) fn log_set_timestamp(&self, id: StatementLoggingId, timestamp: mz_repr::Timestamp) {
763 self.statement_logging_frontend
764 .log
765 .set_execution_timestamp(id, timestamp);
766 }
767
768 pub(crate) fn log_set_transient_index_id(
770 &self,
771 id: StatementLoggingId,
772 transient_index_id: mz_repr::GlobalId,
773 ) {
774 self.statement_logging_frontend
775 .log
776 .set_execution_transient_index(id, transient_index_id);
777 }
778
779 pub(crate) fn dependency_watch_set(
783 &self,
784 id: StatementLoggingId,
785 catalog_state: &CatalogState,
786 input_id_bundle: &CollectionIdBundle,
787 determination: &TimestampDetermination,
788 ) -> Option<WatchSetCreation> {
789 let timestamp = determination.timestamp_context.timestamp_or_default();
799 if !determination.upper.less_equal(×tamp) {
800 use statement_logging::StatementLifecycleEvent::*;
801 self.log_lifecycle_event(id, StorageDependenciesFinished);
802 self.log_lifecycle_event(id, ComputeDependenciesFinished);
803 return None;
804 }
805 Some(WatchSetCreation::new(
806 id,
807 catalog_state,
808 input_id_bundle,
809 timestamp,
810 ))
811 }
812
813 pub(crate) fn log_lifecycle_event(
815 &self,
816 id: StatementLoggingId,
817 event: statement_logging::StatementLifecycleEvent,
818 ) {
819 let when = (self.statement_logging_frontend.now)();
820 self.statement_logging_frontend
821 .log
822 .record_lifecycle_event(id, &event, when);
823 }
824}
825
826#[derive(Debug)]
828pub struct PeekHandle {
829 pub(crate) uuid: Uuid,
830 pub(crate) lifecycle: Arc<PeekLifecycle>,
831}
832
833pub(crate) struct PeekCancelSafety(AtomicBool);
836
837impl PeekCancelSafety {
838 pub(crate) fn new() -> Self {
839 Self(AtomicBool::new(true))
840 }
841
842 pub(crate) fn delegate_side_effect(&self) {
843 self.0.store(false, Ordering::Relaxed);
844 }
845
846 pub(crate) fn can_abort(&self) -> bool {
847 self.0.load(Ordering::Relaxed)
848 }
849}
850
851impl PeekHandle {
852 pub(crate) fn guard_stream<S>(
853 self,
854 stream: S,
855 ) -> impl futures::Stream<Item = crate::PeekResponseUnary> + Send + Sync
856 where
857 S: futures::Stream<Item = crate::PeekResponseUnary> + Send + Sync,
858 {
859 async_stream::stream! {
860 let peek = self;
861 futures::pin_mut!(stream);
862 while let Some(response) = futures::StreamExt::next(&mut stream).await {
863 if let crate::PeekResponseUnary::Error(error) = &response {
867 peek.lifecycle.complete(PeekNotification::Error(error.to_string()));
868 }
869 yield response;
870 }
871 }
872 }
873}
874
875impl Drop for PeekHandle {
876 fn drop(&mut self) {
877 self.lifecycle.cancel(PeekResponse::Canceled);
878 }
879}
880
881#[must_use = "StatementLoggingGuard must be explicitly retired or handed off; \
895 otherwise `Drop` will log the statement as Aborted"]
896struct StatementLoggingGuard {
897 id: Option<StatementLoggingId>,
899 log: Arc<StatementLog>,
900 now: mz_ore::now::NowFn,
901}
902
903impl StatementLoggingGuard {
904 fn adopt(outer: ExecuteContextGuard, peek_client: &PeekClient) -> Self {
907 Self {
908 id: outer.defuse().retire(),
909 log: Arc::clone(&peek_client.statement_logging_frontend.log),
910 now: peek_client.statement_logging_frontend.now.clone(),
911 }
912 }
913
914 fn id(&self) -> Option<StatementLoggingId> {
916 self.id
917 }
918
919 fn retire(mut self, reason: statement_logging::StatementEndedExecutionReason) {
922 self.emit(reason);
923 }
924
925 fn release(mut self) -> ExecuteContextExtra {
928 ExecuteContextExtra::new(self.id.take())
929 }
930
931 fn defuse(&mut self) {
935 self.id = None;
936 }
937
938 fn emit(&mut self, reason: statement_logging::StatementEndedExecutionReason) {
939 let Some(id) = self.id.take() else {
940 return;
941 };
942 let ended_at = (self.now)();
943 self.log.end_execution(id, reason, ended_at);
944 }
945}
946
947impl Drop for StatementLoggingGuard {
948 fn drop(&mut self) {
949 self.emit(statement_logging::StatementEndedExecutionReason::Aborted);
952 }
953}
954
955pub(crate) struct ExecutionLogging {
966 guard: Option<StatementLoggingGuard>,
967 handed_off: bool,
970 coordinator_must_not_run: bool,
974}
975
976pub(crate) enum TakeOver {
978 StatementToRun,
980 UnrolledExecute,
989}
990
991impl ExecutionLogging {
992 pub(crate) fn adopt(outer: Option<ExecuteContextGuard>, peek_client: &PeekClient) -> Self {
996 Self {
997 guard: outer.map(|outer| StatementLoggingGuard::adopt(outer, peek_client)),
998 handed_off: false,
999 coordinator_must_not_run: false,
1000 }
1001 }
1002
1003 pub(crate) fn id(&self) -> Option<StatementLoggingId> {
1006 self.guard.as_ref().and_then(|guard| guard.id())
1007 }
1008
1009 pub(crate) fn take_over(
1018 &mut self,
1019 peek_client: &PeekClient,
1020 session: &mut Session,
1021 stmt: Option<&Statement<Raw>>,
1022 params: &Params,
1023 logging: &Arc<QCell<PreparedStatementLoggingInfo>>,
1024 catalog: &Catalog,
1025 lifecycle_timestamps: Option<LifecycleTimestamps>,
1026 taking_over: TakeOver,
1027 ) -> Option<StatementLoggingId> {
1028 self.begin_or_inherit(
1029 peek_client,
1030 session,
1031 params,
1032 logging,
1033 catalog,
1034 lifecycle_timestamps,
1035 );
1036 count_statement(session, stmt);
1037 if matches!(taking_over, TakeOver::StatementToRun) {
1038 self.coordinator_must_not_run = true;
1039 }
1040 self.id()
1041 }
1042
1043 fn begin_or_inherit(
1046 &mut self,
1047 peek_client: &PeekClient,
1048 session: &mut Session,
1049 params: &Params,
1050 logging: &Arc<QCell<PreparedStatementLoggingInfo>>,
1051 catalog: &Catalog,
1052 lifecycle_timestamps: Option<LifecycleTimestamps>,
1053 ) {
1054 if self.guard.is_none() {
1055 self.guard = Some(peek_client.begin_statement_logging(
1056 session,
1057 params,
1058 logging,
1059 catalog,
1060 lifecycle_timestamps,
1061 ));
1062 }
1063 }
1064
1065 #[must_use]
1070 pub(crate) fn release(&mut self) -> Option<ExecuteContextExtra> {
1071 if self.coordinator_must_not_run {
1072 soft_panic_or_log!(
1073 "statement handed to the coordinator after the session task took it over: \
1074 its per-statement metrics are counted twice"
1075 );
1076 }
1077 if self.handed_off {
1078 return Some(ExecuteContextExtra::new(None));
1079 }
1080 self.guard.take().map(|guard| guard.release())
1081 }
1082
1083 pub(crate) fn retire(self, result: &Result<ExecuteResponse, AdapterError>) {
1085 let Some(guard) = self.guard else {
1086 return;
1087 };
1088 if guard.id().is_none() {
1092 return;
1093 }
1094 guard.retire(end_reason(result));
1095 }
1096
1097 pub(crate) fn defuse(&mut self) {
1100 if let Some(guard) = self.guard.as_mut() {
1101 guard.defuse();
1102 }
1103 }
1104
1105 fn hand_off(&mut self) -> Option<StatementLoggingGuard> {
1109 let guard = self.guard.take();
1110 self.handed_off = guard.is_some();
1111 guard
1112 }
1113}
1114
1115fn end_reason(
1122 result: &Result<ExecuteResponse, AdapterError>,
1123) -> statement_logging::StatementEndedExecutionReason {
1124 if let Ok(response) = result {
1125 if terminates_elsewhere(response) {
1126 soft_panic_or_log!(
1127 "frontend-sequenced statement still owed an end event while returning {:?}",
1128 crate::command::ExecuteResponseKind::from(response)
1129 );
1130 return statement_logging::StatementEndedExecutionReason::Aborted;
1131 }
1132 }
1133 result.into()
1134}
1135
1136fn count_statement(session: &Session, stmt: Option<&Statement<Raw>>) {
1143 let Some(stmt) = stmt else {
1144 return;
1145 };
1146 let session_type = metrics::session_type_label_value(session.user());
1147 session
1148 .metrics()
1149 .query_total(&[session_type, metrics::statement_type_label_value(stmt)])
1150 .inc();
1151 if let Statement::Subscribe(SubscribeStatement { output, .. })
1152 | Statement::Copy(CopyStatement {
1153 relation: CopyRelation::Subscribe(SubscribeStatement { output, .. }),
1154 ..
1155 }) = stmt
1156 {
1157 session
1158 .metrics()
1159 .subscribe_outputs(&[session_type, metrics::subscribe_output_label_value(output)])
1160 .inc();
1161 }
1162 let application_name = ApplicationNameHint::from_str(session.application_name());
1163 if let Some(labels) = metrics::as_of_query_label_values(session_type, application_name, stmt) {
1164 session.metrics().as_of_queries(&labels).inc();
1165 }
1166}
1167
1168fn terminates_elsewhere(response: &ExecuteResponse) -> bool {
1173 match response {
1174 ExecuteResponse::SendingRowsStreaming { .. }
1175 | ExecuteResponse::Subscribing { .. }
1176 | ExecuteResponse::Fetch { .. }
1177 | ExecuteResponse::CopyFrom { .. } => true,
1178 ExecuteResponse::CopyTo { resp, .. } => {
1181 !matches!(**resp, ExecuteResponse::SendingRowsImmediate { .. })
1182 }
1183 _ => false,
1184 }
1185}
1186
1187#[derive(Error, Debug)]
1189pub enum CollectionLookupError {
1190 #[error("instance does not exist: {0}")]
1192 InstanceMissing(ComputeInstanceId),
1193 #[error("the instance has shut down")]
1195 InstanceShutDown,
1196 #[error("collection does not exist: {0}")]
1198 CollectionMissing(GlobalId),
1199}
1200
1201impl From<InstanceMissing> for CollectionLookupError {
1202 fn from(error: InstanceMissing) -> Self {
1203 Self::InstanceMissing(error.0)
1204 }
1205}
1206
1207impl From<InstanceShutDown> for CollectionLookupError {
1208 fn from(_error: InstanceShutDown) -> Self {
1209 Self::InstanceShutDown
1210 }
1211}
1212
1213impl From<CollectionMissing> for CollectionLookupError {
1214 fn from(error: CollectionMissing) -> Self {
1215 Self::CollectionMissing(error.0)
1216 }
1217}
1218
1219impl From<AcquireReadHoldsError> for CollectionLookupError {
1220 fn from(error: AcquireReadHoldsError) -> Self {
1221 match error {
1222 AcquireReadHoldsError::CollectionMissing(id) => Self::CollectionMissing(id),
1223 AcquireReadHoldsError::InstanceShutDown => Self::InstanceShutDown,
1224 }
1225 }
1226}
1227
1228#[mz_ore::instrument(level = "debug")]
1230pub(crate) fn create_peek_response_stream(
1231 rows_rx: tokio::sync::oneshot::Receiver<PeekResponse>,
1232 finishing: RowSetFinishing,
1233 max_result_size: u64,
1234 max_returned_query_size: Option<u64>,
1235 duration_histogram: prometheus::Histogram,
1236 mut persist_client: mz_persist_client::PersistClient,
1237 peek_stash_read_batch_size_bytes: usize,
1238 peek_stash_read_memory_budget_bytes: usize,
1239) -> impl futures::Stream<Item = PeekResponseUnary> {
1240 async_stream::stream!({
1241 let result = rows_rx.await;
1242
1243 let rows = match result {
1244 Ok(rows) => rows,
1245 Err(e) => {
1246 yield PeekResponseUnary::Error(AdapterError::Unstructured(anyhow::anyhow!(e)));
1247 return;
1248 }
1249 };
1250
1251 match rows {
1252 PeekResponse::Rows(rows) => {
1253 let rows = RowCollection::merge_sorted(&rows, &finishing.order_by);
1254 match finishing.finish(
1255 rows,
1256 max_result_size,
1257 max_returned_query_size,
1258 &duration_histogram,
1259 ) {
1260 Ok((rows, _size_bytes)) => yield PeekResponseUnary::Rows(Box::new(rows)),
1261 Err(e) => {
1262 yield PeekResponseUnary::Error(AdapterError::Unstructured(
1263 anyhow::Error::msg(e),
1264 ))
1265 }
1266 }
1267 }
1268 PeekResponse::Stashed(response) => {
1269 let response = *response;
1270
1271 let shard_id = response.shard_id;
1272
1273 let mut batches = Vec::new();
1274 for proto_batch in response.batches.into_iter() {
1275 let batch =
1276 persist_client.batch_from_transmittable_batch(&shard_id, proto_batch);
1277
1278 batches.push(batch);
1279 }
1280 tracing::trace!(?batches, "stashed peek response");
1281
1282 let as_of = Antichain::from_elem(mz_repr::Timestamp::default());
1283 let read_schemas: Schemas<SourceData, ()> = Schemas {
1284 id: None,
1285 key: Arc::new(response.relation_desc.clone()),
1286 val: Arc::new(UnitSchema),
1287 };
1288
1289 let mut row_cursor = persist_client
1290 .read_batches_consolidated::<_, _, _, i64>(
1291 response.shard_id,
1292 as_of,
1293 read_schemas,
1294 batches,
1295 |_stats| true,
1296 peek_stash_read_memory_budget_bytes,
1297 )
1298 .await
1299 .expect("invalid usage");
1300
1301 let (tx, mut rx) = tokio::sync::mpsc::channel(1);
1321 mz_ore::task::spawn(|| "read_peek_batches", async move {
1322 for rows in response.inline_rows {
1332 let result = tx.send(rows).await;
1333 if result.is_err() {
1334 tracing::debug!("receiver went away");
1335 }
1336 }
1337
1338 let mut current_batch = Vec::new();
1339 let mut current_batch_size: usize = 0;
1340
1341 'outer: while let Some(rows) = row_cursor.next().await {
1342 for ((source_data, _val), _ts, diff) in rows {
1343 let row = source_data
1344 .0
1345 .expect("we are not sending errors on this code path");
1346
1347 let diff = usize::try_from(diff)
1348 .expect("peek responses cannot have negative diffs");
1349
1350 if diff > 0 {
1351 let diff = NonZeroUsize::new(diff).expect("checked to be non-zero");
1352 current_batch_size =
1353 current_batch_size.saturating_add(row.byte_len());
1354 current_batch.push((row, diff));
1355 }
1356
1357 if current_batch_size > peek_stash_read_batch_size_bytes {
1358 let result = tx
1364 .send(RowCollection::new(
1365 current_batch.drain(..).collect_vec(),
1366 &[],
1367 ))
1368 .await;
1369 if result.is_err() {
1370 tracing::debug!("receiver went away");
1371 break 'outer;
1374 }
1375
1376 current_batch_size = 0;
1377 }
1378 }
1379 }
1380
1381 if current_batch.len() > 0 {
1382 let result = tx.send(RowCollection::new(current_batch, &[])).await;
1383 if result.is_err() {
1384 tracing::debug!("receiver went away");
1385 }
1386 }
1387
1388 let batches = row_cursor.into_lease();
1389 tracing::trace!(?response.shard_id, "cleaning up batches of peek result");
1390 for batch in batches {
1391 batch.delete().await;
1392 }
1393 });
1394
1395 assert!(
1396 finishing.is_streamable(response.relation_desc.arity()),
1397 "can only get stashed responses when the finishing is streamable"
1398 );
1399
1400 tracing::trace!("query result is streamable!");
1401
1402 assert!(finishing.is_streamable(response.relation_desc.arity()));
1403 let mut incremental_finishing = RowSetFinishingIncremental::new(
1404 finishing.offset,
1405 finishing.limit,
1406 finishing.project,
1407 max_returned_query_size,
1408 );
1409
1410 let mut got_zero_rows = true;
1411 while let Some(rows) = rx.recv().await {
1412 got_zero_rows = false;
1413
1414 let result_rows = incremental_finishing.finish_incremental(
1415 rows,
1416 max_result_size,
1417 &duration_histogram,
1418 );
1419
1420 match result_rows {
1421 Ok(result_rows) => yield PeekResponseUnary::Rows(Box::new(result_rows)),
1422 Err(e) => {
1423 yield PeekResponseUnary::Error(AdapterError::Unstructured(
1424 anyhow::Error::msg(e),
1425 ))
1426 }
1427 }
1428 }
1429
1430 if got_zero_rows {
1433 let row_iter = vec![].into_row_iter();
1434 yield PeekResponseUnary::Rows(Box::new(row_iter));
1435 }
1436 }
1437 PeekResponse::Canceled => {
1438 yield PeekResponseUnary::Canceled;
1439 }
1440 PeekResponse::Error(e) => {
1441 yield PeekResponseUnary::Error(e.into());
1442 }
1443 }
1444 })
1445}
1446
1447#[cfg(test)]
1448mod tests {
1449 use std::sync::{Arc, Mutex};
1450
1451 use futures::{FutureExt, StreamExt};
1452 use mz_compute_client::controller::PeekNotification;
1453 use mz_compute_client::controller::peek_lifecycle::PeekLifecycle;
1454 use uuid::Uuid;
1455
1456 use super::{PeekCancelSafety, PeekHandle};
1457
1458 fn owned_peek() -> (PeekHandle, Arc<Mutex<Vec<PeekNotification>>>) {
1459 let outcomes = Arc::new(Mutex::new(Vec::new()));
1460 let retired = Arc::clone(&outcomes);
1461 let lifecycle = Arc::new(PeekLifecycle::new(move |outcome| {
1462 retired.lock().expect("test lock poisoned").push(outcome)
1463 }));
1464 (
1465 PeekHandle {
1466 uuid: Uuid::new_v4(),
1467 lifecycle,
1468 },
1469 outcomes,
1470 )
1471 }
1472
1473 #[mz_ore::test]
1474 fn unpolled_response_drop_retires_peek() {
1475 let (peek, outcomes) = owned_peek();
1476 let stream = peek.guard_stream(futures::stream::pending());
1477 drop(stream);
1478 assert_eq!(
1479 *outcomes.lock().expect("test lock poisoned"),
1480 vec![PeekNotification::Canceled]
1481 );
1482 }
1483
1484 #[mz_ore::test]
1485 fn pending_response_drop_retires_peek_once() {
1486 let (peek, outcomes) = owned_peek();
1487 let lifecycle = Arc::clone(&peek.lifecycle);
1488 let mut stream = Box::pin(peek.guard_stream(futures::stream::pending()));
1489 assert!(stream.next().now_or_never().is_none());
1490 drop(stream);
1491 lifecycle.complete(PeekNotification::Success {
1492 rows: 1,
1493 result_size: 8,
1494 });
1495 assert_eq!(
1496 *outcomes.lock().expect("test lock poisoned"),
1497 vec![PeekNotification::Canceled]
1498 );
1499 }
1500
1501 #[mz_ore::test(tokio::test)]
1502 async fn closed_instance_response_retires_error_before_stream_drop() {
1503 let (peek, outcomes) = owned_peek();
1504 let error = crate::AdapterError::Internal("instance stopped".into());
1505 let message = error.to_string();
1506 let mut stream =
1507 Box::pin(
1508 peek.guard_stream(futures::stream::iter([crate::PeekResponseUnary::Error(
1509 error,
1510 )])),
1511 );
1512 assert!(matches!(
1513 stream.next().await,
1514 Some(crate::PeekResponseUnary::Error(_))
1515 ));
1516 drop(stream);
1517 assert_eq!(
1518 *outcomes.lock().expect("test lock poisoned"),
1519 vec![PeekNotification::Error(message)]
1520 );
1521 }
1522
1523 #[mz_ore::test(tokio::test)]
1524 async fn finishing_error_does_not_overwrite_controller_retirement() {
1525 let (peek, outcomes) = owned_peek();
1526 let success = PeekNotification::Success {
1527 rows: 1,
1528 result_size: 8,
1529 };
1530 peek.lifecycle.complete(success.clone());
1531 let mut stream =
1532 Box::pin(
1533 peek.guard_stream(futures::stream::iter([crate::PeekResponseUnary::Error(
1534 crate::AdapterError::ResultSize("too large".into()),
1535 )])),
1536 );
1537 assert!(stream.next().await.is_some());
1538 drop(stream);
1539 assert_eq!(*outcomes.lock().expect("test lock poisoned"), vec![success]);
1540 }
1541
1542 #[mz_ore::test]
1543 fn dispatched_non_peek_side_effect_must_not_be_aborted() {
1544 let safety = PeekCancelSafety::new();
1545 assert!(safety.can_abort());
1546 safety.delegate_side_effect();
1547 assert!(!safety.can_abort());
1548 }
1549}