Skip to main content

mz_adapter/coord/
peek.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
10//! Logic and types for creating, executing, and tracking peeks.
11//!
12//! This module determines if a dataflow can be short-cut, by returning constant values
13//! or by reading out of existing arrangements, and implements the appropriate plan.
14
15use std::collections::BTreeSet;
16use std::fmt;
17use std::ops::Deref;
18use std::sync::Arc;
19
20use mz_adapter_types::connection::ConnectionId;
21use mz_cluster_client::ReplicaId;
22use mz_compute_client::controller::PeekNotification;
23use mz_compute_client::protocol::command::PeekTarget;
24use mz_compute_types::ComputeInstanceId;
25use mz_compute_types::dataflows::{DataflowDescription, IndexImport};
26use mz_expr::explain::{HumanizedExplain, HumanizerMode, fmt_text_constant_rows};
27use mz_expr::{
28    EvalError, Id, MirRelationExpr, MirScalarExpr, OptimizedMirRelationExpr, RowSetFinishing,
29    permutation_for_arrangement,
30};
31use mz_ore::cast::CastFrom;
32use mz_ore::soft_assert_eq_or_log;
33use mz_ore::str::{StrExt, separated};
34use mz_ore::task;
35use mz_repr::explain::text::DisplayText;
36use mz_repr::explain::{CompactScalars, IndexUsageType, PlanRenderingContext, UsedIndexes};
37use mz_repr::{
38    Diff, GlobalId, IntoRowIterator, RelationDesc, Row, RowIterator, SqlRelationType,
39    preserves_order,
40};
41use serde::{Deserialize, Serialize};
42use tokio::sync::oneshot;
43use tracing::{Instrument, Span};
44
45use crate::active_compute_sink::{ActiveComputeSink, ActiveCopyTo};
46use crate::catalog::Catalog;
47use crate::coord::timestamp_selection::TimestampDetermination;
48use crate::optimize::OptimizerError;
49use crate::peek_client::CoordinatorClient;
50use crate::statement_logging::StatementExecutionStrategy;
51use crate::statement_logging::WatchSetCreation;
52use crate::{AdapterError, ExecuteResponse, PeekClient};
53
54/// The response from a `Peek`, with row multiplicities represented in unary.
55///
56/// Note that each `Peek` expects to generate exactly one `PeekResponse`, i.e.
57/// we expect a 1:1 contract between `Peek` and `PeekResponseUnary`.
58#[derive(Debug)]
59pub enum PeekResponseUnary {
60    Rows(Box<dyn RowIterator + Send + Sync>),
61    Error(AdapterError),
62    Canceled,
63    /// A dependency was dropped during execution.
64    DependencyDropped(DroppedDependency),
65}
66
67/// A dependency that was dropped while a peek or subscribe was in flight.
68///
69/// The `name` fields hold the bare name (e.g. `db.schema.t` or `c`); `Display`
70/// applies SQL identifier quoting to produce `relation "db.schema.t"` or
71/// `cluster "c"` for direct use in error wording.
72#[derive(Clone, Debug)]
73pub enum DroppedDependency {
74    Relation { name: String },
75    Cluster { name: String },
76}
77
78impl fmt::Display for DroppedDependency {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        match self {
81            Self::Relation { name } => write!(f, "relation {}", name.quoted()),
82            Self::Cluster { name } => write!(f, "cluster {}", name.quoted()),
83        }
84    }
85}
86
87impl DroppedDependency {
88    /// User-facing error for a query (peek or subscribe) that could not finish
89    /// because this dependency was dropped mid-flight.
90    pub fn query_terminated_error(&self) -> String {
91        format!("query could not complete because {self} was dropped")
92    }
93
94    /// Convert this dropped dependency into an [`AdapterError::ConcurrentDependencyDrop`].
95    pub fn to_concurrent_dependency_drop(&self) -> AdapterError {
96        let (kind, name) = match self {
97            Self::Relation { name } => ("relation", name.clone()),
98            Self::Cluster { name } => ("cluster", name.clone()),
99        };
100        AdapterError::ConcurrentDependencyDrop {
101            dependency_kind: kind,
102            dependency_id: name,
103        }
104    }
105}
106
107#[derive(Clone, Debug)]
108pub struct PeekDataflowPlan {
109    pub(crate) desc: mz_compute_types::dataflows::LirDataflowDescription,
110    pub(crate) id: GlobalId,
111    key: Vec<MirScalarExpr>,
112    permutation: Vec<usize>,
113    thinned_arity: usize,
114}
115
116impl PeekDataflowPlan {
117    pub fn new(
118        desc: mz_compute_types::dataflows::LirDataflowDescription,
119        id: GlobalId,
120        typ: &SqlRelationType,
121    ) -> Self {
122        let arity = typ.arity();
123        let key = typ
124            .default_key()
125            .into_iter()
126            .map(MirScalarExpr::column)
127            .collect::<Vec<_>>();
128        let (permutation, thinning) = permutation_for_arrangement(&key, arity);
129        Self {
130            desc,
131            id,
132            key,
133            permutation,
134            thinned_arity: thinning.len(),
135        }
136    }
137}
138
139#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Ord, PartialOrd)]
140pub enum FastPathPlan {
141    /// The view evaluates to a constant result that can be returned.
142    ///
143    /// The [SqlRelationType] is unnecessary for evaluating the constant result but
144    /// may be helpful when printing out an explanation.
145    Constant(Result<Vec<(Row, Diff)>, EvalError>, SqlRelationType),
146    /// The view can be read out of an existing arrangement.
147    /// (coll_id, idx_id, values to look up, mfp to apply)
148    PeekExisting(GlobalId, GlobalId, Option<Vec<Row>>, mz_expr::SafeMfpPlan),
149    /// The view can be read directly out of Persist.
150    PeekPersist(GlobalId, Option<Row>, mz_expr::SafeMfpPlan),
151}
152
153impl<'a, T: 'a> DisplayText<PlanRenderingContext<'a, T>> for FastPathPlan {
154    fn fmt_text(
155        &self,
156        f: &mut fmt::Formatter<'_>,
157        ctx: &mut PlanRenderingContext<'a, T>,
158    ) -> fmt::Result {
159        if ctx.config.verbose_syntax {
160            self.fmt_verbose_text(f, ctx)
161        } else {
162            self.fmt_default_text(f, ctx)
163        }
164    }
165}
166
167impl FastPathPlan {
168    pub fn fmt_default_text<'a, T>(
169        &self,
170        f: &mut fmt::Formatter<'_>,
171        ctx: &mut PlanRenderingContext<'a, T>,
172    ) -> fmt::Result {
173        let mode = HumanizedExplain::new(ctx.config.redacted);
174
175        match self {
176            FastPathPlan::Constant(rows, _) => {
177                write!(f, "{}→Constant ", ctx.indent)?;
178
179                match rows {
180                    Ok(rows) => writeln!(f, "({} rows)", rows.len())?,
181                    Err(err) => {
182                        if mode.redacted() {
183                            writeln!(f, "(error: █)")?;
184                        } else {
185                            writeln!(f, "(error: {})", err.to_string().quoted(),)?;
186                        }
187                    }
188                }
189            }
190            FastPathPlan::PeekExisting(coll_id, idx_id, literal_constraints, mfp) => {
191                let coll = ctx
192                    .humanizer
193                    .humanize_id(*coll_id)
194                    .unwrap_or_else(|| coll_id.to_string());
195                let idx = ctx
196                    .humanizer
197                    .humanize_id(*idx_id)
198                    .unwrap_or_else(|| idx_id.to_string());
199                writeln!(f, "{}→Map/Filter/Project", ctx.indent)?;
200                ctx.indent.set();
201
202                ctx.indent += 1;
203
204                mode.expr(mfp.deref(), None).fmt_default_text(f, ctx)?;
205                let printed = !mfp.expressions.is_empty() || !mfp.predicates.is_empty();
206
207                if printed {
208                    ctx.indent += 1;
209                }
210                if let Some(literal_constraints) = literal_constraints {
211                    writeln!(f, "{}→Index Lookup on {coll} (using {idx})", ctx.indent)?;
212                    ctx.indent += 1;
213                    let values = separated("; ", mode.seq(literal_constraints, None));
214                    writeln!(f, "{}Lookup values: {values}", ctx.indent)?;
215                } else {
216                    writeln!(f, "{}→Indexed {coll} (using {idx})", ctx.indent)?;
217                }
218
219                ctx.indent.reset();
220            }
221            FastPathPlan::PeekPersist(global_id, literal_constraint, mfp) => {
222                let coll = ctx
223                    .humanizer
224                    .humanize_id(*global_id)
225                    .unwrap_or_else(|| global_id.to_string());
226                writeln!(f, "{}→Map/Filter/Project", ctx.indent)?;
227                ctx.indent.set();
228
229                ctx.indent += 1;
230
231                mode.expr(mfp.deref(), None).fmt_default_text(f, ctx)?;
232                let printed = !mfp.expressions.is_empty() || !mfp.predicates.is_empty();
233
234                if printed {
235                    ctx.indent += 1;
236                }
237                if let Some(literal_constraint) = literal_constraint {
238                    writeln!(f, "{}→ReadStorage Lookup on {coll}", ctx.indent)?;
239                    ctx.indent += 1;
240                    let value = mode.expr(literal_constraint, None);
241                    writeln!(f, "{}Lookup value: {value}", ctx.indent)?;
242                } else {
243                    writeln!(f, "{}→ReadStorage {coll}", ctx.indent)?;
244                }
245
246                ctx.indent.reset();
247            }
248        }
249
250        Ok(())
251    }
252
253    pub fn fmt_verbose_text<'a, T>(
254        &self,
255        f: &mut fmt::Formatter<'_>,
256        ctx: &mut PlanRenderingContext<'a, T>,
257    ) -> fmt::Result {
258        let redacted = ctx.config.redacted;
259        let mode = HumanizedExplain::new(redacted);
260
261        // TODO(aalexandrov): factor out common PeekExisting and PeekPersist
262        // code.
263        match self {
264            FastPathPlan::Constant(Ok(rows), _) => {
265                if !rows.is_empty() {
266                    writeln!(f, "{}Constant", ctx.indent)?;
267                    *ctx.as_mut() += 1;
268                    fmt_text_constant_rows(
269                        f,
270                        rows.iter().map(|(row, diff)| (row, diff)),
271                        ctx.as_mut(),
272                        redacted,
273                    )?;
274                    *ctx.as_mut() -= 1;
275                } else {
276                    writeln!(f, "{}Constant <empty>", ctx.as_mut())?;
277                }
278                Ok(())
279            }
280            FastPathPlan::Constant(Err(err), _) => {
281                if redacted {
282                    writeln!(f, "{}Error █", ctx.as_mut())
283                } else {
284                    writeln!(f, "{}Error {}", ctx.as_mut(), err.to_string().escaped())
285                }
286            }
287            FastPathPlan::PeekExisting(coll_id, idx_id, literal_constraints, mfp) => {
288                ctx.as_mut().set();
289                let (map, filter, project) = mfp.as_map_filter_project();
290
291                let cols = if !ctx.config.humanized_exprs {
292                    None
293                } else if let Some(cols) = ctx.humanizer.column_names_for_id(*idx_id) {
294                    // FIXME: account for thinning and permutation
295                    // See mz_expr::permutation_for_arrangement
296                    // See permute_oneshot_mfp_around_index
297                    let cols = itertools::chain(
298                        cols.iter().cloned(),
299                        std::iter::repeat(String::new()).take(map.len()),
300                    )
301                    .collect();
302                    Some(cols)
303                } else {
304                    None
305                };
306
307                if project.len() != mfp.input_arity + map.len()
308                    || !project.iter().enumerate().all(|(i, o)| i == *o)
309                {
310                    let outputs = mode.seq(&project, cols.as_ref());
311                    let outputs = CompactScalars(outputs);
312                    writeln!(f, "{}Project ({})", ctx.as_mut(), outputs)?;
313                    *ctx.as_mut() += 1;
314                }
315                if !filter.is_empty() {
316                    let predicates = separated(" AND ", mode.seq(&filter, cols.as_ref()));
317                    writeln!(f, "{}Filter {}", ctx.as_mut(), predicates)?;
318                    *ctx.as_mut() += 1;
319                }
320                if !map.is_empty() {
321                    let scalars = mode.seq(&map, cols.as_ref());
322                    let scalars = CompactScalars(scalars);
323                    writeln!(f, "{}Map ({})", ctx.as_mut(), scalars)?;
324                    *ctx.as_mut() += 1;
325                }
326                MirRelationExpr::fmt_indexed_filter(
327                    f,
328                    ctx,
329                    coll_id,
330                    idx_id,
331                    literal_constraints.clone(),
332                    None,
333                )?;
334                writeln!(f)?;
335                ctx.as_mut().reset();
336                Ok(())
337            }
338            FastPathPlan::PeekPersist(gid, literal_constraint, mfp) => {
339                ctx.as_mut().set();
340                let (map, filter, project) = mfp.as_map_filter_project();
341
342                let cols = if !ctx.config.humanized_exprs {
343                    None
344                } else if let Some(cols) = ctx.humanizer.column_names_for_id(*gid) {
345                    let cols = itertools::chain(
346                        cols.iter().cloned(),
347                        std::iter::repeat(String::new()).take(map.len()),
348                    )
349                    .collect::<Vec<_>>();
350                    Some(cols)
351                } else {
352                    None
353                };
354
355                if project.len() != mfp.input_arity + map.len()
356                    || !project.iter().enumerate().all(|(i, o)| i == *o)
357                {
358                    let outputs = mode.seq(&project, cols.as_ref());
359                    let outputs = CompactScalars(outputs);
360                    writeln!(f, "{}Project ({})", ctx.as_mut(), outputs)?;
361                    *ctx.as_mut() += 1;
362                }
363                if !filter.is_empty() {
364                    let predicates = separated(" AND ", mode.seq(&filter, cols.as_ref()));
365                    writeln!(f, "{}Filter {}", ctx.as_mut(), predicates)?;
366                    *ctx.as_mut() += 1;
367                }
368                if !map.is_empty() {
369                    let scalars = mode.seq(&map, cols.as_ref());
370                    let scalars = CompactScalars(scalars);
371                    writeln!(f, "{}Map ({})", ctx.as_mut(), scalars)?;
372                    *ctx.as_mut() += 1;
373                }
374                let human_id = ctx
375                    .humanizer
376                    .humanize_id(*gid)
377                    .unwrap_or_else(|| gid.to_string());
378                write!(f, "{}PeekPersist {human_id}", ctx.as_mut())?;
379                if let Some(literal) = literal_constraint {
380                    let value = mode.expr(literal, None);
381                    writeln!(f, " [value={}]", value)?;
382                } else {
383                    writeln!(f, "")?;
384                }
385                ctx.as_mut().reset();
386                Ok(())
387            }
388        }?;
389        Ok(())
390    }
391}
392
393/// Possible ways in which the coordinator could produce the result for a goal view.
394#[derive(Clone, Debug)]
395pub enum PeekPlan {
396    FastPath(FastPathPlan),
397    /// The view must be installed as a dataflow and then read.
398    SlowPath(PeekDataflowPlan),
399}
400
401/// Convert `mfp` to an executable, non-temporal plan.
402/// It should be non-temporal, as OneShot preparation populates `mz_now`.
403///
404/// If the `mfp` can't be converted into a non-temporal plan, this returns an _internal_ error.
405fn mfp_to_safe_plan(
406    mfp: mz_expr::MapFilterProject,
407) -> Result<mz_expr::SafeMfpPlan, OptimizerError> {
408    mfp.into_plan()
409        .map_err(OptimizerError::InternalUnsafeMfpPlan)?
410        .into_nontemporal()
411        .map_err(|e| OptimizerError::InternalUnsafeMfpPlan(format!("{:?}", e)))
412}
413
414/// If it can't convert `mfp` into a `SafeMfpPlan`, this returns an _internal_ error.
415fn permute_oneshot_mfp_around_index(
416    mfp: mz_expr::MapFilterProject,
417    key: &[MirScalarExpr],
418) -> Result<mz_expr::SafeMfpPlan, OptimizerError> {
419    let input_arity = mfp.input_arity;
420    let mut safe_mfp = mfp_to_safe_plan(mfp)?;
421    let (permute, thinning) = permutation_for_arrangement(key, input_arity);
422    safe_mfp.permute_fn(|c| permute[c], key.len() + thinning.len());
423    Ok(safe_mfp)
424}
425
426/// Determine if the dataflow plan can be implemented without an actual dataflow.
427///
428/// If the optimized plan is a `Constant` or a `Get` of a maintained arrangement,
429/// we can avoid building a dataflow (and either just return the results, or peek
430/// out of the arrangement, respectively).
431pub fn create_fast_path_plan(
432    dataflow_plan: &mut DataflowDescription<OptimizedMirRelationExpr>,
433    view_id: GlobalId,
434    finishing: Option<&RowSetFinishing>,
435    persist_fast_path_limit: usize,
436    persist_fast_path_order: bool,
437) -> Result<Option<FastPathPlan>, OptimizerError> {
438    // At this point, `dataflow_plan` contains our best optimized dataflow.
439    // We will check the plan to see if there is a fast path to escape full dataflow construction.
440
441    // We need to restrict ourselves to settings where the inserted transient view is the first thing
442    // to build (no dependent views). There is likely an index to build as well, but we may not be sure.
443    if dataflow_plan.objects_to_build.len() >= 1 && dataflow_plan.objects_to_build[0].id == view_id
444    {
445        let mut mir = &*dataflow_plan.objects_to_build[0].plan.as_inner_mut();
446        if let Some((rows, found_typ)) = mir.as_const() {
447            // In the case of a constant, we can return the result now.
448            let plan = FastPathPlan::Constant(
449                rows.clone(),
450                mz_repr::SqlRelationType::from_repr(found_typ),
451            );
452            return Ok(Some(plan));
453        } else {
454            // If there is a TopK that would be completely covered by the finishing, then jump
455            // through the TopK.
456            if let MirRelationExpr::TopK {
457                input,
458                group_key,
459                order_key,
460                limit,
461                offset,
462                monotonic: _,
463                expected_group_size: _,
464            } = mir
465            {
466                if let Some(finishing) = finishing {
467                    if group_key.is_empty() && *order_key == finishing.order_by && *offset == 0 {
468                        // The following is roughly `limit >= finishing.limit + finishing.offset`,
469                        // but with Options.
470                        let finishing_limits_at_least_as_topk = match (limit, finishing.limit) {
471                            (None, _) => true,
472                            (Some(..), None) => false,
473                            (Some(topk_limit), Some(finishing_limit)) => {
474                                if let Some(l) = topk_limit.as_literal_int64() {
475                                    i128::cast_from(l)
476                                        >= i128::cast_from(*finishing_limit)
477                                            + i128::cast_from(finishing.offset)
478                                } else {
479                                    false
480                                }
481                            }
482                        };
483                        if finishing_limits_at_least_as_topk {
484                            mir = input;
485                        }
486                    }
487                }
488            }
489            // In the case of a linear operator around an indexed view, we
490            // can skip creating a dataflow and instead pull all the rows in
491            // index and apply the linear operator against them.
492            let (mfp, mir) = mz_expr::MapFilterProject::extract_from_expression(mir);
493            match mir {
494                MirRelationExpr::Get {
495                    id: Id::Global(get_id),
496                    typ: repr_typ,
497                    ..
498                } => {
499                    // Just grab any arrangement if an arrangement exists
500                    for (index_id, IndexImport { desc, .. }) in dataflow_plan.index_imports.iter() {
501                        if desc.on_id == *get_id {
502                            return Ok(Some(FastPathPlan::PeekExisting(
503                                *get_id,
504                                *index_id,
505                                None,
506                                permute_oneshot_mfp_around_index(mfp, &desc.key)?,
507                            )));
508                        }
509                    }
510
511                    // If there is no arrangement, consider peeking the persist shard directly.
512                    // Generally, we consider a persist peek when the query can definitely be satisfied
513                    // by scanning through a small, constant number of Persist key-values.
514                    let safe_mfp = mfp_to_safe_plan(mfp)?;
515                    let (_maps, filters, projection) = safe_mfp.as_map_filter_project();
516
517                    let persist_fast_path_order_relation_typ = if persist_fast_path_order {
518                        Some(
519                            dataflow_plan
520                                .source_imports
521                                .get(get_id)
522                                .expect("Get's ID is also imported")
523                                .desc
524                                .typ
525                                .clone(),
526                        )
527                    } else {
528                        None
529                    };
530
531                    let literal_constraint =
532                        if let Some(relation_typ) = &persist_fast_path_order_relation_typ {
533                            let mut row = Row::default();
534                            let mut packer = row.packer();
535                            for (idx, col) in relation_typ.column_types.iter().enumerate() {
536                                if !preserves_order(&col.scalar_type) {
537                                    break;
538                                }
539                                let col_expr = MirScalarExpr::column(idx);
540
541                                let Some((literal, _)) = filters
542                                    .iter()
543                                    .filter_map(|f| f.expr_eq_literal(&col_expr))
544                                    .next()
545                                else {
546                                    break;
547                                };
548                                packer.extend_by_row(&literal);
549                            }
550                            if row.is_empty() { None } else { Some(row) }
551                        } else {
552                            None
553                        };
554
555                    let finish_ok = match &finishing {
556                        None => false,
557                        Some(RowSetFinishing {
558                            order_by,
559                            limit,
560                            offset,
561                            ..
562                        }) => {
563                            let order_ok =
564                                if let Some(relation_typ) = &persist_fast_path_order_relation_typ {
565                                    order_by.iter().enumerate().all(|(idx, order)| {
566                                        // Map the ordering column back to the column in the source data.
567                                        // (If it's not one of the input columns, we can't make any guarantees.)
568                                        let column_idx = projection[order.column];
569                                        if column_idx >= safe_mfp.input_arity {
570                                            return false;
571                                        }
572                                        let column_type = &relation_typ.column_types[column_idx];
573                                        let index_ok = idx == column_idx;
574                                        let nulls_ok = !column_type.nullable || order.nulls_last;
575                                        let asc_ok = !order.desc;
576                                        let type_ok = preserves_order(&column_type.scalar_type);
577                                        index_ok && nulls_ok && asc_ok && type_ok
578                                    })
579                                } else {
580                                    order_by.is_empty()
581                                };
582                            let limit_ok = limit.map_or(false, |l| {
583                                usize::cast_from(l) + *offset < persist_fast_path_limit
584                            });
585                            order_ok && limit_ok
586                        }
587                    };
588
589                    let key_constraint = if let Some(literal) = &literal_constraint {
590                        let prefix_len = literal.iter().count();
591                        repr_typ
592                            .keys
593                            .iter()
594                            .any(|k| k.iter().all(|idx| *idx < prefix_len))
595                    } else {
596                        false
597                    };
598
599                    // We can generate a persist peek when:
600                    // - We have a literal constraint that includes an entire key (so we'll return at most one value)
601                    // - We can return the first N key values (no filters, small limit, consistent order)
602                    if key_constraint || (filters.is_empty() && finish_ok) {
603                        return Ok(Some(FastPathPlan::PeekPersist(
604                            *get_id,
605                            literal_constraint,
606                            safe_mfp,
607                        )));
608                    }
609                }
610                MirRelationExpr::Join { implementation, .. } => {
611                    if let mz_expr::JoinImplementation::IndexedFilter(coll_id, idx_id, key, vals) =
612                        implementation
613                    {
614                        return Ok(Some(FastPathPlan::PeekExisting(
615                            *coll_id,
616                            *idx_id,
617                            Some(vals.clone()),
618                            permute_oneshot_mfp_around_index(mfp, key)?,
619                        )));
620                    }
621                }
622                // nothing can be done for non-trivial expressions.
623                _ => {}
624            }
625        }
626    }
627    Ok(None)
628}
629
630impl FastPathPlan {
631    pub fn used_indexes(&self, finishing: Option<&RowSetFinishing>) -> UsedIndexes {
632        match self {
633            FastPathPlan::Constant(..) => UsedIndexes::default(),
634            FastPathPlan::PeekExisting(_coll_id, idx_id, literal_constraints, _mfp) => {
635                if literal_constraints.is_some() {
636                    UsedIndexes::new([(*idx_id, vec![IndexUsageType::Lookup(*idx_id)])].into())
637                } else if finishing.map_or(false, |f| f.limit.is_some() && f.order_by.is_empty()) {
638                    UsedIndexes::new([(*idx_id, vec![IndexUsageType::FastPathLimit])].into())
639                } else {
640                    UsedIndexes::new([(*idx_id, vec![IndexUsageType::FullScan])].into())
641                }
642            }
643            FastPathPlan::PeekPersist(..) => UsedIndexes::default(),
644        }
645    }
646}
647
648impl crate::coord::Coordinator {
649    /// Creates the transient dataflow for a slow-path peek and acquires the peek's read hold.
650    ///
651    /// On error, nothing stays installed. On success, the caller must drop the returned
652    /// collection, after queuing any peek on it, to release the dataflow's implied holds.
653    fn create_transient_peek_target(
654        &mut self,
655        plan: PeekDataflowPlan,
656        source_arity: usize,
657        compute_instance: ComputeInstanceId,
658    ) -> Result<
659        (
660            GlobalId,
661            mz_storage_types::read_holds::ReadHold,
662            mz_expr::SafeMfpPlan,
663        ),
664        AdapterError,
665    > {
666        let PeekDataflowPlan {
667            desc: dataflow,
668            id: index_id,
669            key: index_key,
670            permutation: index_permutation,
671            thinned_arity: index_thinned_arity,
672        } = plan;
673        // The peek's hold protects only index_id. Multiple exports would leave
674        // other outputs without equivalent protection during teardown.
675        let exports: Vec<GlobalId> = dataflow.export_ids().collect();
676        soft_assert_eq_or_log!(
677            exports.as_slice(),
678            &[index_id],
679            "slow-path peek dataflow must export exactly [index_id]",
680        );
681        if exports.as_slice() != [index_id] {
682            return Err(AdapterError::internal(
683                "peek error",
684                format!("slow-path peek dataflow exports {exports:?}, expected [{index_id}]"),
685            ));
686        }
687
688        let mut mfp = mz_expr::MapFilterProject::new(source_arity);
689        mfp.permute_fn(
690            |c| index_permutation[c],
691            index_key.len() + index_thinned_arity,
692        );
693        let mfp = mfp_to_safe_plan(mfp)?;
694
695        self.controller
696            .compute
697            .create_dataflow(compute_instance, dataflow, None)
698            .map_err(AdapterError::concurrent_dependency_drop_from_dataflow_creation_error)?;
699        // The new collection's implied hold pins since at as_of until we can
700        // acquire the peek's hold. Failed acquisition must drop that collection.
701        match self
702            .controller
703            .compute
704            .acquire_read_hold(compute_instance, index_id)
705        {
706            Ok(read_hold) => Ok((index_id, read_hold, mfp)),
707            Err(error) => {
708                self.drop_compute_collections(vec![(compute_instance, index_id)]);
709                Err(AdapterError::concurrent_dependency_drop_from_collection_update_error(error))
710            }
711        }
712    }
713
714    /// Returns a [`PeekClient`] for coordinator-owned queries, which have to
715    /// run off the main loop because the client calls back into it.
716    ///
717    /// The client holds no session [`Client`](crate::Client), so it does not
718    /// keep the coordinator alive.
719    pub(crate) fn background_peek_client(&self, catalog: &Arc<Catalog>) -> PeekClient {
720        let build_version = catalog.state().config().build_info.human_version(None);
721        PeekClient::new(
722            CoordinatorClient::Background {
723                tx: self.internal_cmd_tx.clone(),
724                metrics: self.metrics.clone(),
725            },
726            self.peek_registry
727                .connection(crate::session::DUMMY_CONNECTION_ID),
728            catalog,
729            Arc::clone(&self.controller.storage_collections),
730            Arc::clone(&self.transient_id_gen),
731            self.optimizer_metrics.clone(),
732            self.persist_client.clone(),
733            self.statement_logging.create_frontend(build_version),
734            Arc::clone(&self.occ_write_semaphore),
735            self.group_commit_tx.clone(),
736            self.controller.read_only(),
737        )
738    }
739
740    /// Implements a slow-path peek: ships its transient dataflow and peeks the
741    /// dataflow's index. This is called from the command handler for
742    /// `ExecuteSlowPathPeek`.
743    ///
744    /// `peek`'s lifecycle ends the statement's logging on every path, including
745    /// an error return.
746    pub(crate) fn implement_slow_path_peek(
747        &mut self,
748        peek: crate::peek_client::PeekHandle,
749        dataflow_plan: PeekDataflowPlan,
750        determination: TimestampDetermination,
751        finishing: RowSetFinishing,
752        compute_instance: ComputeInstanceId,
753        target_replica: Option<ReplicaId>,
754        intermediate_result_type: SqlRelationType,
755        conn_id: ConnectionId,
756        max_result_size: u64,
757        max_query_result_size: Option<u64>,
758        watch_set: Option<WatchSetCreation>,
759    ) -> Result<ExecuteResponse, AdapterError> {
760        let issue = || {
761            if let Some(ws) = watch_set {
762                self.install_peek_watch_sets(conn_id, ws)
763                    .map_err(AdapterError::concurrent_dependency_drop_from_compute_lookup_error)?;
764            }
765
766            let (index_id, read_hold, map_filter_project) = self.create_transient_peek_target(
767                dataflow_plan,
768                intermediate_result_type.arity(),
769                compute_instance,
770            )?;
771
772            // At this stage we don't know column names for the result because we
773            // only know the peek's result type as a bare SqlRelationType.
774            let peek_result_column_names =
775                (0..intermediate_result_type.arity()).map(|i| format!("peek_{i}"));
776            let peek_result_desc =
777                RelationDesc::new(intermediate_result_type, peek_result_column_names);
778
779            let (rows_tx, rows_rx) = tokio::sync::oneshot::channel();
780            let issued = self.controller.compute.peek(
781                compute_instance,
782                PeekTarget::Index { id: index_id },
783                None,
784                peek.uuid,
785                determination.timestamp_context.timestamp_or_default(),
786                peek_result_desc,
787                finishing.clone(),
788                map_filter_project,
789                read_hold,
790                target_replica,
791                rows_tx,
792                Some(Arc::clone(&peek.lifecycle)),
793            );
794
795            // Drop the dataflow now that the peek is queued. This is required:
796            // `add_collection` installs implied/warmup holds owned by the controller
797            // and only released via `drop_collections`, so without this call the
798            // transient dataflow's `since` would stay pinned at `as_of` forever. The
799            // peek's own read hold keeps the collection alive on the cluster until
800            // the response arrives. This also cleans up when the peek fails to
801            // issue or its lifecycle is already retired.
802            self.drop_compute_collections(vec![(compute_instance, index_id)]);
803
804            issued.map_err(AdapterError::concurrent_dependency_drop_from_peek_error)?;
805            Ok::<_, AdapterError>(rows_rx)
806        };
807        let rows_rx = match issue() {
808            Ok(rows_rx) => rows_rx,
809            Err(error) => {
810                peek.lifecycle
811                    .complete(PeekNotification::Error(error.to_string()));
812                return Err(error);
813            }
814        };
815
816        let dyncfgs = self.catalog().system_config().dyncfgs();
817        let peek_response_stream = crate::peek_client::create_peek_response_stream(
818            rows_rx,
819            finishing,
820            max_result_size,
821            max_query_result_size,
822            self.metrics.row_set_finishing_seconds(),
823            self.persist_client.clone(),
824            mz_compute_types::dyncfgs::PEEK_RESPONSE_STASH_READ_BATCH_SIZE_BYTES.get(dyncfgs),
825            mz_compute_types::dyncfgs::PEEK_RESPONSE_STASH_READ_MEMORY_BUDGET_BYTES.get(dyncfgs),
826        );
827
828        Ok(crate::ExecuteResponse::SendingRowsStreaming {
829            rows: Box::pin(peek.guard_stream(peek_response_stream)),
830            instance_id: compute_instance,
831            strategy: StatementExecutionStrategy::Standard,
832        })
833    }
834
835    /// Implements a `COPY TO` command by installing peek watch sets,
836    /// shipping the dataflow, and spawning a background task to wait for completion.
837    /// This is called from the command handler for ExecuteCopyTo.
838    ///
839    /// (The S3 preflight check must be completed successfully via the
840    /// `CopyToPreflight` command _before_ calling this method. The preflight is
841    /// handled separately to avoid blocking the coordinator's main task with
842    /// slow S3 network operations.)
843    ///
844    /// This method does NOT block waiting for completion. Instead, it spawns a background task that
845    /// will send the response through the provided tx channel when the COPY TO completes.
846    /// All errors (setup or execution) are sent through tx.
847    pub(crate) async fn implement_copy_to(
848        &mut self,
849        df_desc: mz_compute_types::dataflows::LirDataflowDescription,
850        compute_instance: ComputeInstanceId,
851        target_replica: Option<ReplicaId>,
852        source_ids: BTreeSet<GlobalId>,
853        conn_id: ConnectionId,
854        watch_set: Option<WatchSetCreation>,
855        tx: oneshot::Sender<Result<ExecuteResponse, AdapterError>>,
856    ) {
857        // Helper to send error and return early
858        let send_err = |tx: oneshot::Sender<Result<ExecuteResponse, AdapterError>>,
859                        e: AdapterError| {
860            let _ = tx.send(Err(e));
861        };
862
863        // Install watch sets for statement lifecycle logging if enabled.
864        // If this fails, we just send the error back. The frontend will handle logging
865        // for the error case (no ExecuteContextExtra is created here).
866        if let Some(ws) = watch_set {
867            if let Err(e) = self.install_peek_watch_sets(conn_id.clone(), ws) {
868                let err = AdapterError::concurrent_dependency_drop_from_compute_lookup_error(e);
869                send_err(tx, err);
870                return;
871            }
872        }
873
874        // Note: We don't create an ExecuteContextExtra here because the frontend handles
875        // all statement logging for COPY TO operations.
876
877        let sink_id = df_desc.sink_id();
878
879        // Create and register ActiveCopyTo.
880        // Note: sink_tx/sink_rx is the channel for the compute sink to notify completion
881        // This is different from the command's tx which sends the response to the client
882        let (sink_tx, sink_rx) = oneshot::channel();
883        let active_copy_to = ActiveCopyTo {
884            conn_id: conn_id.clone(),
885            tx: sink_tx,
886            cluster_id: compute_instance,
887            depends_on: source_ids,
888        };
889
890        // Add metadata for the new COPY TO. CopyTo returns a `ready` future, so it is safe to drop.
891        drop(self.add_active_compute_sink(sink_id, ActiveComputeSink::CopyTo(active_copy_to)));
892
893        // Try to ship the dataflow. We handle errors gracefully because dependencies might have
894        // disappeared during sequencing.
895        if let Err(e) = self
896            .try_ship_dataflow(df_desc, compute_instance, target_replica)
897            .await
898            .map_err(AdapterError::concurrent_dependency_drop_from_dataflow_creation_error)
899        {
900            // Clean up the active compute sink that was added above, since the dataflow was never
901            // created. If we don't do this, the sink_id remains in drop_sinks but no collection
902            // exists in the compute controller, causing a panic when the connection terminates.
903            self.remove_active_compute_sink(sink_id).await;
904            send_err(tx, e);
905            return;
906        }
907
908        // Spawn background task to wait for completion
909        // We must NOT await sink_rx here directly, as that would block the coordinator's main task
910        // from processing the completion message. Instead, we spawn a background task that will
911        // send the result through tx when the COPY TO completes.
912        let span = Span::current();
913        task::spawn(
914            || "copy to completion",
915            async move {
916                let res = sink_rx.await;
917                let result = match res {
918                    Ok(res) => res,
919                    Err(_) => Err(AdapterError::Internal("copy to sender dropped".into())),
920                };
921
922                let _ = tx.send(result);
923            }
924            .instrument(span),
925        );
926    }
927
928    /// Constructs an [`ExecuteResponse`] that that will send some rows to the
929    /// client immediately, as opposed to asking the dataflow layer to send along
930    /// the rows after some computation.
931    pub(crate) fn send_immediate_rows<I>(rows: I) -> ExecuteResponse
932    where
933        I: IntoRowIterator,
934        I::Iter: Send + Sync + 'static,
935    {
936        let rows = Box::new(rows.into_row_iter());
937        ExecuteResponse::SendingRowsImmediate { rows }
938    }
939}
940
941#[cfg(test)]
942mod tests {
943    use std::collections::BTreeMap;
944
945    use mz_expr::func::IsNull;
946    use mz_expr::{MapFilterProject, UnaryFunc};
947    use mz_ore::str::Indent;
948    use mz_repr::explain::text::text_string_at;
949    use mz_repr::explain::{DummyHumanizer, ExplainConfig, PlanRenderingContext};
950    use mz_repr::{Datum, SqlColumnType, SqlScalarType};
951
952    use super::*;
953
954    #[mz_ore::test]
955    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
956    fn test_fast_path_plan_as_text() {
957        let typ = SqlRelationType::new(vec![SqlColumnType {
958            scalar_type: SqlScalarType::String,
959            nullable: false,
960        }]);
961        let constant_err = FastPathPlan::Constant(Err(EvalError::DivisionByZero), typ.clone());
962        let no_lookup = FastPathPlan::PeekExisting(
963            GlobalId::User(8),
964            GlobalId::User(10),
965            None,
966            MapFilterProject::new(4)
967                .map(Some(MirScalarExpr::column(0).or(MirScalarExpr::column(2))))
968                .project([1, 4])
969                .into_plan()
970                .expect("invalid plan")
971                .into_nontemporal()
972                .expect("invalid nontemporal"),
973        );
974        let lookup = FastPathPlan::PeekExisting(
975            GlobalId::User(9),
976            GlobalId::User(11),
977            Some(vec![Row::pack(Some(Datum::Int32(5)))]),
978            MapFilterProject::new(3)
979                .filter(Some(
980                    MirScalarExpr::column(0).call_unary(UnaryFunc::IsNull(IsNull)),
981                ))
982                .into_plan()
983                .expect("invalid plan")
984                .into_nontemporal()
985                .expect("invalid nontemporal"),
986        );
987
988        let humanizer = DummyHumanizer;
989        let config = ExplainConfig {
990            redacted: false,
991            verbose_syntax: true,
992            ..Default::default()
993        };
994        let ctx_gen = || {
995            let indent = Indent::default();
996            let annotations = BTreeMap::new();
997            PlanRenderingContext::<FastPathPlan>::new(
998                indent,
999                &humanizer,
1000                annotations,
1001                &config,
1002                BTreeSet::default(),
1003            )
1004        };
1005
1006        let constant_err_exp = "Error \"division by zero\"\n";
1007        let no_lookup_exp = "Project (#1, #4)\n  Map ((#0 OR #2))\n    ReadIndex on=u8 [DELETED INDEX]=[*** full scan ***]\n";
1008        let lookup_exp =
1009            "Filter (#0) IS NULL\n  ReadIndex on=u9 [DELETED INDEX]=[lookup value=(5)]\n";
1010
1011        assert_eq!(text_string_at(&constant_err, ctx_gen), constant_err_exp);
1012        assert_eq!(text_string_at(&no_lookup, ctx_gen), no_lookup_exp);
1013        assert_eq!(text_string_at(&lookup, ctx_gen), lookup_exp);
1014
1015        let mut constant_rows = vec![
1016            (Row::pack(Some(Datum::String("hello"))), Diff::ONE),
1017            (Row::pack(Some(Datum::String("world"))), 2.into()),
1018            (Row::pack(Some(Datum::String("star"))), 500.into()),
1019        ];
1020        let constant_exp1 =
1021            "Constant\n  - (\"hello\")\n  - ((\"world\") x 2)\n  - ((\"star\") x 500)\n";
1022        assert_eq!(
1023            text_string_at(
1024                &FastPathPlan::Constant(Ok(constant_rows.clone()), typ.clone()),
1025                ctx_gen
1026            ),
1027            constant_exp1
1028        );
1029        constant_rows
1030            .extend((0..20).map(|i| (Row::pack(Some(Datum::String(&i.to_string()))), Diff::ONE)));
1031        let constant_exp2 = "Constant\n  total_rows (diffs absed): 523\n  first_rows:\n    - (\"hello\")\
1032        \n    - ((\"world\") x 2)\n    - ((\"star\") x 500)\n    - (\"0\")\n    - (\"1\")\
1033        \n    - (\"2\")\n    - (\"3\")\n    - (\"4\")\n    - (\"5\")\n    - (\"6\")\
1034        \n    - (\"7\")\n    - (\"8\")\n    - (\"9\")\n    - (\"10\")\n    - (\"11\")\
1035        \n    - (\"12\")\n    - (\"13\")\n    - (\"14\")\n    - (\"15\")\n    - (\"16\")\n";
1036        assert_eq!(
1037            text_string_at(&FastPathPlan::Constant(Ok(constant_rows), typ), ctx_gen),
1038            constant_exp2
1039        );
1040    }
1041}