Skip to main content

mz_adapter/
peek_client.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::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
67/// Storage collections trait alias we need to consult for since/frontiers.
68pub type StorageCollectionsHandle =
69    Arc<dyn mz_storage_client::storage_collections::StorageCollections + Send + Sync>;
70
71/// Clients needed for peek sequencing in the Adapter Frontend.
72#[derive(Debug, Clone)]
73pub struct PeekClient {
74    /// The peek partition of the connection this client serves.
75    connection_peeks: Arc<ConnectionPeeks>,
76    coordinator_client: CoordinatorClient,
77    /// Cache of the latest catalog snapshot. Serves
78    /// [`PeekClient::catalog_snapshot`] without a Coordinator round-trip
79    /// while the catalog's transient revision is unchanged.
80    ///
81    /// Holds a `Weak` so that an idle session does not keep a superseded
82    /// catalog version alive.
83    catalog_cache: Weak<Catalog>,
84    /// Channels to talk to each compute Instance task directly. Lazily populated.
85    /// Note that these are never cleaned up. In theory, this could lead to a very slow memory leak
86    /// if a long-running user session keeps peeking on clusters that are being created and dropped
87    /// in a hot loop. Hopefully this won't occur any time soon.
88    compute_instances: BTreeMap<ComputeInstanceId, InstanceClient>,
89    /// Handle to storage collections for reading frontiers and policies.
90    pub storage_collections: StorageCollectionsHandle,
91    /// A generator for transient `GlobalId`s, shared with Coordinator.
92    pub transient_id_gen: Arc<TransientIdGen>,
93    pub optimizer_metrics: OptimizerMetrics,
94    /// Per-timeline oracles from the coordinator. Lazily populated.
95    oracles: BTreeMap<Timeline, Arc<dyn TimestampOracle<Timestamp> + Send + Sync>>,
96    persist_client: PersistClient,
97    /// Statement logging state for frontend peek sequencing.
98    pub statement_logging_frontend: StatementLoggingFrontend,
99    /// Semaphore for limiting concurrent OCC (optimistic concurrency control) write operations.
100    pub occ_write_semaphore: Arc<Semaphore>,
101    /// Requests a group commit. Used to advance the write timeline when we
102    /// need the oracle to move but have nothing to write ourselves.
103    pub(crate) group_commit_notifier: GroupCommitNotifier,
104    /// Whether the coordinator is in read-only mode. Mutations must be rejected.
105    pub read_only: bool,
106}
107
108/// A command sender that does not make background work keep the coordinator alive.
109#[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    /// Sends a command, dropping it if the coordinator is gone.
120    ///
121    /// A session cannot outrun the coordinator: it holds a `Client`, and the
122    /// coordinator's loop only exits once every client is dropped, so a failed
123    /// send there is a real bug. Background work holds no client on purpose, so
124    /// losing the race with shutdown is normal and must not crash the process.
125    /// Dropping the command closes its response channel, which the caller handles
126    /// as an error.
127    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    /// Registers a peek with the connection's partition and creates its
165    /// lifecycle.
166    ///
167    /// The lifecycle takes over the statement's end of execution from `logging`
168    /// on every path, including the errors this returns.
169    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                    // Not `catalog_snapshot`, for the reason `background_peek`
226                    // gives: a background client may race the coordinator's
227                    // shutdown.
228                    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    /// Creates a PeekClient.
266    ///
267    /// `catalog` seeds the catalog snapshot cache, so that the session's
268    /// first statements don't need a `Command::CatalogSnapshot` round-trip.
269    #[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(), // lazily populated
288            storage_collections,
289            transient_id_gen,
290            optimizer_metrics,
291            statement_logging_frontend,
292            oracles: Default::default(), // lazily populated
293            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    /// Fetch a snapshot of the catalog.
338    ///
339    /// Serves from the session-side cache when the catalog's transient
340    /// revision is unchanged since the cached snapshot was taken (see
341    /// [`Catalog::transient_revision_is_current`]). An unchanged revision
342    /// means the cached snapshot is identical to what a fresh fetch would
343    /// return. Otherwise falls back to a `Command::CatalogSnapshot`
344    /// round-trip and re-populates the cache.
345    ///
346    /// Cache misses record the round-trip time in the adapter metrics,
347    /// labeled by `context`. Hits and misses are counted in
348    /// `catalog_snapshot_cache`.
349    pub async fn catalog_snapshot(&mut self, context: &str) -> Arc<Catalog> {
350        // NOTE: The upgrade can fail even when the revision is unchanged: any
351        // in-place mutation of the Coordinator's catalog (including
352        // revision-preserving ones) moves it to a new allocation, and the
353        // cached allocation is freed once its last user drops. We then fall
354        // through to a refetch.
355        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        // The cache is empty, stale, or its allocation is gone: do the
369        // round-trip.
370        let start = std::time::Instant::now();
371        // Session clients keep the coordinator loop alive. A dropped response
372        // here therefore indicates an internal lifecycle bug, unlike a
373        // background compute lookup racing coordinator shutdown.
374        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    /// Calls the coordinator and returns an error if it drops the response.
392    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    /// Adds the `emit_timestamp_notice` notice to `session`: the explanation of
402    /// `determination`, the timestamp of a statement that reads `id_bundle`.
403    ///
404    /// Skips the notice if a collection in `id_bundle` was dropped since the
405    /// timestamp was determined: the statement does not depend on the notice,
406    /// so it goes on without it.
407    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        // Test-only synchronization point: parks the statement before the
415        // coordinator looks up the frontiers of `id_bundle`, so a test can drop
416        // one of its collections in between.
417        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    /// The client for sending commands to the coordinator.
435    pub(crate) fn coordinator_client(&self) -> &CoordinatorClient {
436        &self.coordinator_client
437    }
438
439    /// Acquire read holds on the given compute/storage collections, and
440    /// determine the smallest common valid write frontier among the specified collections.
441    ///
442    /// Similar to `Coordinator::acquire_read_holds` and `TimestampProvider::least_valid_write`
443    /// combined.
444    ///
445    /// Note: Unlike the Coordinator/StorageController's `least_valid_write` that treats sinks
446    /// specially when fetching storage frontiers (see `mz_storage_controller::collections_frontiers`),
447    /// we intentionally do not special‑case sinks here because peeks never read from sinks.
448    /// Therefore, using `StorageCollections::collections_frontiers` is sufficient.
449    ///
450    /// Note: self is taken &mut because of the lazy fetching in `get_compute_instance_client`.
451    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    /// Implement a fast-path peek plan.
502    /// The slow-path counterpart is `Coordinator::implement_slow_path_peek`.
503    ///
504    /// Note: self is taken &mut because of the lazy fetching in `get_compute_instance_client`.
505    ///
506    /// Note: `input_read_holds` has holds for all inputs. For fast-path peeks, this includes the
507    /// peek target. For slow-path peeks (to be implemented later), we'll need to additionally call
508    /// into the Controller to acquire a hold on the peek target after we create the dataflow.
509    ///
510    /// Constant peeks leave retirement with the caller. Streaming peeks transfer
511    /// it to a frontend lifecycle shared with compute and cancellation.
512    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 the dataflow optimizes to a constant expression, we can immediately return the result.
534        if let FastPathPlan::Constant(rows_res, _) = fast_path {
535            // For constant queries with statement logging, immediately log that
536            // dependencies are "ready" (trivially, because there are none).
537            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                        // No need to retain 0 diffs.
571                    }
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                // TODO(peek-seq): make this a structured error.
583                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                // FastPathPlan::Constant handled above.
631                unreachable!()
632            }
633        };
634
635        let (rows_tx, rows_rx) = oneshot::channel();
636
637        // At this stage we don't know column names for the result because we
638        // only know the peek's result type as a bare SqlRelationType.
639        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        // Test-only synchronization point: parks a peek between registration
672        // and issue, so a test can land a concurrent DROP CLUSTER in this
673        // window. Used by
674        // workflow_test_drop_cluster_during_registered_peeks_fast_path.
675        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    /// Begins a new statement execution log entry, sampling permitting.
723    ///
724    /// Only [`ExecutionLogging::take_over`] may call this: an entry that exists
725    /// without the session task owning its end would stay unfinished forever.
726    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    /// Log cluster selection for a statement.
750    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    /// Log timestamp determination for a statement.
762    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    /// Log transient index ID for a statement.
769    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    /// Returns the watch set that reports when the dependencies of a logged
780    /// statement have caught up to its timestamp. Returns `None` if they
781    /// already have, after recording that.
782    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        // The determination's upper is not beyond any input's write frontier.
790        // Once every input is complete at the timestamp, the statement no
791        // longer waits for anything, whatever the frontiers of the
792        // collections that those inputs are derived from.
793        //
794        // NOTE: `respond_immediately` is true for every read without a
795        // timestamp. Such a read still waits for its inputs' frontiers to
796        // become empty, which is what comparing against the maximum timestamp
797        // checks.
798        let timestamp = determination.timestamp_context.timestamp_or_default();
799        if !determination.upper.less_equal(&timestamp) {
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    /// Log a statement lifecycle event.
814    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/// Owns cleanup while sequencing and while the returned response is in flight.
827#[derive(Debug)]
828pub struct PeekHandle {
829    pub(crate) uuid: Uuid,
830    pub(crate) lifecycle: Arc<PeekLifecycle>,
831}
832
833/// Dropping read-only sequencing is safe. An unrelated coordinator-owned
834/// side effect must instead produce its definitive result once dispatched.
835pub(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                // Instance shutdown can close the response channel without a
864                // controller notification. Finishing errors after a normal
865                // completion cannot change the already-retired outcome.
866                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/// RAII guard owning a frontend statement-logging lifecycle.
882///
883/// Unless logging responsibility is handed off via
884/// [`defuse`](StatementLoggingGuard::defuse), the guard ensures that every
885/// statement whose beginning was logged also has its end logged, even on early-return, panic, or mid-flight
886/// drop of the enclosing future: if the guard is dropped without being defused,
887/// it emits `StatementEndedExecutionReason::Aborted`.
888///
889/// When the guard is `defuse`d, some other component (e.g. the protocol layer,
890/// for subscribe responses) takes over and logs the end itself.
891///
892/// For non-sampled statements the guard still exists but carries no id, and
893/// retirement / drop are no-ops.
894#[must_use = "StatementLoggingGuard must be explicitly retired or handed off; \
895              otherwise `Drop` will log the statement as Aborted"]
896struct StatementLoggingGuard {
897    /// `None` if the statement was not sampled for logging.
898    id: Option<StatementLoggingId>,
899    log: Arc<StatementLog>,
900    now: mz_ore::now::NowFn,
901}
902
903impl StatementLoggingGuard {
904    /// Arms a guard for the obligation the coordinator armed for `outer`, the
905    /// statement whose execution the one we are about to run serves.
906    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    /// Returns the logging id, if this statement is being logged.
915    fn id(&self) -> Option<StatementLoggingId> {
916        self.id
917    }
918
919    /// Retires the guard with an explicit end-execution reason.
920    /// A no-op if the guard was defused or the statement is not sampled.
921    fn retire(mut self, reason: statement_logging::StatementEndedExecutionReason) {
922        self.emit(reason);
923    }
924
925    /// Turns the obligation back into its transferable form, disarming this
926    /// guard.
927    fn release(mut self) -> ExecuteContextExtra {
928        ExecuteContextExtra::new(self.id.take())
929    }
930
931    /// Hands off logging responsibility without emitting an end-execution
932    /// event. Call this at the point where another component takes over
933    /// end-of-execution logging. Afterwards the guard is inert.
934    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        // `emit` is a no-op if the guard was already retired or defused (i.e.
950        // `id` is `None`).
951        self.emit(statement_logging::StatementEndedExecutionReason::Aborted);
952    }
953}
954
955/// The session task's slot for the end-of-execution obligation of the statement
956/// it is running. One slot is held for the whole `SessionClient::execute` call
957/// and the session task retires it at exactly one site.
958///
959/// An empty slot means no log entry exists for this execution, so a fallback to
960/// the coordinator lets it begin its own. An occupied slot means the session
961/// task owes an end event: [`Self::retire`] pays it, [`Self::release`] transfers
962/// it to the coordinator, [`Self::hand_off`] transfers it to a peek lifecycle.
963/// [`Self::id`] returning `None` covers both "not sampled" and "the end is
964/// logged elsewhere", which want identical treatment everywhere.
965pub(crate) struct ExecutionLogging {
966    guard: Option<StatementLoggingGuard>,
967    /// Whether [`Self::hand_off`] moved the guard out. A log entry exists then,
968    /// although `guard` is empty.
969    handed_off: bool,
970    /// Whether the coordinator must not run this statement, because the session
971    /// task has already counted it in the metrics `Coordinator::handle_execute`
972    /// maintains. Handing it over afterwards would count it twice.
973    coordinator_must_not_run: bool,
974}
975
976/// Which statement the session task is taking the log entry over for.
977pub(crate) enum TakeOver {
978    /// The statement that will run here, so the coordinator must not run it.
979    StatementToRun,
980    /// A SQL `EXECUTE` that unrolls into an inner statement, for a session task
981    /// that will go on to run that inner statement.
982    ///
983    /// The entry stays armed, so a failure to unroll is recorded against the
984    /// `EXECUTE`. Only the `EXECUTE` itself is counted here. The inner
985    /// statement is a statement in its own right and is counted wherever it
986    /// ends up running, exactly as the coordinator does when it re-dispatches a
987    /// `Plan::Execute`, which is why the slot stays releasable.
988    UnrolledExecute,
989}
990
991impl ExecutionLogging {
992    /// Adopts the end-of-execution obligation of an outer statement (a FETCH or
993    /// an EXECUTE running its inner statement), or starts out empty when there
994    /// is no outer statement.
995    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    /// Returns the logging id, if an end event is owed and the statement is
1004    /// being logged.
1005    pub(crate) fn id(&self) -> Option<StatementLoggingId> {
1006        self.guard.as_ref().and_then(|guard| guard.id())
1007    }
1008
1009    /// Records that the session task, not the coordinator, is executing `stmt`.
1010    /// Bumps the counters `Coordinator::handle_execute` would have bumped and
1011    /// makes sure a log entry exists, inheriting the adopted one if there is
1012    /// one. `stmt` is `None` for an empty portal, which is logged but not
1013    /// counted.
1014    ///
1015    /// For [`TakeOver::StatementToRun`], every exit after this call must produce
1016    /// an outcome for the statement: the coordinator will not see it.
1017    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    /// Makes sure a log entry exists for this execution, keeping an adopted one
1044    /// if there is one.
1045    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    /// Hands the obligation to the coordinator, which retires it once the
1066    /// statement it dispatches finishes. `None` tells the coordinator to begin
1067    /// its own entry, `Some` with no id inside tells it that an entry already
1068    /// exists or that sampling declined.
1069    #[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    /// Emits the end event for `result`, if we still owe one.
1084    pub(crate) fn retire(self, result: &Result<ExecuteResponse, AdapterError>) {
1085        let Some(guard) = self.guard else {
1086            return;
1087        };
1088        // A defused or released slot owes no end event. Bail before mapping
1089        // `result` to an end reason, which soft-panics for the responses whose
1090        // end is logged elsewhere.
1091        if guard.id().is_none() {
1092            return;
1093        }
1094        guard.retire(end_reason(result));
1095    }
1096
1097    /// Leaves the slot inert, for dispatch sites that hand the end of execution
1098    /// to the protocol layer (subscribes).
1099    pub(crate) fn defuse(&mut self) {
1100        if let Some(guard) = self.guard.as_mut() {
1101            guard.defuse();
1102        }
1103    }
1104
1105    /// Moves the end-of-execution obligation into the returned guard, for a
1106    /// peek whose lifecycle logs the end. Afterwards the slot behaves as after
1107    /// [`Self::defuse`]. Returns `None` if no log entry exists.
1108    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
1115/// Maps an execution outcome to the reason to record for it.
1116///
1117/// The responses whose end is logged elsewhere are filtered out first: their
1118/// `StatementEndedExecutionReason` conversion panics, and this runs for every
1119/// statement the session task executes, so that panic would take down the
1120/// connection.
1121fn 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
1136/// Bumps `query_total`, as `Coordinator::handle_execute` does for the statements
1137/// it sequences, `subscribe_outputs` for a subscribe, and `as_of_queries` for an
1138/// `AS OF` query.
1139///
1140/// `stmt` is `None` for an empty portal, which is logged but not counted. The
1141/// coordinator skips it the same way.
1142fn 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
1168/// Whether someone else logs the end of execution for `response`: the
1169/// peek lifecycle, the protocol layer for a subscribe, a
1170/// FETCH or a COPY FROM. The dispatch sites that produce these defuse the slot,
1171/// so an armed slot alongside one of them means a dispatch site did not.
1172fn terminates_elsewhere(response: &ExecuteResponse) -> bool {
1173    match response {
1174        ExecuteResponse::SendingRowsStreaming { .. }
1175        | ExecuteResponse::Subscribing { .. }
1176        | ExecuteResponse::Fetch { .. }
1177        | ExecuteResponse::CopyFrom { .. } => true,
1178        // COPY TO STDOUT of an immediate result terminates here. Anything else
1179        // it can wrap does not.
1180        ExecuteResponse::CopyTo { resp, .. } => {
1181            !matches!(**resp, ExecuteResponse::SendingRowsImmediate { .. })
1182        }
1183        _ => false,
1184    }
1185}
1186
1187/// Errors arising during collection lookup in peek client operations.
1188#[derive(Error, Debug)]
1189pub enum CollectionLookupError {
1190    /// The specified compute instance does not exist.
1191    #[error("instance does not exist: {0}")]
1192    InstanceMissing(ComputeInstanceId),
1193    /// The specified compute instance has shut down.
1194    #[error("the instance has shut down")]
1195    InstanceShutDown,
1196    /// The compute collection does not exist.
1197    #[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/// Creates an async stream that processes peek responses and yields rows.
1229#[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                // NOTE: Using the cursor creates Futures that are not Sync,
1302                // while `ExecuteResponse::SendingRowsStreaming` needs a Sync
1303                // stream, so a spawned task drives them. The task has the
1304                // additional benefit that we get to delete batches once we're
1305                // done.
1306                //
1307                // Batch deletion is best-effort, though, and there are
1308                // multiple known ways in which they can leak, among them:
1309                //
1310                // - ProtoBatch is lost in flight
1311                // - ProtoBatch is lost because when combining PeekResponse
1312                // from workers a cancellation or error "overrides" other
1313                // results, meaning we drop them
1314                // - This task here is not run to completion before it can
1315                // delete all batches
1316                //
1317                // This is semi-ok, because persist needs a reaper of leaked
1318                // batches already, and so we piggy-back on that, even if it
1319                // might not exist as of today.
1320                let (tx, mut rx) = tokio::sync::mpsc::channel(1);
1321                mz_ore::task::spawn(|| "read_peek_batches", async move {
1322                    // We always send our inline rows first. Ordering
1323                    // doesn't matter because we can only be in this case
1324                    // when there is no ORDER BY.
1325                    //
1326                    // We _could_ write these out as a Batch, and include it
1327                    // in the batches we read via the Consolidator. If we
1328                    // wanted to get a consistent ordering. That's not
1329                    // needed for correctness! But might be nice for more
1330                    // aesthetic reasons.
1331                    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                                // We're re-encoding the rows as a RowCollection
1359                                // here, for which we pay in CPU time. We're in a
1360                                // slow path already, since we're returning a big
1361                                // stashed result so this is worth the convenience
1362                                // of that for now.
1363                                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                                    // Don't return but break so we fall out to the
1372                                    // batch delete logic below.
1373                                    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                // Even when there's zero rows, clients still expect an
1431                // empty PeekResponse.
1432                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}