mz_compute_types/plan/lowering.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//! Lowering [`DataflowDescription`]s from MIR ([`MirRelationExpr`]) to LIR ([`LirRelationExpr`]).
11
12use std::collections::{BTreeMap, BTreeSet};
13
14use columnar::Len;
15use itertools::Itertools;
16use mz_expr::JoinImplementation::{DeltaQuery, Differential, IndexedFilter, Unimplemented};
17use mz_expr::{
18 AggregateExpr, Columns, Id, JoinInputMapper, MapFilterProject, MfpPlan, MirRelationExpr,
19 MirScalarExpr, OptimizedMirRelationExpr, SafeMfpPlan, TableFunc, permutation_for_arrangement,
20};
21use mz_ore::{assert_none, soft_assert_eq_or_log, soft_panic_or_log};
22use mz_repr::optimize::OptimizerFeatures;
23use mz_repr::{GlobalId, Timestamp};
24
25use crate::dataflows::{BuildDesc, DataflowDescription, IndexImport};
26use crate::plan::join::{DeltaJoinPlan, JoinPlan, LinearJoinPlan};
27use crate::plan::reduce::{KeyValPlan, ReducePlan};
28use crate::plan::scalar::{
29 LirScalarExpr, lses_from_mses, mfp_mir_to_lir, mfp_mir_to_lir_plan, mfp_plan_mir_to_lir,
30};
31use crate::plan::threshold::ThresholdPlan;
32use crate::plan::top_k::TopKPlan;
33use crate::plan::{
34 ArrangementStrategy, AvailableCollections, GetPlan, LirId, LirRelationExpr, LirRelationNode,
35 LoweringMetrics,
36};
37
38/// Pick an [`ArrangementStrategy`] based on whether the input may contain future-stamped
39/// updates. Future updates are the only case where temporal bucketing pays off.
40///
41/// Any arrangement or consolidation that absorbs data that can have future updates should be
42/// guarded by a temporal bucketing operator.
43fn strategy_from_future(has_future_updates: bool) -> ArrangementStrategy {
44 if has_future_updates {
45 ArrangementStrategy::TemporalBucketing
46 } else {
47 ArrangementStrategy::Direct
48 }
49}
50
51/// The result of lowering a [`MirRelationExpr`] to a [`LirRelationExpr`].
52struct LoweredExpr {
53 /// The lowered plan.
54 plan: LirRelationExpr,
55 /// The arrangement keys that the plan is certain to produce.
56 keys: AvailableCollections,
57 /// Whether the plan's output may contain updates at future timestamps,
58 /// e.g., from a temporal MFP using `mz_now()`.
59 has_future_updates: bool,
60}
61
62pub(super) struct Context {
63 /// Known bindings to (possibly arranged) collections.
64 arrangements: BTreeMap<Id, AvailableCollections>,
65 /// Ids whose collections may contain updates at future timestamps,
66 /// e.g., from a temporal MFP using `mz_now()`.
67 has_future_updates: BTreeSet<Id>,
68 /// Tracks the next available `LirId`.
69 next_lir_id: LirId,
70 /// Information to print along with error messages.
71 debug_info: LirDebugInfo,
72 /// Whether to enable fusion of MFPs in reductions.
73 enable_reduce_mfp_fusion: bool,
74 /// Metrics recorded during lowering, if any are being collected.
75 metrics: Option<LoweringMetrics>,
76 /// Whether the current expression is subject to single-time (one-shot
77 /// `SELECT`) monotonic operator selection.
78 ///
79 /// Lowering locks in which arrangements a node makes available, and that set
80 /// changes with the chosen operator variant (e.g. a monotonic `TopK`/`Reduce`
81 /// arranges differently than its non-monotonic form). So the variant must be
82 /// picked here, during lowering, rather than by a later rewrite that would
83 /// leave the already-computed `AvailableCollections` describing the wrong shape.
84 ///
85 /// Initialized from the dataflow's `is_single_time()` and forced to `false`
86 /// while lowering the recursive bindings of a `LetRec`, whose values are not
87 /// restricted to a single time.
88 single_time: bool,
89 /// Global ids of the dataflow's source imports.
90 source_imports: BTreeSet<GlobalId>,
91 /// MIR `MfpPlan`s pushed onto `Get::Collection` reads of source imports,
92 /// keyed by the `Get`'s `LirId`.
93 ///
94 /// `refine_source_mfps` identifies common parts across sibling reads and pushes the
95 /// common part into the shared source MFP. That pass runs on MIR because
96 /// only MIR can utter the `mz_now()` predicates that temporal bounds fold
97 /// into. Retaining the MIR form here lets it find common parts without
98 /// round-tripping the LIR plans back through MIR.
99 source_get_mfps: BTreeMap<LirId, MfpPlan<MirScalarExpr>>,
100}
101
102impl Context {
103 pub fn new(
104 debug_name: String,
105 features: &OptimizerFeatures,
106 metrics: Option<&LoweringMetrics>,
107 ) -> Self {
108 Self {
109 arrangements: Default::default(),
110 has_future_updates: Default::default(),
111 next_lir_id: LirId(1),
112 debug_info: LirDebugInfo {
113 debug_name,
114 id: GlobalId::Transient(0),
115 },
116 enable_reduce_mfp_fusion: features.enable_reduce_mfp_fusion,
117 metrics: metrics.cloned(),
118 // Set from the dataflow in `lower` before any expression is lowered.
119 single_time: false,
120 source_imports: Default::default(),
121 source_get_mfps: Default::default(),
122 }
123 }
124
125 fn allocate_lir_id(&mut self) -> LirId {
126 let id = self.next_lir_id;
127 self.next_lir_id = LirId(
128 self.next_lir_id
129 .0
130 .checked_add(1)
131 .expect("No LirId overflow"),
132 );
133 id
134 }
135
136 pub fn lower(
137 mut self,
138 desc: DataflowDescription<OptimizedMirRelationExpr>,
139 ) -> Result<DataflowDescription<LirRelationExpr>, String> {
140 // Sources might provide arranged forms of their data, in the future.
141 // Indexes provide arranged forms of their data.
142 for IndexImport {
143 desc: index_desc,
144 typ,
145 ..
146 } in desc.index_imports.values()
147 {
148 let key = lses_from_mses(&index_desc.key);
149 // TODO[btv] - We should be told the permutation by
150 // `index_desc`, and it should have been generated
151 // at the same point the thinning logic was.
152 //
153 // We should for sure do that soon, but it requires
154 // a bit of a refactor, so for now we just
155 // _assume_ that they were both generated by `permutation_for_arrangement`,
156 // and recover it here.
157 let (permutation, thinning) = permutation_for_arrangement(&key, typ.arity());
158 let index_keys = self
159 .arrangements
160 .entry(Id::Global(index_desc.on_id))
161 .or_insert_with(AvailableCollections::default);
162 index_keys.arranged.push((key, permutation, thinning));
163 }
164 for id in desc.source_imports.keys() {
165 self.arrangements
166 .entry(Id::Global(*id))
167 .or_insert_with(AvailableCollections::new_raw);
168 self.source_imports.insert(*id);
169 }
170
171 // One-shot `SELECT` dataflows run at a single time, which lets us select
172 // monotonic operator variants during lowering (see the `TopK` and `Reduce`
173 // arms), so that `AvailableCollections` reflect the final operator variant.
174 self.single_time = desc.is_single_time();
175
176 // Build each object in order, registering the arrangements it forms.
177 let mut objects_to_build = Vec::with_capacity(desc.objects_to_build.len());
178 for build in desc.objects_to_build {
179 self.debug_info.id = build.id;
180 let LoweredExpr {
181 plan,
182 keys,
183 has_future_updates,
184 } = self.lower_mir_expr(&build.plan)?;
185
186 self.arrangements.insert(Id::Global(build.id), keys);
187 if has_future_updates {
188 self.has_future_updates.insert(Id::Global(build.id));
189 }
190 objects_to_build.push(BuildDesc { id: build.id, plan });
191 }
192
193 let mut dataflow = DataflowDescription {
194 source_imports: desc.source_imports,
195 index_imports: desc.index_imports,
196 objects_to_build,
197 index_exports: desc.index_exports,
198 sink_exports: desc.sink_exports,
199 as_of: desc.as_of,
200 until: desc.until,
201 initial_storage_as_of: desc.initial_storage_as_of,
202 refresh_schedule: desc.refresh_schedule,
203 debug_name: desc.debug_name,
204 time_dependence: desc.time_dependence,
205 };
206
207 // Refining: identify the common parts in the MFPs pushed onto a
208 // source's reads and hoist the shared prefix into the source itself.
209 self.refine_source_mfps(&mut dataflow);
210
211 Ok(dataflow)
212 }
213
214 /// Identifies common parts of the `MapFilterProject`s pushed onto sibling `Get::Collection`
215 /// reads of each imported source, hoisting the shared prefix into the
216 /// source's own MFP.
217 ///
218 /// The reads' MFPs are lowering artifacts (MIR sees only `Get(GlobalId)`),
219 /// so this belongs in lowering. We run on MIR because only MIR can
220 /// utter the `mz_now()` predicates that temporal bounds fold into, so it
221 /// consumes the MIR `MfpPlan`s stashed in [`Self::source_get_mfps`] rather
222 /// than round-tripping the lowered LIR plans back through MIR.
223 fn refine_source_mfps(&mut self, dataflow: &mut DataflowDescription<LirRelationExpr>) {
224 for (source_id, source_import) in dataflow.source_imports.iter_mut() {
225 let source = &mut source_import.desc;
226 let source_id = *source_id;
227 let mut identity_present = false;
228
229 // Collect the MIR `MfpPlan`s pushed onto this source's
230 // `Get::Collection` reads. Folding their temporal bounds back into
231 // `mz_now()` predicates (`into_map_filter_project`) lets
232 // `extract_common`'s column remapping apply uniformly across the
233 // whole MFP. Also note identity reads, which block pushdown.
234 let mut taken: Vec<(LirId, MapFilterProject<MirScalarExpr>)> = Vec::new();
235 for build_desc in dataflow.objects_to_build.iter() {
236 let mut todo = vec![&build_desc.plan];
237 while let Some(expression) = todo.pop() {
238 let node = &expression.node;
239 if let LirRelationNode::Get { id, plan, .. } = node {
240 if *id == Id::Global(source_id) {
241 match plan {
242 GetPlan::Collection(_) => {
243 let mir_plan = self
244 .source_get_mfps
245 .remove(&expression.lir_id)
246 .expect("stashed MIR MfpPlan for source Get::Collection");
247 taken.push((
248 expression.lir_id,
249 mir_plan.into_map_filter_project(),
250 ));
251 }
252 GetPlan::PassArrangements => {
253 identity_present = true;
254 }
255 GetPlan::Arrangement(..) => {
256 panic!("Surprising `GetPlan` for imported source: {:?}", plan);
257 }
258 }
259 }
260 } else {
261 todo.extend(node.children());
262 }
263 }
264 }
265
266 // Direct exports of sources are possible, and prevent pushdown.
267 identity_present |= dataflow
268 .index_exports
269 .values()
270 .any(|(x, _)| x.on_id == source_id);
271 identity_present |= dataflow.sink_exports.values().any(|x| x.from == source_id);
272
273 if identity_present || taken.is_empty() {
274 // Nothing to push down. The reads already carry their final LIR
275 // MFPs, so leave them untouched.
276 continue;
277 }
278
279 // Extract the common prefix and push it into the source's MFP.
280 let mut mfp_refs: Vec<&mut MapFilterProject<MirScalarExpr>> =
281 taken.iter_mut().map(|(_, mfp)| mfp).collect();
282 let common = MapFilterProject::extract_common(&mut mfp_refs[..]);
283 let mut source_mfp = if let Some(mfp) = source.arguments.operators.take() {
284 MapFilterProject::compose(mfp, common)
285 } else {
286 common
287 };
288 source_mfp.optimize();
289 source.arguments.operators = Some(source_mfp);
290
291 // Convert each residual MFP back to an LIR `MfpPlan` once, and
292 // install it on the corresponding read by `LirId`.
293 let replacements: BTreeMap<LirId, MfpPlan<LirScalarExpr>> = taken
294 .into_iter()
295 .map(|(lir_id, mir_mfp)| (lir_id, mfp_mir_to_lir_plan(mir_mfp)))
296 .collect();
297
298 for build_desc in dataflow.objects_to_build.iter_mut() {
299 let mut todo = vec![&mut build_desc.plan];
300 while let Some(expression) = todo.pop() {
301 if let Some(replacement) = replacements.get(&expression.lir_id) {
302 if let LirRelationNode::Get {
303 plan: GetPlan::Collection(mfp_plan),
304 ..
305 } = &mut expression.node
306 {
307 *mfp_plan = replacement.clone();
308 } else {
309 panic!(
310 "LirId {:?} was a GetPlan::Collection but is now {:?}",
311 expression.lir_id, expression.node
312 );
313 }
314 }
315 todo.extend(expression.node.children_mut());
316 }
317 }
318 }
319 }
320
321 /// This method converts a MirRelationExpr into a plan that can be directly rendered.
322 ///
323 /// The rough structure is that we repeatedly extract map/filter/project operators
324 /// from each expression we see, bundle them up as a `MapFilterProject` object, and
325 /// then produce a plan for the combination of that with the next operator.
326 ///
327 /// The method accesses `self.arrangements`, which it will locally add to and remove from for
328 /// `Let` bindings (by the end of the call it should contain the same bindings as when it
329 /// started).
330 ///
331 /// The result of the method is both a `LirRelationExpr`, but also a list of arrangements that
332 /// are certain to be produced, which can be relied on by the next steps in the plan.
333 /// Each of the arrangement keys is associated with an MFP that must be applied if that
334 /// arrangement is used, to back out the permutation associated with that arrangement.
335 ///
336 /// An empty list of arrangement keys indicates that only a `Collection` stream can
337 /// be assumed to exist.
338 fn lower_mir_expr(&mut self, expr: &MirRelationExpr) -> Result<LoweredExpr, String> {
339 // This function is recursive and can overflow its stack, so grow it if
340 // needed. The growth here is unbounded. Our general solution for this problem
341 // is to use [`ore::stack::RecursionGuard`] to additionally limit the stack
342 // depth. That however requires upstream error handling. This function is
343 // currently called by the Coordinator after calls to `catalog_transact`,
344 // and thus are not allowed to fail. Until that allows errors, we choose
345 // to allow the unbounded growth here. We are though somewhat protected by
346 // higher levels enforcing their own limits on stack depth (in the parser,
347 // transformer/desugarer, and planner).
348 mz_ore::stack::maybe_grow(|| self.lower_mir_expr_stack_safe(expr))
349 }
350
351 fn lower_mir_expr_stack_safe(&mut self, expr: &MirRelationExpr) -> Result<LoweredExpr, String> {
352 // Extract a maximally large MapFilterProject from `expr`.
353 // We will then try and push this in to the resulting expression.
354 //
355 // Importantly, `mfp` may contain temporal operators and not be a "safe" MFP.
356 // While we would eventually like all plan stages to be able to absorb such
357 // general operators, not all of them can.
358 let (mut mfp, expr) = MapFilterProject::extract_from_expression(expr);
359 // We attempt to plan what we have remaining, in the context of `mfp`.
360 // We may not be able to do this, and must wrap some operators with a `Mfp` stage.
361 let LoweredExpr {
362 mut plan,
363 mut keys,
364 mut has_future_updates,
365 } = match expr {
366 // These operators should have been extracted from the expression.
367 MirRelationExpr::Map { .. } => {
368 panic!("This operator should have been extracted");
369 }
370 MirRelationExpr::Filter { .. } => {
371 panic!("This operator should have been extracted");
372 }
373 MirRelationExpr::Project { .. } => {
374 panic!("This operator should have been extracted");
375 }
376 // These operators may not have been extracted, and need to result in a `LirRelationExpr`.
377 MirRelationExpr::Constant { rows, typ: _ } => {
378 let lir_id = self.allocate_lir_id();
379 let node = LirRelationNode::Constant {
380 rows: rows.clone().map(|rows| {
381 rows.into_iter()
382 .map(|(row, diff)| (row, Timestamp::MIN, diff))
383 .collect()
384 }),
385 };
386 // The plan, not arranged in any way.
387 LoweredExpr {
388 plan: node.as_plan(lir_id),
389 keys: AvailableCollections::new_raw(),
390 has_future_updates: false,
391 }
392 }
393 MirRelationExpr::Get { id, typ: _, .. } => {
394 // This stage can absorb arbitrary MFP operators.
395 let mut mfp = mfp.take();
396 // If `mfp` is the identity, we can surface all imported arrangements.
397 // Otherwise, we apply `mfp` and promise no arrangements.
398 let mut in_keys = self
399 .arrangements
400 .get(id)
401 .cloned()
402 .unwrap_or_else(AvailableCollections::new_raw);
403
404 // Seek out an arrangement key that might be constrained to a literal.
405 // Note: this code has very little use nowadays, as its job was mostly taken over
406 // by `LiteralConstraints` (see in the below longer comment).
407 let key_val = in_keys
408 .arranged
409 .iter()
410 .filter_map(|key| {
411 mfp.literal_constraints(
412 &key.0.iter().map(MirScalarExpr::from).collect_vec(),
413 )
414 .map(|val| {
415 if let Some(metrics) = &self.metrics {
416 metrics.inc_literal_constraints("get");
417 }
418 (key.clone(), val)
419 })
420 })
421 .max_by_key(|(key, _val)| key.0.len());
422
423 // A source-import `Get::Collection`'s MIR `MfpPlan`, retained for
424 // `refine_source_mfps`. Stashed by `LirId` once the id is allocated below.
425 let mut source_get_mfp: Option<MfpPlan<MirScalarExpr>> = None;
426
427 // Determine the plan of action for the `Get` stage.
428 let plan = if let Some(((key, permutation, thinning), val)) = &key_val {
429 // This code path used to handle looking up literals from indexes, but it's
430 // mostly deprecated, as this is nowadays performed by the `LiteralConstraints`
431 // MIR transform instead. However, it's still called in a couple of tricky
432 // special cases:
433 // - `LiteralConstraints` handles only Gets of global ids, so this code still
434 // gets to handle Filters on top of Gets of local ids.
435 // - Lowering does a `MapFilterProject::extract_from_expression`, while
436 // `LiteralConstraints` does
437 // `MapFilterProject::extract_non_errors_from_expr_mut`.
438 // - It might happen that new literal constraint optimization opportunities
439 // appear somewhere near the end of the MIR optimizer after
440 // `LiteralConstraints` has already run.
441 // (Also note that a similar literal constraint handling machinery is also
442 // present when handling the leftover MFP after this big match.)
443 mfp.permute_fn(|c| permutation[c], thinning.len() + key.len());
444 in_keys.arranged = vec![(key.clone(), permutation.clone(), thinning.clone())];
445 GetPlan::Arrangement(key.clone(), Some(val.clone()), mfp_mir_to_lir_plan(mfp))
446 } else if !mfp.is_identity() {
447 // We need to ensure a collection exists, which means we must form it.
448 if let Some((key, permutation, thinning)) =
449 in_keys.arbitrary_arrangement().cloned()
450 {
451 mfp.permute_fn(|c| permutation[c], thinning.len() + key.len());
452 in_keys.arranged =
453 vec![(key.clone(), permutation.clone(), thinning.clone())];
454 GetPlan::Arrangement(key.clone(), None, mfp_mir_to_lir_plan(mfp))
455 } else {
456 let mir_plan = mfp.into_plan().expect("MFP planning failed");
457 if let Id::Global(gid) = id {
458 if self.source_imports.contains(gid) {
459 source_get_mfp = Some(mir_plan.clone());
460 }
461 }
462 GetPlan::Collection(mfp_plan_mir_to_lir(mir_plan))
463 }
464 } else {
465 // By default, just pass input arrangements through.
466 GetPlan::PassArrangements
467 };
468
469 let out_keys = if let GetPlan::PassArrangements = plan {
470 in_keys.clone()
471 } else {
472 AvailableCollections::new_raw()
473 };
474
475 // Even with a non-temporal MFP, we must propagate `has_future_updates`
476 // from the underlying binding — applying an MFP doesn't drop future-
477 // timestamped updates that already exist on the input.
478 //
479 // Note that global Gets from different dataflows can't have future updates, because
480 // both indexes and materialized views hold back future updates.
481 let has_future_updates = self.has_future_updates.contains(id)
482 || match &plan {
483 GetPlan::Arrangement(_, _, mfp_plan) | GetPlan::Collection(mfp_plan) => {
484 mfp_plan.has_temporal_bounds()
485 }
486 GetPlan::PassArrangements => false,
487 };
488
489 let lir_id = self.allocate_lir_id();
490 if let Some(mir_plan) = source_get_mfp {
491 self.source_get_mfps.insert(lir_id, mir_plan);
492 }
493 let node = LirRelationNode::Get {
494 id: id.clone(),
495 keys: in_keys,
496 plan,
497 };
498 // Return the plan, and any keys if an identity `mfp`.
499 LoweredExpr {
500 plan: node.as_plan(lir_id),
501 keys: out_keys,
502 has_future_updates,
503 }
504 }
505 MirRelationExpr::Let { id, value, body } => {
506 // It would be unfortunate to have a non-trivial `mfp` here, as we hope
507 // that they would be pushed down. I am not sure if we should take the
508 // initiative to push down the `mfp` ourselves.
509
510 // Plan the value using only the initial arrangements, but
511 // introduce any resulting arrangements bound to `id`.
512 let LoweredExpr {
513 plan: value,
514 keys: v_keys,
515 has_future_updates: v_future,
516 } = self.lower_mir_expr(value)?;
517 let pre_existing = self.arrangements.insert(Id::Local(*id), v_keys);
518 assert_none!(pre_existing);
519 if v_future {
520 self.has_future_updates.insert(Id::Local(*id));
521 }
522 // Plan the body using initial and `value` arrangements,
523 // and then remove reference to the value arrangements.
524 let LoweredExpr {
525 plan: body,
526 keys: b_keys,
527 has_future_updates: b_future,
528 } = self.lower_mir_expr(body)?;
529 self.arrangements.remove(&Id::Local(*id));
530 self.has_future_updates.remove(&Id::Local(*id));
531 // Return the plan, and any `body` arrangements.
532 let lir_id = self.allocate_lir_id();
533 LoweredExpr {
534 plan: LirRelationNode::Let {
535 id: id.clone(),
536 value: Box::new(value),
537 body: Box::new(body),
538 }
539 .as_plan(lir_id),
540 keys: b_keys,
541 has_future_updates: b_future,
542 }
543 }
544 MirRelationExpr::LetRec {
545 ids,
546 values,
547 limits,
548 body,
549 } => {
550 assert_eq!(ids.len(), values.len());
551 assert_eq!(ids.len(), limits.len());
552 // Plan the values using only the available arrangements, but
553 // introduce any resulting arrangements bound to each `id`.
554 // Arrangements made available cannot be used by prior bindings,
555 // as we cannot circulate an arrangement through a `Variable` yet.
556 let mut lir_values = Vec::with_capacity(values.len());
557 let mut any_v_future = false;
558 // The recursive bindings of a `LetRec` are not restricted to a single
559 // time, so single-time monotonic selection must not apply to them. Only
560 // the `body`, lowered below, inherits the enclosing scope's flag.
561 let outer_single_time = self.single_time;
562 self.single_time = false;
563 for (id, value) in ids.iter().zip_eq(values) {
564 let LoweredExpr {
565 plan: mut lir_value,
566 keys: mut v_keys,
567 has_future_updates: v_future,
568 } = self.lower_mir_expr(value)?;
569 any_v_future |= v_future;
570 // If `v_keys` does not contain an unarranged collection, we must form it.
571 if !v_keys.raw {
572 // Choose an "arbitrary" arrangement; TODO: prefer a specific one.
573 let (input_key, permutation, thinning) =
574 v_keys.arbitrary_arrangement().unwrap();
575 let mut input_mfp = MapFilterProject::new(value.arity());
576 input_mfp.permute_fn(|c| permutation[c], thinning.len() + input_key.len());
577 let input_key = Some(input_key.clone());
578
579 let forms = AvailableCollections::new_raw();
580
581 // We just want to insert an `ArrangeBy` to form an unarranged collection,
582 // but there is a complication: We shouldn't break the invariant (created by
583 // `NormalizeLets`, and relied upon by the rendering) that there isn't
584 // anything between two `LetRec`s. So if `lir_value` is itself a `LetRec`,
585 // then we insert the `ArrangeBy` on the `body` of the inner `LetRec`,
586 // instead of on top of the inner `LetRec`.
587 //
588 // We forward `v_future` for honesty; bucketing has no observable effect
589 // inside an iterative scope, but the field should reflect reality.
590 lir_value = match lir_value {
591 LirRelationExpr {
592 node:
593 LirRelationNode::LetRec {
594 ids,
595 values,
596 limits,
597 body,
598 },
599 lir_id,
600 } => {
601 let inner_lir_id = self.allocate_lir_id();
602 LirRelationNode::LetRec {
603 ids,
604 values,
605 limits,
606 body: Box::new(
607 LirRelationNode::ArrangeBy {
608 input_key,
609 input: body,
610 input_mfp: mfp_mir_to_lir_plan(input_mfp),
611 forms,
612 strategy: strategy_from_future(v_future),
613 }
614 .as_plan(inner_lir_id),
615 ),
616 }
617 .as_plan(lir_id)
618 }
619 lir_value => {
620 let lir_id = self.allocate_lir_id();
621 LirRelationNode::ArrangeBy {
622 input_key,
623 input: Box::new(lir_value),
624 input_mfp: mfp_mir_to_lir_plan(input_mfp),
625 forms,
626 strategy: strategy_from_future(v_future),
627 }
628 .as_plan(lir_id)
629 }
630 };
631 v_keys.raw = true;
632 }
633 let pre_existing = self.arrangements.insert(Id::Local(*id), v_keys);
634 assert_none!(pre_existing);
635 if v_future {
636 self.has_future_updates.insert(Id::Local(*id));
637 }
638 lir_values.push(lir_value);
639 }
640 // As we exit the iterative scope, we must leave all arrangements behind,
641 // as they reference a timestamp coordinate that must be stripped off.
642 for id in ids.iter() {
643 self.arrangements
644 .insert(Id::Local(*id), AvailableCollections::new_raw());
645 }
646 // Plan the body using initial and `value` arrangements,
647 // and then remove reference to the value arrangements.
648 self.single_time = outer_single_time;
649 let LoweredExpr {
650 plan: body,
651 keys: b_keys,
652 has_future_updates: b_future,
653 } = self.lower_mir_expr(body)?;
654 for id in ids.iter() {
655 self.arrangements.remove(&Id::Local(*id));
656 self.has_future_updates.remove(&Id::Local(*id));
657 }
658 // Return the plan, and any `body` arrangements.
659 //
660 // The body's `b_future` alone can under-report: an earlier binding may only
661 // inherit `has_future_updates` via a Variable to a *later* binding, which the
662 // sequential sweep can't observe at the time the earlier binding is lowered.
663 // A precise fix would require a fixpoint (or the MIR `Analysis` framework with
664 // a `true ⊑ false` lattice). As a cheap correct alternative, OR with the
665 // bindings' future flags: any cross-binding propagation must originate from a
666 // local temporal predicate inside *some* binding, so the OR captures it
667 // without forcing bucketing on a fully non-temporal LetRec.
668 let lir_id = self.allocate_lir_id();
669 LoweredExpr {
670 plan: LirRelationNode::LetRec {
671 ids: ids.clone(),
672 values: lir_values,
673 limits: limits.clone(),
674 body: Box::new(body),
675 }
676 .as_plan(lir_id),
677 keys: b_keys,
678 has_future_updates: b_future || any_v_future,
679 }
680 }
681 MirRelationExpr::FlatMap {
682 input: flat_map_input,
683 func,
684 exprs,
685 } => {
686 // A `FlatMap UnnestList` that comes after the `Reduce` of a window function can be
687 // fused into the lowered `Reduce`.
688 //
689 // In theory, we could have implemented this also as an MIR transform. However, this
690 // is more of a physical optimization, which are sometimes unpleasant to make a part
691 // of the MIR pipeline. The specific problem here with putting this into the MIR
692 // pipeline would be that we'd need to modify MIR's semantics: MIR's Reduce
693 // currently always emits exactly 1 row per group, but the fused Reduce-FlatMap can
694 // emit multiple rows per group. Such semantic changes of MIR are very scary, since
695 // various parts of the optimizer assume that Reduce emits only 1 row per group, and
696 // it would be very hard to hunt down all these parts. (For example, key inference
697 // infers the group key as a unique key.)
698 let fused_with_reduce = 'fusion: {
699 if !matches!(func, TableFunc::UnnestList { .. }) {
700 break 'fusion None;
701 }
702 // We might have a Project of a single col between the FlatMap and the
703 // Reduce. (It projects away the grouping keys of the Reduce, and keeps the
704 // result of the window function.)
705 let (maybe_reduce, num_grouping_keys) = if let MirRelationExpr::Project {
706 input: project_input,
707 outputs: projection,
708 } = &**flat_map_input
709 {
710 // We want this to be a single column, because we'll want to deal with only
711 // one aggregation in the `Reduce`. (The aggregation of a window function
712 // always stands alone currently: we plan them separately from other
713 // aggregations, and Reduces are never fused. When window functions are
714 // fused with each other, they end up in one aggregation. When there are
715 // multiple window functions in the same SELECT, but can't be fused, they
716 // end up in different Reduces.)
717 if let &[single_col] = &**projection {
718 (project_input, single_col)
719 } else {
720 break 'fusion None;
721 }
722 } else {
723 (flat_map_input, 0)
724 };
725 if let MirRelationExpr::Reduce {
726 input,
727 group_key,
728 aggregates,
729 monotonic,
730 expected_group_size,
731 } = &**maybe_reduce
732 {
733 if group_key.len() != num_grouping_keys
734 || aggregates.len() != 1
735 || !aggregates[0].func.can_fuse_with_unnest_list()
736 {
737 break 'fusion None;
738 }
739 // At the beginning, `non_fused_mfp_above_flat_map` will be the original MFP
740 // above the FlatMap. Later, we'll mutate this to be the residual MFP that
741 // didn't get fused into the `Reduce`.
742 let non_fused_mfp_above_flat_map = &mut mfp;
743 let reduce_output_arity = num_grouping_keys + 1;
744 // We are fusing away the list that the FlatMap would have been unnesting,
745 // so the column that had that list disappears, so we have to permute the
746 // MFP above the FlatMap with this column disappearance.
747 let tweaked_mfp = {
748 let mut mfp = non_fused_mfp_above_flat_map.clone();
749 if mfp.demand().contains(&0) {
750 // I don't think this can happen currently that this MFP would
751 // refer to the list column, because both the list column and the
752 // MFP were constructed by the HIR-to-MIR lowering, so it's not just
753 // some random MFP that we are seeing here. But anyhow, it's better
754 // to check this here for robustness against future code changes.
755 break 'fusion None;
756 }
757 let permutation: BTreeMap<_, _> =
758 (1..mfp.input_arity).map(|col| (col, col - 1)).collect();
759 mfp.permute_fn(|c| permutation[&c], mfp.input_arity - 1);
760 mfp
761 };
762 // We now put together the project that was before the FlatMap, and the
763 // tweaked version of the MFP that was after the FlatMap.
764 // (Part of this MFP might be fused into the Reduce.)
765 let mut project_and_tweaked_mfp = {
766 let mut mfp = MapFilterProject::new(reduce_output_arity);
767 mfp = mfp.project(vec![num_grouping_keys]);
768 mfp = MapFilterProject::compose(mfp, tweaked_mfp);
769 mfp
770 };
771 let fused = self.lower_reduce(
772 input,
773 group_key,
774 aggregates,
775 monotonic,
776 expected_group_size,
777 &mut project_and_tweaked_mfp,
778 true,
779 )?;
780 // Update the residual MFP.
781 *non_fused_mfp_above_flat_map = project_and_tweaked_mfp;
782 Some(fused)
783 } else {
784 break 'fusion None;
785 }
786 };
787 if let Some(fused_with_reduce) = fused_with_reduce {
788 fused_with_reduce
789 } else {
790 // Couldn't fuse it with a `Reduce`, so lower as a normal `FlatMap`.
791 let LoweredExpr {
792 plan: input,
793 keys,
794 has_future_updates: input_future,
795 } = self.lower_mir_expr(flat_map_input)?;
796 // This stage can absorb arbitrary MFP instances.
797 let mut mfp = mfp.take();
798 let mut exprs = exprs.clone();
799 // Prefer the unarranged collection when present: it presents input columns
800 // in logical order, so no permutation is required.
801 let input_key = if keys.raw {
802 None
803 } else if let Some((k, permutation, thinning)) = keys.arbitrary_arrangement() {
804 // Reading from this arrangement exposes input columns in arrangement
805 // order (key columns followed by thinned value columns). We must
806 // permute every reference to an input column accordingly: the
807 // `expr`s feeding the table function arguments, and the `mfp` running
808 // after the table function (which still references input columns at
809 // positions `0..input_arity`).
810 //
811 // The renderer hands the `mfp` the *whole* arranged row and appends the
812 // table-function output after it. The arranged row can be wider than the
813 // logical input row when the key is not a set of distinct columns (an
814 // expression, functional, or repeated-column key carries extra key
815 // values). So the table-function output columns at positions
816 // `input_arity..` must be shifted to land after the arranged row, and the
817 // `mfp`'s new input arity must reflect the arranged width.
818 for expr in &mut exprs {
819 expr.permute(permutation);
820 }
821 let input_arity = permutation.len();
822 let arranged_arity = thinning.len() + k.len();
823 let output_arity = mfp.input_arity - input_arity;
824 mfp.permute_fn(
825 |c| {
826 if c < input_arity {
827 permutation[c]
828 } else {
829 arranged_arity + (c - input_arity)
830 }
831 },
832 arranged_arity + output_arity,
833 );
834 Some(k.clone())
835 } else {
836 None
837 };
838
839 let lir_id = self.allocate_lir_id();
840 // The absorbed `mfp` may contain temporal predicates, which can
841 // introduce future-stamped updates that aren't present on the input.
842 let has_future_updates = input_future || mfp.has_temporal_predicates();
843 // Return the plan, and no arrangements.
844 LoweredExpr {
845 plan: LirRelationNode::FlatMap {
846 input_key,
847 input: Box::new(input),
848 exprs: lses_from_mses(&exprs),
849 func: func.clone(),
850 mfp_after: mfp_mir_to_lir_plan(mfp),
851 }
852 .as_plan(lir_id),
853 keys: AvailableCollections::new_raw(),
854 has_future_updates,
855 }
856 }
857 }
858 MirRelationExpr::Join {
859 inputs,
860 equivalences,
861 implementation,
862 } => {
863 // Plan each of the join inputs independently.
864 // The `plans` get surfaced upwards, and the `input_keys` should
865 // be used as part of join planning / to validate the existing
866 // plans / to aid in indexed seeding of update streams.
867 let mut plans = Vec::new();
868 let mut input_keys = Vec::new();
869 let mut input_arities = Vec::new();
870 let mut input_futures = Vec::new();
871 for input in inputs.iter() {
872 let LoweredExpr {
873 plan,
874 keys,
875 has_future_updates: input_future,
876 } = self.lower_mir_expr(input)?;
877 input_arities.push(input.arity());
878 plans.push(plan);
879 input_keys.push(keys);
880 input_futures.push(input_future);
881 }
882 let any_input_future = input_futures.iter().any(|&f| f);
883
884 let input_mapper =
885 JoinInputMapper::new_from_input_arities(input_arities.iter().copied());
886
887 // Extract temporal predicates as joins cannot currently absorb them.
888 let (plan, missing) = match implementation {
889 IndexedFilter(_coll_id, _idx_id, key, _val) => {
890 // Start with the constant input. (This used to be important before database-issues#4016
891 // was fixed.)
892 let start: usize = 1;
893 let order = vec![(0usize, key.clone(), None)];
894 // All columns of the constant input will be part of the arrangement key.
895 let source_arrangement = (
896 (0..key.len())
897 .map(LirScalarExpr::column)
898 .collect::<Vec<_>>(),
899 (0..key.len()).collect::<Vec<_>>(),
900 Vec::<usize>::new(),
901 );
902 let (ljp, missing) = LinearJoinPlan::create_from(
903 start,
904 Some(&source_arrangement),
905 equivalences,
906 &order,
907 input_mapper,
908 &mut mfp,
909 &input_keys,
910 );
911 (JoinPlan::Linear(ljp), missing)
912 }
913 Differential((start, start_arr, _start_characteristic), order) => {
914 let source_arrangement = start_arr.as_ref().and_then(|key| {
915 let key = lses_from_mses(key);
916 input_keys[*start]
917 .arranged
918 .iter()
919 .find(|(k, _, _)| k == &key)
920 .clone()
921 });
922 let (ljp, missing) = LinearJoinPlan::create_from(
923 *start,
924 source_arrangement,
925 equivalences,
926 order,
927 input_mapper,
928 &mut mfp,
929 &input_keys,
930 );
931 (JoinPlan::Linear(ljp), missing)
932 }
933 DeltaQuery(orders) => {
934 let (djp, missing) = DeltaJoinPlan::create_from(
935 equivalences,
936 orders,
937 input_mapper,
938 &mut mfp,
939 &input_keys,
940 );
941 (JoinPlan::Delta(djp), missing)
942 }
943 // Other plans are errors, and should be reported as such.
944 Unimplemented => return Err("unimplemented join".to_string()),
945 };
946 // The renderer will expect certain arrangements to exist; if any of those are not available, the join planning functions above should have returned them in
947 // `missing`. We thus need to plan them here so they'll exist.
948 let is_delta = matches!(plan, JoinPlan::Delta(_));
949 for ((((input_plan, input_keys), missing), arity), input_future) in plans
950 .iter_mut()
951 .zip_eq(input_keys.iter())
952 .zip_eq(missing)
953 .zip_eq(input_arities.iter().cloned())
954 .zip_eq(input_futures.iter().copied())
955 {
956 if missing != Default::default() {
957 if is_delta {
958 // join_implementation.rs produced a sub-optimal plan here;
959 // we shouldn't plan delta joins at all if not all of the required
960 // arrangements are available. Soft panic in CI and log an error in
961 // production to increase the chances that we will catch all situations
962 // that violate this constraint.
963 soft_panic_or_log!("Arrangements depended on by delta join alarmingly absent: {:?}
964Dataflow info: {}
965This is not expected to cause incorrect results, but could indicate a performance issue in Materialize.", missing, self.debug_info);
966 } else {
967 soft_panic_or_log!("Arrangements depended on by a non-delta join are absent: {:?}
968Dataflow info: {}
969This is not expected to cause incorrect results, but could indicate a performance issue in Materialize.", missing, self.debug_info);
970 // Nowadays MIR transforms take care to insert MIR ArrangeBys for each
971 // Join input. (Earlier, they were missing in the following cases:
972 // - They were const-folded away for constant inputs. This is not
973 // happening since
974 // https://github.com/MaterializeInc/materialize/pull/16351
975 // - They were not being inserted for the constant input of
976 // `IndexedFilter`s. This was fixed in
977 // https://github.com/MaterializeInc/materialize/pull/20920
978 // - They were not being inserted for the first input of Differential
979 // joins. This was fixed in
980 // https://github.com/MaterializeInc/materialize/pull/16099)
981 }
982 let lir_id = self.allocate_lir_id();
983 let raw_plan = std::mem::replace(
984 input_plan,
985 LirRelationNode::Constant {
986 rows: Ok(Vec::new()),
987 }
988 .as_plan(lir_id),
989 );
990 *input_plan =
991 self.arrange_by(raw_plan, missing, input_keys, arity, input_future);
992 }
993 }
994 // Return the plan, and no arrangements.
995 // Both linear and delta join planning extract temporal predicates back into the
996 // residual `mfp` (see `LinearJoinPlan::create_from` / `DeltaJoinPlan::create_from`),
997 // so the absorbed MFP cannot introduce future updates — the join's output future
998 // flag is just the OR of its inputs.
999 let lir_id = self.allocate_lir_id();
1000 LoweredExpr {
1001 plan: LirRelationNode::Join {
1002 inputs: plans,
1003 plan,
1004 }
1005 .as_plan(lir_id),
1006 keys: AvailableCollections::new_raw(),
1007 has_future_updates: any_input_future,
1008 }
1009 }
1010 MirRelationExpr::Reduce {
1011 input,
1012 group_key,
1013 aggregates,
1014 monotonic,
1015 expected_group_size,
1016 } => {
1017 if aggregates
1018 .iter()
1019 .any(|agg| agg.func.can_fuse_with_unnest_list())
1020 {
1021 // This case should have been handled at the `MirRelationExpr::FlatMap` case
1022 // above. But that has a pretty complicated pattern matching, so it's not
1023 // unthinkable that it fails.
1024 soft_panic_or_log!(
1025 "Window function performance issue: `reduce_unnest_list_fusion` failed"
1026 );
1027 }
1028 self.lower_reduce(
1029 input,
1030 group_key,
1031 aggregates,
1032 monotonic,
1033 expected_group_size,
1034 &mut mfp,
1035 false,
1036 )?
1037 }
1038 MirRelationExpr::TopK {
1039 input,
1040 group_key,
1041 order_key,
1042 limit,
1043 offset,
1044 monotonic,
1045 expected_group_size,
1046 } => {
1047 let arity = input.arity();
1048 let LoweredExpr {
1049 plan: input,
1050 keys,
1051 has_future_updates: input_future,
1052 } = self.lower_mir_expr(input)?;
1053
1054 let mut top_k_plan = TopKPlan::create_from(
1055 group_key.clone(),
1056 order_key.clone(),
1057 *offset,
1058 limit
1059 .as_ref()
1060 .map(|limit| LirScalarExpr::try_from(limit).expect("lowerable MIR")),
1061 arity,
1062 *monotonic,
1063 *expected_group_size,
1064 );
1065
1066 // For single-time dataflows, upgrade to the monotonic variant with
1067 // mandatory consolidation. `refine_single_time_consolidation` later
1068 // relaxes `must_consolidate` where the input is physically monotonic.
1069 if self.single_time {
1070 top_k_plan.as_monotonic(true);
1071 }
1072
1073 // We don't have an MFP here -- install an operator to permute the
1074 // input, if necessary.
1075 let input = if !keys.raw {
1076 self.arrange_by(
1077 input,
1078 AvailableCollections::new_raw(),
1079 &keys,
1080 arity,
1081 // `new_raw` means no arrangement, so no bucketing is needed
1082 false,
1083 )
1084 } else {
1085 input
1086 };
1087 // Return the plan, and the keys it produces. `MonotonicTop1` arranges its
1088 // output by the group key (see `render_top1_monotonic`), so a downstream
1089 // consumer keyed the same way can reuse that arrangement instead of forcing
1090 // another `ArrangeBy`.
1091 let out_keys = match &top_k_plan {
1092 TopKPlan::MonotonicTop1(_) => {
1093 let key = group_key
1094 .iter()
1095 .map(|c| LirScalarExpr::column(*c))
1096 .collect::<Vec<_>>();
1097 let (permutation, thinning) = permutation_for_arrangement(&key, arity);
1098 AvailableCollections::new_arranged(vec![(key, permutation, thinning)])
1099 }
1100 // MonotonicTopK / Basic key their arrangements by (hash, group_key), which is
1101 // not reusable by a group-key consumer, so they advertise no arrangement.
1102 TopKPlan::MonotonicTopK(_) | TopKPlan::Basic(_) => {
1103 AvailableCollections::new_raw()
1104 }
1105 };
1106 let temporal_bucketing_strategy = strategy_from_future(input_future);
1107 let lir_id = self.allocate_lir_id();
1108 LoweredExpr {
1109 plan: LirRelationNode::TopK {
1110 input: Box::new(input),
1111 top_k_plan,
1112 temporal_bucketing_strategy,
1113 }
1114 .as_plan(lir_id),
1115 keys: out_keys,
1116 has_future_updates: false,
1117 }
1118 }
1119 MirRelationExpr::Negate { input } => {
1120 let arity = input.arity();
1121 let LoweredExpr {
1122 plan: input,
1123 keys,
1124 has_future_updates: input_future,
1125 } = self.lower_mir_expr(input)?;
1126
1127 // We don't have an MFP here -- install an operator to permute the
1128 // input, if necessary.
1129 let input = if !keys.raw {
1130 self.arrange_by(
1131 input,
1132 AvailableCollections::new_raw(),
1133 &keys,
1134 arity,
1135 // `new_raw` means no arrangement, so no bucketing is needed
1136 false,
1137 )
1138 } else {
1139 input
1140 };
1141 // Return the plan, and no arrangements.
1142 let lir_id = self.allocate_lir_id();
1143 LoweredExpr {
1144 plan: LirRelationNode::Negate {
1145 input: Box::new(input),
1146 }
1147 .as_plan(lir_id),
1148 keys: AvailableCollections::new_raw(),
1149 has_future_updates: input_future,
1150 }
1151 }
1152 MirRelationExpr::Threshold { input } => {
1153 let LoweredExpr {
1154 plan,
1155 keys,
1156 has_future_updates: input_future,
1157 } = self.lower_mir_expr(input)?;
1158 let arity = input.arity();
1159 let (threshold_plan, required_arrangement) = ThresholdPlan::create_from(arity);
1160
1161 let plan = if !keys
1162 .arranged
1163 .iter()
1164 .any(|(key, _, _)| key == &required_arrangement.0)
1165 {
1166 self.arrange_by(
1167 plan,
1168 AvailableCollections::new_arranged(vec![required_arrangement]),
1169 &keys,
1170 arity,
1171 input_future,
1172 )
1173 } else {
1174 plan
1175 };
1176
1177 let output_keys = threshold_plan.keys();
1178 // Return the plan, and any produced keys.
1179 let lir_id = self.allocate_lir_id();
1180 LoweredExpr {
1181 plan: LirRelationNode::Threshold {
1182 input: Box::new(plan),
1183 threshold_plan,
1184 }
1185 .as_plan(lir_id),
1186 keys: output_keys,
1187 // Threshold builds its own output arrangement whose
1188 // MergeBatcher absorbs future-stamped updates, so no
1189 // future updates flow out.
1190 has_future_updates: false,
1191 }
1192 }
1193 MirRelationExpr::Union { base, inputs } => {
1194 let arity = base.arity();
1195 let mut lowered_inputs = Vec::with_capacity(1 + inputs.len());
1196 lowered_inputs.push(self.lower_mir_expr(base)?);
1197 for input in inputs.iter() {
1198 lowered_inputs.push(self.lower_mir_expr(input)?);
1199 }
1200
1201 // A Union with any `Negate` input should consolidate its
1202 // output. The lowering is the only place where this decision
1203 // can be coupled with the per-input bucketing strategy.
1204 let consolidate_output = lowered_inputs
1205 .iter()
1206 .any(|l| matches!(l.plan.node, LirRelationNode::Negate { .. }));
1207
1208 // Per-input bucketing strategies: only meaningful when the
1209 // Union consolidates its output, since bucketing only pays off
1210 // ahead of a downstream consolidator.
1211 let temporal_bucketing_strategies: Vec<ArrangementStrategy> = if consolidate_output
1212 {
1213 lowered_inputs
1214 .iter()
1215 .map(|l| strategy_from_future(l.has_future_updates))
1216 .collect()
1217 } else {
1218 lowered_inputs
1219 .iter()
1220 .map(|_| ArrangementStrategy::Direct)
1221 .collect()
1222 };
1223
1224 let has_future_updates = if consolidate_output {
1225 // The MergeBatcher will hold back future updates (regardless of whether we are
1226 // bucketing here or not).
1227 false
1228 } else {
1229 lowered_inputs.iter().any(|l| l.has_future_updates)
1230 };
1231
1232 let plans = lowered_inputs
1233 .into_iter()
1234 .map(
1235 |LoweredExpr {
1236 plan,
1237 keys,
1238 has_future_updates: _,
1239 }| {
1240 // We don't have an MFP here -- install an operator to permute the
1241 // input, if necessary.
1242 if !keys.raw {
1243 self.arrange_by(
1244 plan,
1245 AvailableCollections::new_raw(),
1246 &keys,
1247 arity,
1248 // `new_raw` means no arrangement, so no bucketing is needed
1249 false,
1250 )
1251 } else {
1252 plan
1253 }
1254 },
1255 )
1256 .collect();
1257 // Return the plan and no arrangements.
1258 let lir_id = self.allocate_lir_id();
1259 LoweredExpr {
1260 plan: LirRelationNode::Union {
1261 inputs: plans,
1262 consolidate_output,
1263 temporal_bucketing_strategies,
1264 }
1265 .as_plan(lir_id),
1266 keys: AvailableCollections::new_raw(),
1267 has_future_updates,
1268 }
1269 }
1270 MirRelationExpr::ArrangeBy { input, keys } => {
1271 let input_mir = input;
1272 let LoweredExpr {
1273 plan: input,
1274 keys: mut input_keys,
1275 has_future_updates: input_has_future_updates,
1276 } = self.lower_mir_expr(input)?;
1277 // Fill the `types` in `input_keys` if not already present.
1278 let arity = input_mir.arity();
1279
1280 // Determine keys that are not present in `input_keys`.
1281 let new_keys = keys
1282 .iter()
1283 .filter(|k1| {
1284 !input_keys.arranged.iter().any(|(k2, _, _)| {
1285 k1.len() == k2.len()
1286 && k1
1287 .iter()
1288 .zip_eq(k2)
1289 .all(|(e1, e2)| *e1 == MirScalarExpr::from(e2))
1290 })
1291 })
1292 .cloned()
1293 .collect::<Vec<_>>();
1294 if new_keys.is_empty() {
1295 LoweredExpr {
1296 plan: input,
1297 keys: input_keys,
1298 has_future_updates: input_has_future_updates,
1299 }
1300 } else {
1301 let mut new_keys = new_keys
1302 .iter()
1303 .map(|k| {
1304 let k = lses_from_mses(k);
1305 let (permutation, thinning) = permutation_for_arrangement(&k, arity);
1306 (k, permutation, thinning)
1307 })
1308 .collect::<Vec<_>>();
1309 let forms = AvailableCollections {
1310 raw: input_keys.raw,
1311 arranged: new_keys.clone(),
1312 };
1313 let (input_key, input_mfp) = if let Some((input_key, permutation, thinning)) =
1314 input_keys.arbitrary_arrangement()
1315 {
1316 let mut mfp = MapFilterProject::new(arity);
1317 mfp.permute_fn(|c| permutation[c], thinning.len() + input_key.len());
1318 (Some(input_key.clone()), mfp)
1319 } else {
1320 (None, MapFilterProject::new(arity))
1321 };
1322 input_keys.arranged.append(&mut new_keys);
1323 input_keys.arranged.sort_by(|k1, k2| k1.0.cmp(&k2.0));
1324
1325 // Return the plan and extended keys.
1326 let lir_id = self.allocate_lir_id();
1327 let strategy = strategy_from_future(input_has_future_updates);
1328 assert!(!forms.arranged.is_empty()); // i.e., we do build an arrangement
1329 let has_future_updates = false;
1330 LoweredExpr {
1331 plan: LirRelationNode::ArrangeBy {
1332 input_key,
1333 input: Box::new(input),
1334 input_mfp: mfp_mir_to_lir_plan(input_mfp),
1335 forms,
1336 strategy,
1337 }
1338 .as_plan(lir_id),
1339 keys: input_keys,
1340 has_future_updates,
1341 }
1342 }
1343 }
1344 };
1345
1346 // If the plan stage did not absorb all linear operators, introduce a new stage to implement them.
1347 if !mfp.is_identity() {
1348 // Check if this MFP introduces future updates.
1349 let mfp_is_temporal = mfp.has_temporal_predicates();
1350 has_future_updates = has_future_updates || mfp_is_temporal;
1351 // Seek out an arrangement key that might be constrained to a literal.
1352 // TODO: Improve key selection heuristic.
1353 let key_val = keys
1354 .arranged
1355 .iter()
1356 .filter_map(|(key, permutation, thinning)| {
1357 let mut mfp = mfp.clone();
1358 mfp.permute_fn(|c| permutation[c], thinning.len() + key.len());
1359 mfp.literal_constraints(&key.iter().map(MirScalarExpr::from).collect_vec())
1360 .map(|val| {
1361 if let Some(metrics) = &self.metrics {
1362 metrics.inc_literal_constraints("mfp");
1363 }
1364 (key.clone(), permutation, thinning, val)
1365 })
1366 })
1367 .max_by_key(|(key, _, _, _)| key.len());
1368
1369 // Input key selection strategy:
1370 // (1) If we can read a key at a particular value, do so
1371 // (2) Otherwise, if there is a key that causes the MFP to be the identity, and
1372 // therefore allows us to avoid discarding the arrangement, use that.
1373 // (3) Otherwise, if there is _some_ key, use that,
1374 // (4) Otherwise just read the raw collection.
1375 let input_key_val = if let Some((key, permutation, thinning, val)) = key_val {
1376 mfp.permute_fn(|c| permutation[c], thinning.len() + key.len());
1377
1378 Some((key, Some(val)))
1379 } else if let Some((key, permutation, thinning)) =
1380 keys.arranged.iter().find(|(key, permutation, thinning)| {
1381 let mut mfp = mfp.clone();
1382 mfp.permute_fn(|c| permutation[c], thinning.len() + key.len());
1383 mfp.is_identity()
1384 })
1385 {
1386 mfp.permute_fn(|c| permutation[c], thinning.len() + key.len());
1387 Some((key.clone(), None))
1388 } else if let Some((key, permutation, thinning)) = keys.arbitrary_arrangement() {
1389 mfp.permute_fn(|c| permutation[c], thinning.len() + key.len());
1390 Some((key.clone(), None))
1391 } else {
1392 None
1393 };
1394
1395 if mfp.is_identity() {
1396 // We have discovered a key
1397 // whose permutation causes the MFP to actually
1398 // be the identity! We can keep it around,
1399 // but without its permutation this time,
1400 // and with a trivial thinning of the right length.
1401 let (key, val) = input_key_val.unwrap();
1402 let (_old_key, old_permutation, old_thinning) = keys
1403 .arranged
1404 .iter_mut()
1405 .find(|(key2, _, _)| key2 == &key)
1406 .unwrap();
1407 *old_permutation = (0..mfp.input_arity).collect();
1408 let old_thinned_arity = old_thinning.len();
1409 *old_thinning = (0..old_thinned_arity).collect();
1410 // Get rid of all other forms, as this is now the only one known to be valid.
1411 // TODO[btv] we can probably save the other arrangements too, if we adjust their permutations.
1412 // This is not hard to do, but leaving it for a quick follow-up to avoid making the present diff too unwieldy.
1413 keys.arranged.retain(|(key2, _, _)| key2 == &key);
1414 keys.raw = false;
1415
1416 // Creating a LirRelationExpr::Mfp node is now logically unnecessary, but we
1417 // should do so anyway when `val` is populated, so that
1418 // the `key_val` optimization gets applied.
1419 let lir_id = self.allocate_lir_id();
1420 if val.is_some() {
1421 plan = LirRelationNode::Mfp {
1422 input: Box::new(plan),
1423 mfp: mfp_mir_to_lir_plan(mfp),
1424 input_key_val: Some((key.clone(), val)),
1425 }
1426 .as_plan(lir_id)
1427 }
1428 } else {
1429 let lir_id = self.allocate_lir_id();
1430 plan = LirRelationNode::Mfp {
1431 input: Box::new(plan),
1432 mfp: mfp_mir_to_lir_plan(mfp),
1433 input_key_val,
1434 }
1435 .as_plan(lir_id);
1436 keys = AvailableCollections::new_raw();
1437 }
1438 }
1439
1440 Ok(LoweredExpr {
1441 plan,
1442 keys,
1443 has_future_updates,
1444 })
1445 }
1446
1447 /// Lowers a `Reduce` with the given fields and an `mfp_on_top`, which is the MFP that is
1448 /// originally on top of the `Reduce`. This MFP, or a part of it, might be fused into the
1449 /// `Reduce`, in which case `mfp_on_top` is mutated to be the residual MFP, i.e., what was not
1450 /// fused.
1451 fn lower_reduce(
1452 &mut self,
1453 input: &MirRelationExpr,
1454 group_key: &Vec<MirScalarExpr>,
1455 aggregates: &Vec<AggregateExpr>,
1456 monotonic: &bool,
1457 expected_group_size: &Option<u64>,
1458 mfp_on_top: &mut MapFilterProject,
1459 fused_unnest_list: bool,
1460 ) -> Result<LoweredExpr, String> {
1461 let input_arity = input.arity();
1462 let LoweredExpr {
1463 plan: input,
1464 keys,
1465 has_future_updates: input_future,
1466 } = self.lower_mir_expr(input)?;
1467 let (input_key, permutation_and_new_arity) =
1468 if let Some((input_key, permutation, thinning)) = keys.arbitrary_arrangement() {
1469 (
1470 Some(input_key.clone()),
1471 Some((permutation.clone(), thinning.len() + input_key.len())),
1472 )
1473 } else {
1474 (None, None)
1475 };
1476 let key_val_plan = KeyValPlan::new(
1477 input_arity,
1478 group_key,
1479 aggregates,
1480 permutation_and_new_arity,
1481 );
1482 let mut reduce_plan = ReducePlan::create_from(
1483 aggregates.clone(),
1484 *monotonic,
1485 *expected_group_size,
1486 fused_unnest_list,
1487 );
1488
1489 // For single-time dataflows, upgrade a hierarchical reduce to its monotonic
1490 // variant with mandatory consolidation. `refine_single_time_consolidation`
1491 // later relaxes `must_consolidate` where the input is physically monotonic.
1492 // Selecting the variant before computing `keys` below keeps the advertised
1493 // `AvailableCollections` consistent with the final plan. `Reduce::keys()` is
1494 // the same for every hierarchical sub-variant, so the advertisement is in fact
1495 // identical either way.
1496 if self.single_time {
1497 if let ReducePlan::Hierarchical(hierarchical) = &mut reduce_plan {
1498 hierarchical.as_monotonic(true);
1499 }
1500 }
1501
1502 // Return the plan, and the keys it produces.
1503 let mfp_after;
1504 let output_arity;
1505 if self.enable_reduce_mfp_fusion {
1506 (mfp_after, *mfp_on_top, output_arity) =
1507 reduce_plan.extract_mfp_after(mfp_on_top.clone(), group_key.len());
1508 } else {
1509 (mfp_after, output_arity) = (
1510 MapFilterProject::new(mfp_on_top.input_arity),
1511 group_key.len() + aggregates.len(),
1512 );
1513 }
1514 soft_assert_eq_or_log!(
1515 mfp_on_top.input_arity,
1516 output_arity,
1517 "Output arity of reduce must match input arity for MFP on top of it"
1518 );
1519 let output_keys = reduce_plan.keys(group_key.len(), output_arity);
1520 let lir_id = self.allocate_lir_id();
1521 // `Reduce` builds its own input arrangement inside `render_reduce` (via `KeyValPlan`),
1522 // bypassing `ensure_collections`. So we can't piggy-back on an upstream `ArrangeBy`'s
1523 // strategy to request temporal bucketing on a temporal-MFP-fed input: there is no such
1524 // `ArrangeBy`. Instead we record the strategy directly on the `Reduce` node, and
1525 // `render_reduce` applies bucketing to the keyed `(key, val)` stream itself.
1526 let temporal_bucketing_strategy = strategy_from_future(input_future);
1527 // (This can't currently happen due to `extract_mfp_after` separating out any temporal part.)
1528 let has_future_updates = mfp_after.has_temporal_predicates();
1529 Ok(LoweredExpr {
1530 plan: LirRelationNode::Reduce {
1531 input_key,
1532 input: Box::new(input),
1533 key_val_plan,
1534 plan: reduce_plan,
1535 mfp_after: SafeMfpPlan::from_mfp(mfp_mir_to_lir(mfp_after)),
1536 temporal_bucketing_strategy,
1537 }
1538 .as_plan(lir_id),
1539 keys: output_keys,
1540 has_future_updates,
1541 })
1542 }
1543
1544 /// Replace the plan with another one
1545 /// that has the collection in some additional forms.
1546 pub fn arrange_by(
1547 &mut self,
1548 plan: LirRelationExpr,
1549 collections: AvailableCollections,
1550 old_collections: &AvailableCollections,
1551 arity: usize,
1552 has_future_updates: bool,
1553 ) -> LirRelationExpr {
1554 if let LirRelationExpr {
1555 node:
1556 LirRelationNode::ArrangeBy {
1557 input_key,
1558 input,
1559 input_mfp,
1560 mut forms,
1561 strategy,
1562 },
1563 lir_id,
1564 } = plan
1565 {
1566 forms.raw |= collections.raw;
1567 forms.arranged.extend(collections.arranged);
1568 forms.arranged.sort_by(|k1, k2| k1.0.cmp(&k2.0));
1569 forms.arranged.dedup_by(|k1, k2| k1.0 == k2.0);
1570 LirRelationNode::ArrangeBy {
1571 input_key,
1572 input,
1573 input_mfp,
1574 forms,
1575 strategy,
1576 }
1577 .as_plan(lir_id)
1578 } else {
1579 let (input_key, input_mfp) = if let Some((input_key, permutation, thinning)) =
1580 old_collections.arbitrary_arrangement()
1581 {
1582 let mut mfp = MapFilterProject::new(arity);
1583 mfp.permute_fn(|c| permutation[c], thinning.len() + input_key.len());
1584 (Some(input_key.clone()), mfp)
1585 } else {
1586 (None, MapFilterProject::new(arity))
1587 };
1588 let lir_id = self.allocate_lir_id();
1589
1590 LirRelationNode::ArrangeBy {
1591 input_key,
1592 input: Box::new(plan),
1593 input_mfp: mfp_mir_to_lir_plan(input_mfp),
1594 forms: collections,
1595 strategy: strategy_from_future(has_future_updates),
1596 }
1597 .as_plan(lir_id)
1598 }
1599 }
1600}
1601
1602/// Various bits of state to print along with error messages during LIR planning,
1603/// to aid debugging.
1604#[derive(Clone, Debug)]
1605pub struct LirDebugInfo {
1606 debug_name: String,
1607 id: GlobalId,
1608}
1609
1610impl std::fmt::Display for LirDebugInfo {
1611 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1612 write!(f, "Debug name: {}; id: {}", self.debug_name, self.id)
1613 }
1614}