Skip to main content

mz_compute/render/
context.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//! Management of dataflow-local state, like arrangements, while building a
11//! dataflow.
12
13use std::collections::BTreeMap;
14use std::rc::Rc;
15
16use columnar::{Columnar, Index};
17use differential_dataflow::consolidation::ConsolidatingContainerBuilder;
18use differential_dataflow::operators::arrange::Arranged;
19use differential_dataflow::trace::cursor::{BatchCursor, BatchKey, BatchVal};
20use differential_dataflow::trace::implementations::BatchContainer;
21use differential_dataflow::trace::{Cursor, Navigable, TraceReader};
22use differential_dataflow::{AsCollection, VecCollection};
23use mz_compute_types::dataflows::DataflowDescription;
24use mz_compute_types::dyncfgs::TEMPORAL_BUCKETING_SUMMARY;
25use mz_compute_types::plan::scalar::LirScalarExpr;
26use mz_compute_types::plan::{ArrangementStrategy, AvailableCollections};
27use mz_dyncfg::ConfigSet;
28use mz_expr::{Eval, Id, MfpPlan};
29use mz_ore::soft_assert_or_log;
30use mz_repr::fixed_length::ExtendDatums;
31use mz_repr::{DatumVec, DatumVecBorrow, Diff, GlobalId, Row, RowArena, SharedRow, StableRow};
32use mz_storage_types::controller::CollectionMetadata;
33use mz_timely_util::columnar::Column;
34use mz_timely_util::columnar::builder::ColumnBuilder;
35use mz_timely_util::columnar::columnar_exchange;
36use mz_timely_util::columnar::consolidate::ConsolidatingColumnBuilder;
37use timely::ContainerBuilder;
38use timely::container::NoopBuilder;
39use timely::dataflow::channels::pact::{ExchangeCore, Pipeline};
40use timely::dataflow::operators::CapabilitySet;
41use timely::dataflow::operators::generic::builder_rc::OperatorBuilder;
42use timely::dataflow::operators::generic::{OutputBuilder, OutputBuilderSession};
43use timely::dataflow::{Scope, Stream};
44use timely::progress::operate::FrontierInterest;
45use timely::progress::{Antichain, Timestamp};
46
47use crate::compute_state::ComputeState;
48use crate::extensions::arrange::{ArrangementBatcher, KeyCollection, MzArrange, MzArrangeCore};
49use crate::extensions::reduce::MzReduce;
50use crate::render::columnar::{ColCollection, flat_map_datums};
51use crate::render::errors::{DataflowErrorSer, ErrorLogger};
52use crate::render::{LinearJoinSpec, MaybeBucketByTime, RenderTimestamp};
53use crate::typedefs::{
54    ErrAgent, ErrBatcher, ErrBuilder, ErrEnter, ErrSpine, RowRowAgent, RowRowChunkedBatcher,
55    RowRowColumnarBatcher, RowRowColumnationBatcher, RowRowEnter, RowRowSpine,
56};
57
58/// Dataflow-local collections and arrangements.
59///
60/// A context means to wrap available data assets and present them in an easy-to-use manner.
61/// These assets include dataflow-local collections and arrangements, as well as imported
62/// arrangements from outside the dataflow.
63///
64/// Context has a timestamp type `T`, which is the timestamp used by the scope in question.
65pub struct Context<'scope, T: RenderTimestamp> {
66    /// The scope within which all managed collections exist.
67    ///
68    /// It is an error to add any collections not contained in this scope.
69    pub(crate) scope: Scope<'scope, T>,
70    /// The debug name of the dataflow associated with this context.
71    pub debug_name: String,
72    /// The Timely ID of the dataflow associated with this context.
73    pub dataflow_id: usize,
74    /// The collection IDs of exports of the dataflow associated with this context.
75    pub export_ids: Vec<GlobalId>,
76    /// Frontier before which updates should not be emitted.
77    ///
78    /// We *must* apply it to sinks, to ensure correct outputs.
79    /// We *should* apply it to sources and imported traces, because it improves performance.
80    pub as_of_frontier: Antichain<mz_repr::Timestamp>,
81    /// Frontier after which updates should not be emitted.
82    /// Used to limit the amount of work done when appropriate.
83    pub until: Antichain<mz_repr::Timestamp>,
84    /// Bindings of identifiers to collections.
85    pub bindings: BTreeMap<Id, CollectionBundle<'scope, T>>,
86    /// The logger, from Timely's logging framework, if logs are enabled.
87    pub(super) compute_logger: Option<crate::logging::compute::Logger>,
88    /// Specification for rendering linear joins.
89    pub(super) linear_join_spec: LinearJoinSpec,
90    /// The expiration time for dataflows in this context. The output's frontier should never advance
91    /// past this frontier, except the empty frontier.
92    pub dataflow_expiration: Antichain<mz_repr::Timestamp>,
93    /// The config set for this context.
94    pub config_set: Rc<ConfigSet>,
95}
96
97impl<'scope, T: RenderTimestamp> Context<'scope, T> {
98    /// Creates a new empty Context.
99    pub fn for_dataflow_in<Plan, O>(
100        dataflow: &DataflowDescription<Plan, CollectionMetadata, O>,
101        scope: Scope<'scope, T>,
102        compute_state: &ComputeState,
103        until: Antichain<mz_repr::Timestamp>,
104        dataflow_expiration: Antichain<mz_repr::Timestamp>,
105    ) -> Self {
106        use mz_ore::collections::CollectionExt as IteratorExt;
107        let dataflow_id = *scope.addr().into_first();
108        let as_of_frontier = dataflow
109            .as_of
110            .clone()
111            .unwrap_or_else(|| Antichain::from_elem(Timestamp::minimum()));
112
113        let export_ids = dataflow.export_ids().collect();
114
115        // Skip compute event logging for transient dataflows. We do this to avoid overhead for
116        // slow-path peeks, but it also affects subscribes. For now that seems fine, but we may
117        // want to reconsider in the future.
118        let compute_logger = if dataflow.is_transient() {
119            None
120        } else {
121            compute_state.compute_logger.clone()
122        };
123
124        Self {
125            scope,
126            debug_name: dataflow.debug_name.clone(),
127            dataflow_id,
128            export_ids,
129            as_of_frontier,
130            until,
131            bindings: BTreeMap::new(),
132            compute_logger,
133            linear_join_spec: compute_state.linear_join_spec,
134            dataflow_expiration,
135            config_set: Rc::clone(&compute_state.worker_config),
136        }
137    }
138}
139
140impl<'scope, T: RenderTimestamp> Context<'scope, T> {
141    /// Insert a collection bundle by an identifier.
142    ///
143    /// This is expected to be used to install external collections (sources, indexes, other views),
144    /// as well as for `Let` bindings of local collections.
145    pub fn insert_id(
146        &mut self,
147        id: Id,
148        collection: CollectionBundle<'scope, T>,
149    ) -> Option<CollectionBundle<'scope, T>> {
150        self.bindings.insert(id, collection)
151    }
152    /// Remove a collection bundle by an identifier.
153    ///
154    /// The primary use of this method is uninstalling `Let` bindings.
155    pub fn remove_id(&mut self, id: Id) -> Option<CollectionBundle<'scope, T>> {
156        self.bindings.remove(&id)
157    }
158    /// Melds a collection bundle to whatever exists.
159    pub fn update_id(&mut self, id: Id, collection: CollectionBundle<'scope, T>) {
160        if !self.bindings.contains_key(&id) {
161            self.bindings.insert(id, collection);
162        } else {
163            let binding = self
164                .bindings
165                .get_mut(&id)
166                .expect("Binding verified to exist");
167            if collection.collection.is_some() {
168                binding.collection = collection.collection;
169            }
170            for (key, flavor) in collection.arranged.into_iter() {
171                binding.arranged.insert(key, flavor);
172            }
173        }
174    }
175    /// Look up a collection bundle by an identifier.
176    pub fn lookup_id(&self, id: Id) -> Option<CollectionBundle<'scope, T>> {
177        self.bindings.get(&id).cloned()
178    }
179
180    pub(super) fn error_logger(&self) -> ErrorLogger {
181        ErrorLogger::new(self.debug_name.clone())
182    }
183}
184
185impl<'scope, T: RenderTimestamp> Context<'scope, T> {
186    /// Brings the underlying arrangements and collections into a region.
187    pub fn enter_region<'a>(
188        &self,
189        region: Scope<'a, T>,
190        bindings: Option<&std::collections::BTreeSet<Id>>,
191    ) -> Context<'a, T> {
192        let bindings = self
193            .bindings
194            .iter()
195            .filter(|(key, _)| bindings.as_ref().map(|b| b.contains(key)).unwrap_or(true))
196            .map(|(key, bundle)| (*key, bundle.enter_region(region)))
197            .collect();
198
199        Context {
200            scope: region,
201            debug_name: self.debug_name.clone(),
202            dataflow_id: self.dataflow_id.clone(),
203            export_ids: self.export_ids.clone(),
204            as_of_frontier: self.as_of_frontier.clone(),
205            until: self.until.clone(),
206            compute_logger: self.compute_logger.clone(),
207            linear_join_spec: self.linear_join_spec.clone(),
208            bindings,
209            dataflow_expiration: self.dataflow_expiration.clone(),
210            config_set: Rc::clone(&self.config_set),
211        }
212    }
213}
214
215/// Describes flavor of arrangement: local or imported trace.
216#[derive(Clone)]
217pub enum ArrangementFlavor<'scope, T: RenderTimestamp> {
218    /// A dataflow-local arrangement.
219    Local(
220        Arranged<'scope, RowRowAgent<T, Diff>>,
221        Arranged<'scope, ErrAgent<T, Diff>>,
222    ),
223    /// An imported trace from outside the dataflow.
224    ///
225    /// The `GlobalId` identifier exists so that exports of this same trace
226    /// can refer back to and depend on the original instance.
227    Trace(
228        GlobalId,
229        Arranged<'scope, RowRowEnter<mz_repr::Timestamp, Diff, T>>,
230        Arranged<'scope, ErrEnter<mz_repr::Timestamp, T>>,
231    ),
232}
233
234impl<'scope, T: RenderTimestamp> ArrangementFlavor<'scope, T> {
235    /// Constructs and applies logic to elements of `self` and returns the results.
236    ///
237    /// The `logic` callback receives a borrow of the decoded datum vector, a timestamp, a
238    /// diff, and two output sessions: one for `ok` updates of type `(D, T, Diff)` and one for
239    /// MFP-style `DataflowErrorSer` updates. It must return the number of records *produced*
240    /// (written to either session), not the number of input tuples consumed.
241    ///
242    /// # Fuel
243    ///
244    /// The operator accumulates the returned counts as fuel and yields when the total reaches
245    /// an internal refuel threshold. The metric is output-produced (not input-consumed) on
246    /// purpose: it regulates two asymmetric pressures.
247    ///
248    /// * **Drain inputs.** The operator holds a clone of each pending `Batch` until its work
249    ///   item pops; we want to release that memory back to the upstream arrangement as soon
250    ///   as possible. A `filter(false)` MFP returns 0 for every tuple, so fuel never trips
251    ///   and the cursor runs to end-of-batch in one activation.
252    /// * **Throttle outputs.** A `map("1KB-string")` MFP produces large records per input;
253    ///   stopping when emit count hits the threshold caps how much data a single activation
254    ///   dumps on the next operator.
255    ///
256    /// The refuel constant is a pragmatic compromise: large enough to be a non-event in
257    /// steady-state, small enough that one activation can't flood downstream. There is no
258    /// universal value across MFP shapes.
259    ///
260    /// If `key` is set, this is a promise that `logic` will produce no results on
261    /// records for which the key does not evaluate to the value. This is used to
262    /// leap directly to exactly those records.
263    ///
264    /// The `max_demand` parameter limits the number of columns decoded from the
265    /// input. Only the first `max_demand` columns are decoded. Pass `usize::MAX` to
266    /// decode all columns.
267    pub fn flat_map<DCB, L>(
268        &self,
269        key: Option<&Row>,
270        max_demand: usize,
271        logic: L,
272    ) -> (
273        Stream<'scope, T, DCB::Container>,
274        VecCollection<'scope, T, DataflowErrorSer, Diff>,
275    )
276    where
277        DCB: ContainerBuilder,
278        L: for<'a, 'b> FnMut(
279                &'a mut DatumVecBorrow<'b>,
280                T,
281                Diff,
282                &mut Session<T, DCB>,
283                &mut Session<T, ECB<T>>,
284            ) -> usize
285            + 'static,
286    {
287        // `logic` is passed straight through to `flat_map_core_fallible`, which owns the per-row
288        // decode (and the activation-scoped arena it decodes into).
289        match &self {
290            ArrangementFlavor::Local(oks, errs) => {
291                let (oks, mfp_errs) = CollectionBundle::<T>::flat_map_core_fallible::<_, DCB, _>(
292                    oks.clone(),
293                    key,
294                    max_demand,
295                    logic,
296                    REFUEL,
297                );
298                let errs = errs.clone().as_collection(|k, &()| k.clone());
299                let errs = errs.concat(mfp_errs.as_collection());
300                (oks, errs)
301            }
302            ArrangementFlavor::Trace(_, oks, errs) => {
303                let (oks, mfp_errs) = CollectionBundle::<T>::flat_map_core_fallible::<_, DCB, _>(
304                    oks.clone(),
305                    key,
306                    max_demand,
307                    logic,
308                    REFUEL,
309                );
310                let errs = errs.clone().as_collection(|k, &()| k.clone());
311                let errs = errs.concat(mfp_errs.as_collection());
312                (oks, errs)
313            }
314        }
315    }
316
317    /// Ok-only variant of [`Self::flat_map`]. The `logic` callback receives a single output
318    /// session, cannot produce errors, and returns the number of records produced (see
319    /// [`Self::flat_map`] for fuel semantics). The returned err collection comes solely from
320    /// the arrangement; no extra operator is built to carry an empty MFP-error stream.
321    pub fn flat_map_ok<DCB, L>(
322        &self,
323        key: Option<&Row>,
324        max_demand: usize,
325        logic: L,
326    ) -> (
327        Stream<'scope, T, DCB::Container>,
328        VecCollection<'scope, T, DataflowErrorSer, Diff>,
329    )
330    where
331        // No push bound here: it lives at `logic`'s `give` call site, so a caller can push
332        // borrowed records into a columnar builder that has no owned-tuple `Push`.
333        DCB: ContainerBuilder,
334        L: for<'a, 'b> FnMut(&'a mut DatumVecBorrow<'b>, T, Diff, &mut Session<T, DCB>) -> usize
335            + 'static,
336    {
337        match &self {
338            ArrangementFlavor::Local(oks, errs) => {
339                let oks = CollectionBundle::<T>::flat_map_core_ok::<_, DCB, _>(
340                    oks.clone(),
341                    key,
342                    max_demand,
343                    logic,
344                    REFUEL,
345                );
346                let errs = errs.clone().as_collection(|k, &()| k.clone());
347                (oks, errs)
348            }
349            ArrangementFlavor::Trace(_, oks, errs) => {
350                let oks = CollectionBundle::<T>::flat_map_core_ok::<_, DCB, _>(
351                    oks.clone(),
352                    key,
353                    max_demand,
354                    logic,
355                    REFUEL,
356                );
357                let errs = errs.clone().as_collection(|k, &()| k.clone());
358                (oks, errs)
359            }
360        }
361    }
362}
363impl<'scope, T: RenderTimestamp> ArrangementFlavor<'scope, T> {
364    /// The scope containing the collection bundle.
365    pub fn scope(&self) -> Scope<'scope, T> {
366        match self {
367            ArrangementFlavor::Local(oks, _errs) => oks.stream.scope(),
368            ArrangementFlavor::Trace(_gid, oks, _errs) => oks.stream.scope(),
369        }
370    }
371
372    /// Brings the arrangement flavor into a region.
373    pub fn enter_region<'a>(&self, region: Scope<'a, T>) -> ArrangementFlavor<'a, T> {
374        match self {
375            ArrangementFlavor::Local(oks, errs) => ArrangementFlavor::Local(
376                oks.clone().enter_region(region),
377                errs.clone().enter_region(region),
378            ),
379            ArrangementFlavor::Trace(gid, oks, errs) => ArrangementFlavor::Trace(
380                *gid,
381                oks.clone().enter_region(region),
382                errs.clone().enter_region(region),
383            ),
384        }
385    }
386}
387impl<'scope, T: RenderTimestamp> ArrangementFlavor<'scope, T> {
388    /// Extracts the arrangement flavor from a region.
389    pub fn leave_region<'outer>(&self, outer: Scope<'outer, T>) -> ArrangementFlavor<'outer, T> {
390        match self {
391            ArrangementFlavor::Local(oks, errs) => ArrangementFlavor::Local(
392                oks.clone().leave_region(outer),
393                errs.clone().leave_region(outer),
394            ),
395            ArrangementFlavor::Trace(gid, oks, errs) => ArrangementFlavor::Trace(
396                *gid,
397                oks.clone().leave_region(outer),
398                errs.clone().leave_region(outer),
399            ),
400        }
401    }
402}
403/// Rewrites an arranged error collection to hold each of its errors once.
404///
405/// Sound because query semantics depend only on whether an error is present, and correct under
406/// retraction only because it reads the accumulated collection: no pointwise function of the input
407/// diffs (a saturating add, a sign) can collapse multiplicity and still cancel when the errors
408/// retract.
409///
410/// NOTE: One consumer does read the multiplicity. Error-count introspection reports it as the
411/// number of failing rows, so `log_dataflow_errors` must see the collection before this collapses
412/// it, or a dataflow reports one error however many rows failed. Collapse after the logging, never
413/// before.
414pub(crate) fn distinct_arranged_errs<'a, T: RenderTimestamp>(
415    errs: Arranged<'a, ErrAgent<T, Diff>>,
416    name: &str,
417) -> Arranged<'a, ErrAgent<T, Diff>> {
418    errs.mz_reduce_abelian::<_, ErrBuilder<_, _>, ErrSpine<_, _>, _>(
419        name,
420        |_err, _input, output| output.push(((), Diff::ONE)),
421    )
422}
423
424/// Rewrites an error collection to hold each of its errors once.
425///
426/// Costs an arrangement more than [`distinct_arranged_errs`], which reuses the arrangement its
427/// input already has.
428pub(crate) fn distinct_errs_collection<'a, T: RenderTimestamp>(
429    errs: VecCollection<'a, T, DataflowErrorSer, Diff>,
430) -> VecCollection<'a, T, DataflowErrorSer, Diff> {
431    let errs: KeyCollection<_, _, _> = errs.into();
432    let errs = errs.mz_arrange::<ErrBatcher<_, _>, ErrSpine<_, _>>("Arrange errors");
433    distinct_arranged_errs(errs, "Distinct errors").as_collection(|err, _| err.clone())
434}
435
436/// A bundle of the various ways a collection can be represented.
437///
438/// This type maintains the invariant that it does contain at least one valid
439/// source of data, either a collection or at least one arrangement.
440#[derive(Clone)]
441pub struct CollectionBundle<'scope, T: RenderTimestamp> {
442    pub collection: Option<(
443        ColCollection<'scope, T>,
444        VecCollection<'scope, T, DataflowErrorSer, Diff>,
445    )>,
446    pub arranged: BTreeMap<Vec<LirScalarExpr>, ArrangementFlavor<'scope, T>>,
447}
448
449impl<'scope, T: RenderTimestamp> CollectionBundle<'scope, T> {
450    /// Construct a new collection bundle from a [`ColCollection`] and an error stream.
451    pub fn from_edge(
452        oks: ColCollection<'scope, T>,
453        errs: VecCollection<'scope, T, DataflowErrorSer, Diff>,
454    ) -> Self {
455        Self {
456            collection: Some((oks, errs)),
457            arranged: BTreeMap::default(),
458        }
459    }
460
461    /// Inserts arrangements by the expressions on which they are keyed.
462    pub fn from_expressions(
463        exprs: Vec<LirScalarExpr>,
464        arrangements: ArrangementFlavor<'scope, T>,
465    ) -> Self {
466        let mut arranged = BTreeMap::new();
467        arranged.insert(exprs, arrangements);
468        Self {
469            collection: None,
470            arranged,
471        }
472    }
473
474    /// Inserts arrangements by the columns on which they are keyed.
475    pub fn from_columns<I: IntoIterator<Item = usize>>(
476        columns: I,
477        arrangements: ArrangementFlavor<'scope, T>,
478    ) -> Self {
479        let mut keys = Vec::new();
480        for column in columns {
481            keys.push(LirScalarExpr::column(column));
482        }
483        Self::from_expressions(keys, arrangements)
484    }
485
486    /// The scope containing the collection bundle.
487    pub fn scope(&self) -> Scope<'scope, T> {
488        if let Some((oks, _errs)) = &self.collection {
489            oks.scope()
490        } else {
491            self.arranged
492                .values()
493                .next()
494                .expect("Must contain a valid collection")
495                .scope()
496        }
497    }
498
499    /// Collapses the multiplicity of every error this bundle carries to one.
500    ///
501    /// Belongs at the definition of a binding that more than one `Get` reads. Each reader
502    /// propagates the binding's errors independently, so a binding read `f` times contributes its
503    /// errors `f` times to the dataflow's error output, and those factors apply again at every
504    /// further level of sharing: a chain of diamonds multiplies rather than adds, and reaches
505    /// `Diff` overflow at a depth plans really do have. Collapsing at each definition holds the
506    /// dataflow's error multiplicity to the fan-out of a single level.
507    ///
508    /// Sound because error semantics depend only on whether an error is present, and correct under
509    /// retraction only because it reads the accumulated collection: no pointwise function of the
510    /// input diffs (a saturating add, a sign) can collapse multiplicity and still cancel when the
511    /// errors retract.
512    ///
513    /// Collapses every form the bundle offers, not just one. Each form carries its own error
514    /// stream, and those streams differ in content as well as identity: an arrangement's errors
515    /// include the key-formation errors that the raw collection's do not. Which form a consumer
516    /// reads is the consumer's choice, and a delta join reads both within one operator, so a
517    /// binding's definition cannot know which form to collapse.
518    ///
519    /// NOTE: Leaves imported arrangements (`ArrangementFlavor::Trace`) alone, whose error traces
520    /// this dataflow cannot rewrite in place. Their errors arrive bounded by the exporting
521    /// dataflow's last level of sharing rather than collapsed to one, since nothing collapses at an
522    /// export. A global read more than once within one dataflow is not collapsed either, because
523    /// only local bindings reach this.
524    pub fn distinct_errs(mut self) -> Self {
525        if let Some((oks, errs)) = self.collection.take() {
526            self.collection = Some((oks, distinct_errs_collection(errs)));
527        }
528        for (key, flavor) in std::mem::take(&mut self.arranged) {
529            let flavor = match flavor {
530                ArrangementFlavor::Local(oks, errs) => {
531                    // Names the key, not the binding: an operator name carrying a `LocalId` would
532                    // churn the introspection goldens every time the optimizer renumbers locals.
533                    let name = format!("Distinct errors[{key:?}]");
534                    ArrangementFlavor::Local(oks, distinct_arranged_errs(errs, &name))
535                }
536                flavor @ ArrangementFlavor::Trace(..) => flavor,
537            };
538            self.arranged.insert(key, flavor);
539        }
540        self
541    }
542
543    /// Brings the collection bundle into a region.
544    pub fn enter_region<'inner>(&self, region: Scope<'inner, T>) -> CollectionBundle<'inner, T> {
545        CollectionBundle {
546            collection: self.collection.as_ref().map(|(oks, errs)| {
547                (
548                    oks.clone().enter_region(region),
549                    errs.clone().enter_region(region),
550                )
551            }),
552            arranged: self
553                .arranged
554                .iter()
555                .map(|(key, bundle)| (key.clone(), bundle.enter_region(region)))
556                .collect(),
557        }
558    }
559}
560
561impl<'scope, T: RenderTimestamp> CollectionBundle<'scope, T> {
562    /// Extracts the collection bundle from a region.
563    pub fn leave_region<'outer>(&self, outer: Scope<'outer, T>) -> CollectionBundle<'outer, T> {
564        CollectionBundle {
565            collection: self.collection.as_ref().map(|(oks, errs)| {
566                (
567                    oks.clone().leave_region(outer),
568                    errs.clone().leave_region(outer),
569                )
570            }),
571            arranged: self
572                .arranged
573                .iter()
574                .map(|(key, bundle)| (key.clone(), bundle.leave_region(outer)))
575                .collect(),
576        }
577    }
578}
579
580impl<'scope, T: RenderTimestamp> CollectionBundle<'scope, T> {
581    /// Asserts that the arrangement for a specific key
582    /// (or the raw collection for no key) exists,
583    /// and returns the corresponding collection.
584    ///
585    /// This returns the collection as-is, without
586    /// doing any unthinning transformation.
587    /// Therefore, it should be used when the appropriate transformation
588    /// was planned as part of a following MFP.
589    ///
590    /// If `key` is specified, the function converts the arrangement to a collection using a
591    /// fueled `flat_map` operator.
592    ///
593    /// The keyed path materializes the arrangement as the columnar edge. The unkeyed path
594    /// returns the unarranged `.collection` edge with its variant intact.
595    pub fn as_specific_collection(
596        &self,
597        key: Option<&[LirScalarExpr]>,
598    ) -> (
599        ColCollection<'scope, T>,
600        VecCollection<'scope, T, DataflowErrorSer, Diff>,
601    ) {
602        // Any operator that uses this method was told to use a particular
603        // collection during LIR planning, where we should have made
604        // sure that that collection exists.
605        //
606        // If it doesn't, we panic.
607        match key {
608            None => self
609                .collection
610                .clone()
611                .expect("The unarranged collection doesn't exist."),
612            Some(key) => {
613                let arranged = self.arranged.get(key).unwrap_or_else(|| {
614                    panic!("The collection arranged by {:?} doesn't exist.", key)
615                });
616                // Output is 1:1 from the already-consolidated cursor, so a
617                // non-consolidating `ColumnBuilder` suffices. `max_demand` is
618                // `usize::MAX` because the materialized collection carries every column.
619                let (ok, err) =
620                    arranged.flat_map_ok::<ColumnBuilder<(Row, T, Diff)>, _>(None, usize::MAX, {
621                        // `give` copies the bytes into the column, so one buffer
622                        // serves every record.
623                        let mut row_buf = Row::default();
624                        move |borrow, t, r, ok_session| {
625                            row_buf.packer().extend(borrow.iter());
626                            ok_session.give((&row_buf, &t, &r));
627                            1
628                        }
629                    });
630                (ok.as_collection(), err)
631            }
632        }
633    }
634
635    /// Constructs and applies logic to elements of a collection and returns the results.
636    ///
637    /// The function applies `logic` on elements. The logic conceptually receives
638    /// `(&Row, &Row)` pairs in the form of a datum vec in the expected order.
639    ///
640    /// If `key_val` is set, this is a promise that `logic` will produce no results on
641    /// records for which the key does not evaluate to the value. This is used when we
642    /// have an arrangement by that key to leap directly to exactly those records.
643    /// It is important that `logic` still guard against data that does not satisfy
644    /// this constraint, as this method does not statically know that it will have
645    /// that arrangement.
646    ///
647    /// The `max_demand` parameter limits the number of columns decoded from the
648    /// input. Only the first `max_demand` columns are decoded. Pass `usize::MAX` to
649    /// decode all columns.
650    pub fn flat_map<DCB, L>(
651        &self,
652        key_val: Option<(Vec<LirScalarExpr>, Option<Row>)>,
653        max_demand: usize,
654        logic: L,
655    ) -> (
656        Stream<'scope, T, DCB::Container>,
657        VecCollection<'scope, T, DataflowErrorSer, Diff>,
658    )
659    where
660        DCB: ContainerBuilder,
661        L: for<'a> FnMut(
662                &'a mut DatumVecBorrow<'_>,
663                T,
664                Diff,
665                &mut Session<T, DCB>,
666                &mut Session<T, ECB<T>>,
667            ) -> usize
668            + 'static,
669    {
670        // If `key_val` is set, we should have to use the corresponding arrangement.
671        // If there isn't one, that implies an error in the contract between
672        // key-production and available arrangements.
673        if let Some((key, val)) = key_val {
674            self.arrangement(&key)
675                .expect("Should have ensured during planning that this arrangement exists.")
676                .flat_map::<DCB, _>(val.as_ref(), max_demand, logic)
677        } else {
678            let (oks, errs) = self
679                .collection
680                .clone()
681                .expect("Invariant violated: CollectionBundle contains no collection.");
682            let (ok_stream, err_stream) =
683                flat_map_datums::<_, DCB, _>(oks, "CollectionFlatMap", max_demand, logic);
684            let errs = errs.concat(err_stream.as_collection());
685            (ok_stream, errs)
686        }
687    }
688
689    /// Factored out common logic for using literal keys in general traces.
690    ///
691    /// This logic is sufficiently interesting that we want to write it only
692    /// once, and thereby avoid any skew in the two uses of the logic.
693    ///
694    /// The function presents the contents of the trace as `(key, value, time, delta)` tuples,
695    /// where key and value are potentially specialized, but convertible into rows. The `logic`
696    /// callback writes ok results into the first session and errors into the second, returning
697    /// the number of records produced. See [`ArrangementFlavor::flat_map`] for the fuel
698    /// rationale.
699    fn flat_map_core_fallible<Tr, DCB, L>(
700        trace: Arranged<'scope, Tr>,
701        key: Option<&<<BatchCursor<Tr> as Cursor>::KeyContainer as BatchContainer>::Owned>,
702        max_demand: usize,
703        mut logic: L,
704        refuel: usize,
705    ) -> (
706        Stream<'scope, T, DCB::Container>,
707        Stream<'scope, T, Vec<(DataflowErrorSer, T, Diff)>>,
708    )
709    where
710        Tr: TraceReader<Batch: Navigable, Time = T> + Clone + 'static,
711        for<'a> BatchCursor<Tr>:
712            Cursor<Key<'a>: ExtendDatums, Val<'a>: ExtendDatums, Time = T, Diff = mz_repr::Diff>,
713        <<BatchCursor<Tr> as Cursor>::KeyContainer as BatchContainer>::Owned: PartialEq,
714        DCB: ContainerBuilder,
715        // `logic` receives the key and value already decoded into a `DatumVecBorrow`. The decode
716        // (and its arena/`DatumVec`) lives in the per-activation closure below, so it is scoped to
717        // a single scheduling invocation rather than to the operator.
718        L: for<'a, 'b> FnMut(
719                &'a mut DatumVecBorrow<'b>,
720                T,
721                mz_repr::Diff,
722                &mut Session<T, DCB>,
723                &mut Session<T, ECB<T>>,
724            ) -> usize
725            + 'static,
726    {
727        let scope = trace.stream.scope();
728
729        let mut key_con = <BatchCursor<Tr> as Cursor>::KeyContainer::with_capacity(1);
730        if let Some(key) = &key {
731            key_con.push_own(key);
732        }
733        let mode = if key.is_some() { "index" } else { "scan" };
734        let name = format!("ArrangementFlatMap({})", mode);
735
736        let mut builder = OperatorBuilder::new(name, scope.clone());
737        let (ok_output, ok_stream) = builder.new_output();
738        let mut ok_output = OutputBuilder::<_, DCB>::from(ok_output);
739        let (err_output, err_stream) = builder.new_output();
740        let mut err_output = OutputBuilder::<_, ECB<T>>::from(err_output);
741        let mut input = builder.new_input(trace.stream.clone(), Pipeline);
742        let operator_info = builder.operator_info();
743
744        builder.build(move |_capabilities| {
745            // Acquire an activator to reschedule the operator when it has unfinished work.
746            let activator = scope.activator_for(operator_info.address);
747            // Maintain a list of work to do, cursor to navigate and process.
748            let mut todo = std::collections::VecDeque::new();
749            move |_frontiers| {
750                let key = key_con.get(0);
751                let mut ok_output = ok_output.activate();
752                let mut err_output = err_output.activate();
753
754                // First, dequeue all batches.
755                input.for_each(|time, data| {
756                    // Retain a capability for each output, as the work may complete across
757                    // multiple activations.
758                    let ok_cap = time.retain_stamp(0);
759                    let err_cap = time.retain_stamp(1);
760                    for span in data.iter() {
761                        let Some(batch) = &span.inner else {
762                            continue;
763                        };
764                        todo.push_back(PendingWork::new(
765                            ok_cap.clone(),
766                            err_cap.clone(),
767                            batch.cursor(),
768                            batch.clone(),
769                        ));
770                    }
771                });
772
773                // Decode the key/value of each record into datums for `logic`. The arena and datum
774                // buffer are created here, so they are scoped to this activation (dropped when it
775                // returns) rather than retained for the operator's lifetime; both are reused across
776                // the records processed within the activation.
777                let mut temp_storage = RowArena::new();
778                let mut datums = DatumVec::new();
779                let mut decode_logic =
780                    |k: BatchKey<'_, Tr>,
781                     v: BatchVal<'_, Tr>,
782                     t: T,
783                     d: mz_repr::Diff,
784                     ok_session: &mut Session<T, DCB>,
785                     err_session: &mut Session<T, ECB<T>>| {
786                        temp_storage.clear();
787                        let mut datums_borrow = datums.borrow();
788                        k.extend_datums(&temp_storage, &mut datums_borrow, Some(max_demand));
789                        let remaining = max_demand.saturating_sub(datums_borrow.len());
790                        v.extend_datums(&temp_storage, &mut datums_borrow, Some(remaining));
791                        logic(&mut datums_borrow, t, d, ok_session, err_session)
792                    };
793
794                // Second, make progress on `todo`.
795                let mut fuel = refuel;
796                while !todo.is_empty() && fuel > 0 {
797                    todo.front_mut().unwrap().do_work(
798                        key.as_ref(),
799                        &mut decode_logic,
800                        &mut fuel,
801                        &mut ok_output,
802                        &mut err_output,
803                    );
804                    if fuel > 0 {
805                        todo.pop_front();
806                    }
807                }
808                // If we have not finished all work, re-activate the operator.
809                if !todo.is_empty() {
810                    activator.activate();
811                }
812            }
813        });
814
815        (ok_stream, err_stream)
816    }
817
818    /// Ok-only variant of [`Self::flat_map_core_fallible`]. The `logic` callback writes results
819    /// into a single output session and returns the number of records produced (see the
820    /// fallible variant for fuel semantics). Use this when the caller statically knows it
821    /// will never produce `DataflowErrorSer` records, to avoid building a second output port
822    /// and the empty err stream that would follow it.
823    fn flat_map_core_ok<Tr, DCB, L>(
824        trace: Arranged<'scope, Tr>,
825        key: Option<&<<BatchCursor<Tr> as Cursor>::KeyContainer as BatchContainer>::Owned>,
826        max_demand: usize,
827        mut logic: L,
828        refuel: usize,
829    ) -> Stream<'scope, T, DCB::Container>
830    where
831        Tr: TraceReader<Batch: Navigable, Time = T> + Clone + 'static,
832        for<'a> BatchCursor<Tr>:
833            Cursor<Key<'a>: ExtendDatums, Val<'a>: ExtendDatums, Time = T, Diff = mz_repr::Diff>,
834        <<BatchCursor<Tr> as Cursor>::KeyContainer as BatchContainer>::Owned: PartialEq,
835        DCB: ContainerBuilder,
836        L: for<'a, 'b> FnMut(
837                &'a mut DatumVecBorrow<'b>,
838                T,
839                mz_repr::Diff,
840                &mut Session<T, DCB>,
841            ) -> usize
842            + 'static,
843    {
844        let scope = trace.stream.scope();
845
846        let mut key_con = <BatchCursor<Tr> as Cursor>::KeyContainer::with_capacity(1);
847        if let Some(key) = &key {
848            key_con.push_own(key);
849        }
850        let mode = if key.is_some() { "index" } else { "scan" };
851        let name = format!("ArrangementFlatMapOk({})", mode);
852
853        let mut builder = OperatorBuilder::new(name, scope.clone());
854        let (ok_output, ok_stream) = builder.new_output();
855        let mut ok_output = OutputBuilder::<_, DCB>::from(ok_output);
856        let mut input = builder.new_input(trace.stream.clone(), Pipeline);
857        let operator_info = builder.operator_info();
858
859        builder.build(move |_capabilities| {
860            let activator = scope.activator_for(operator_info.address);
861            let mut todo = std::collections::VecDeque::new();
862            move |_frontiers| {
863                let key = key_con.get(0);
864                let mut ok_output = ok_output.activate();
865
866                input.for_each(|time, data| {
867                    let cap = time.retain_stamp(0);
868                    for span in data.iter() {
869                        let Some(batch) = &span.inner else {
870                            continue;
871                        };
872                        todo.push_back(PendingWorkOk::new(
873                            cap.clone(),
874                            batch.cursor(),
875                            batch.clone(),
876                        ));
877                    }
878                });
879
880                // Activation-scoped decode storage; see `flat_map_core_fallible`.
881                let mut temp_storage = RowArena::new();
882                let mut datums = DatumVec::new();
883                let mut decode_logic =
884                    |k: BatchKey<'_, Tr>,
885                     v: BatchVal<'_, Tr>,
886                     t: T,
887                     d: mz_repr::Diff,
888                     ok_session: &mut Session<T, DCB>| {
889                        temp_storage.clear();
890                        let mut datums_borrow = datums.borrow();
891                        k.extend_datums(&temp_storage, &mut datums_borrow, Some(max_demand));
892                        let remaining = max_demand.saturating_sub(datums_borrow.len());
893                        v.extend_datums(&temp_storage, &mut datums_borrow, Some(remaining));
894                        logic(&mut datums_borrow, t, d, ok_session)
895                    };
896
897                let mut fuel = refuel;
898                while !todo.is_empty() && fuel > 0 {
899                    todo.front_mut().unwrap().do_work(
900                        key.as_ref(),
901                        &mut decode_logic,
902                        &mut fuel,
903                        &mut ok_output,
904                    );
905                    if fuel > 0 {
906                        todo.pop_front();
907                    }
908                }
909                if !todo.is_empty() {
910                    activator.activate();
911                }
912            }
913        });
914
915        ok_stream
916    }
917
918    /// Look up an arrangement by the expressions that form the key.
919    ///
920    /// The result may be `None` if no such arrangement exists, or it may be one of many
921    /// "arrangement flavors" that represent the types of arranged data we might have.
922    pub fn arrangement(&self, key: &[LirScalarExpr]) -> Option<ArrangementFlavor<'scope, T>> {
923        self.arranged.get(key).map(|x| x.clone())
924    }
925}
926
927impl<'scope, T: RenderTimestamp> CollectionBundle<'scope, T> {
928    /// Presents `self` as a stream of updates, having been subjected to `mfp`.
929    ///
930    /// This operator is able to apply the logic of `mfp` early, which can substantially
931    /// reduce the amount of data produced when `mfp` is non-trivial.
932    ///
933    /// The `key_val` argument, when present, indicates that a specific arrangement should
934    /// be used, and if, in addition, the `val` component is present,
935    /// that we can seek to the supplied row.
936    pub fn as_collection_core(
937        &self,
938        mut mfp_plan: MfpPlan<LirScalarExpr>,
939        key_val: Option<(Vec<LirScalarExpr>, Option<StableRow>)>,
940        until: Antichain<mz_repr::Timestamp>,
941    ) -> (
942        ColCollection<'scope, T>,
943        VecCollection<'scope, T, DataflowErrorSer, Diff>,
944    ) {
945        // Unwrap the stable-serialization row wrapper, seeking works on
946        // plain rows.
947        let key_val = key_val.map(|(key, val)| (key, val.map(|val| val.0)));
948        // If the MFP is trivial, we can just return the collection.
949        // In the case that we weren't going to apply the `key_val` optimization,
950        // this path results in a slightly smaller and faster
951        // dataflow graph, and is intended to fix
952        // https://github.com/MaterializeInc/database-issues/issues/3111
953        let has_key_val = if let Some((_key, Some(_val))) = &key_val {
954            true
955        } else {
956            false
957        };
958
959        if mfp_plan.is_identity() && !has_key_val {
960            let key = key_val.map(|(k, _v)| k);
961            return match key {
962                // Unarranged identity hands the edge straight through, so a columnar
963                // producer stays columnar.
964                None => self
965                    .collection
966                    .clone()
967                    .expect("The unarranged collection doesn't exist."),
968                Some(key) => self.as_specific_collection(Some(&key)),
969            };
970        }
971
972        let max_demand = mfp_plan.demand().last().map(|x| *x + 1).unwrap_or(0);
973        mfp_plan.permute_fn(|c| c, max_demand);
974
975        let mut datum_vec = DatumVec::new();
976        // Wrap in an `Rc` so that lifetimes work out.
977        let until = std::rc::Rc::new(until);
978
979        // `ConsolidatingColumnBuilder` folds within-batch duplicates. It consolidates in
980        // place, so records are given owned, which costs nothing here because
981        // `mfp_plan.evaluate` already produces a fresh `Row` per result.
982        let (stream, errors) = self.flat_map::<ConsolidatingColumnBuilder<Row, T, Diff>, _>(
983            key_val,
984            max_demand,
985            move |row_datums, time, diff, ok_session, err_session| {
986                let mut row_builder = SharedRow::get();
987                let until = std::rc::Rc::clone(&until);
988                let temp_storage = RowArena::new();
989                let row_iter = row_datums.iter();
990                let mut datums_local = datum_vec.borrow();
991                datums_local.extend(row_iter);
992                let event_time = time.event_time();
993                let mut work: usize = 0;
994                for result in mfp_plan.evaluate(
995                    &mut datums_local,
996                    &temp_storage,
997                    event_time,
998                    diff.clone(),
999                    move |time| !until.less_equal(time),
1000                    &mut row_builder,
1001                ) {
1002                    work += 1;
1003                    match result {
1004                        Ok((row, event_time, diff)) => {
1005                            // Copy the whole time, and re-populate event time.
1006                            let mut time: T = time.clone();
1007                            *time.event_time_mut() = event_time;
1008                            ok_session.give((row, time, diff));
1009                        }
1010                        Err((e, event_time, diff)) => {
1011                            // Copy the whole time, and re-populate event time.
1012                            let mut time: T = time.clone();
1013                            *time.event_time_mut() = event_time;
1014                            err_session.give((e, time, diff));
1015                        }
1016                    }
1017                }
1018                work
1019            },
1020        );
1021
1022        (stream.as_collection(), errors)
1023    }
1024    pub fn ensure_collections(
1025        mut self,
1026        collections: AvailableCollections,
1027        input_key: Option<Vec<LirScalarExpr>>,
1028        input_mfp: MfpPlan<LirScalarExpr>,
1029        as_of: Antichain<mz_repr::Timestamp>,
1030        until: Antichain<mz_repr::Timestamp>,
1031        config_set: &ConfigSet,
1032        strategy: ArrangementStrategy,
1033    ) -> Self
1034    where
1035        T: MaybeBucketByTime,
1036    {
1037        if collections == Default::default() {
1038            return self;
1039        }
1040        // Cache collection to avoid reforming it each time.
1041        //
1042        // TODO(mcsherry): In theory this could be faster run out of another arrangement,
1043        // as the `map_fallible` that follows could be run against an arrangement itself.
1044        //
1045        // Note(btv): If we ever do that, we would then only need to make the raw collection here
1046        // if `collections.raw` is true.
1047
1048        for (key, _, _) in collections.arranged.iter() {
1049            soft_assert_or_log!(
1050                !self.arranged.contains_key(key),
1051                "LIR ArrangeBy tried to create an existing arrangement"
1052            );
1053        }
1054
1055        // Track whether we already applied temporal bucketing in this call, to
1056        // avoid bucketing the same updates twice.
1057        let mut bucketed = false;
1058
1059        // True iff at least one new arrangement will actually be built below. Bucketing only
1060        // pays off when something downstream merges/compacts the future-stamped updates; on a
1061        // pure raw collection (no new arrangement) the work is wasted.
1062        let will_create_arrangement = collections
1063            .arranged
1064            .iter()
1065            .any(|(key, _, _)| !self.arranged.contains_key(key));
1066
1067        // We need the collection if either (1) it is explicitly demanded, or (2) we are going to render any arrangement
1068        let form_raw_collection = collections.raw || will_create_arrangement;
1069        if form_raw_collection && self.collection.is_none() {
1070            let (oks, errs) =
1071                self.as_collection_core(input_mfp, input_key.map(|k| (k, None)), until);
1072            // Apply temporal bucketing when the lowering selected `TemporalBucketing` and
1073            // we will build at least one arrangement. This path fires when the collection
1074            // must be formed from scratch (e.g., from an arrangement via as_collection_core).
1075            let effective_strategy = if will_create_arrangement {
1076                strategy
1077            } else {
1078                ArrangementStrategy::Direct
1079            };
1080            let oks = if matches!(effective_strategy, ArrangementStrategy::TemporalBucketing) {
1081                let summary: mz_repr::Timestamp = TEMPORAL_BUCKETING_SUMMARY
1082                    .get(config_set)
1083                    .try_into()
1084                    .expect("must fit");
1085                bucketed = true;
1086                // Temporal bucketing is columnar throughout, so no round trip here.
1087                T::maybe_apply_temporal_bucketing(oks.inner, as_of.clone(), summary)
1088            } else {
1089                oks
1090            };
1091            self.collection = Some((oks, errs));
1092        }
1093        for (key, _, thinning) in collections.arranged {
1094            if !self.arranged.contains_key(&key) {
1095                // TODO: Consider allowing more expressive names.
1096                let name = format!("ArrangeBy[{:?}]", key);
1097
1098                let (oks, errs) = self
1099                    .collection
1100                    .take()
1101                    .expect("Collection constructed above");
1102                // Apply temporal bucketing if the collection already existed on
1103                // the bundle (e.g., from an upstream temporal Mfp or Get) and we
1104                // haven't bucketed yet. This is the common path for temporal-MFP
1105                // → ArrangeBy flows.
1106                let effective_strategy = if bucketed {
1107                    ArrangementStrategy::Direct
1108                } else {
1109                    strategy
1110                };
1111                let oks = if matches!(effective_strategy, ArrangementStrategy::TemporalBucketing) {
1112                    let summary: mz_repr::Timestamp = TEMPORAL_BUCKETING_SUMMARY
1113                        .get(config_set)
1114                        .try_into()
1115                        .expect("must fit");
1116                    bucketed = true;
1117                    // Temporal bucketing is columnar throughout, so no round trip here.
1118                    T::maybe_apply_temporal_bucketing(oks.inner, as_of.clone(), summary)
1119                } else {
1120                    oks
1121                };
1122                let batcher = ArrangementBatcher::from_config(config_set);
1123                let (oks, errs_keyed, passthrough) =
1124                    Self::arrange_collection(&name, oks, key.clone(), thinning.clone(), batcher);
1125                let errs_concat: KeyCollection<_, _, _> = errs.clone().concat(errs_keyed).into();
1126                self.collection = Some((passthrough, errs));
1127                let errs = errs_concat
1128                    .mz_arrange::<ErrBatcher<_, _>, ErrSpine<_, _>>(&format!("{}-errors", name));
1129                self.arranged
1130                    .insert(key, ArrangementFlavor::Local(oks, errs));
1131            }
1132        }
1133        self
1134    }
1135
1136    /// Builds an arrangement from a collection, using the specified key and value thinning.
1137    ///
1138    /// The arrangement's key is based on the `key` expressions, and the value the input with
1139    /// the `thinning` applied to it. It selects which of the input columns are included in the
1140    /// value of the arrangement. The thinning is in support of permuting arrangements such that
1141    /// columns in the key are not included in the value.
1142    ///
1143    /// In addition to the ok and err streams, we produce a passthrough stream that forwards
1144    /// the input as-is, which allows downstream consumers to reuse the collection without
1145    /// teeing the stream.
1146    fn arrange_collection(
1147        name: &String,
1148        oks: ColCollection<'scope, T>,
1149        key: Vec<LirScalarExpr>,
1150        thinning: Vec<usize>,
1151        batcher: ArrangementBatcher,
1152    ) -> (
1153        Arranged<'scope, RowRowAgent<T, Diff>>,
1154        VecCollection<'scope, T, DataflowErrorSer, Diff>,
1155        ColCollection<'scope, T>,
1156    ) {
1157        // Spelled out rather than `map_fallible`, whose closure cannot return the references
1158        // a columnar stream is pushed from.
1159        //
1160        // The arena is per-activation and cleared per row, so the capacity it retains never
1161        // outlives a scheduling invocation.
1162        let (ok_stream, err_stream, passthrough) = {
1163            let mut builder =
1164                OperatorBuilder::new("FormArrangementKey".to_string(), oks.inner.scope());
1165            let (ok_output, ok_stream) = builder.new_output();
1166            let mut ok_output =
1167                OutputBuilder::<_, ColumnBuilder<((Row, Row), T, Diff)>>::from(ok_output);
1168            let (err_output, err_stream) = builder.new_output();
1169            let mut err_output = OutputBuilder::from(err_output);
1170            let (passthrough_output, passthrough_stream) = builder.new_output();
1171            let mut passthrough_output =
1172                OutputBuilder::<_, NoopBuilder<Column<(Row, T, Diff)>>>::from(passthrough_output);
1173            let mut input = builder.new_input(oks.inner, Pipeline);
1174            builder.set_notify_for(0, FrontierInterest::Never);
1175            builder.build(move |_capabilities| {
1176                let mut key_buf = Row::default();
1177                let mut val_buf = Row::default();
1178                let mut datums = DatumVec::new();
1179                move |_frontiers| {
1180                    // Scoped to the activation so the arena's retained capacity does not
1181                    // outlive a single scheduling invocation; cleared per row to reuse it
1182                    // within the batch.
1183                    let mut temp_storage = RowArena::new();
1184                    let mut ok_output = ok_output.activate();
1185                    let mut err_output = err_output.activate();
1186                    let mut passthrough_output = passthrough_output.activate();
1187                    input.for_each(|time, data| {
1188                        let mut ok_session = ok_output.session_with_builder(&time);
1189                        let mut err_session = err_output.session(&time);
1190                        // Rows are read from the borrowed column, never materialized as
1191                        // owned `Row`s. Times and diffs are owned only on the error path.
1192                        for (row, t, d) in data.borrow().into_index_iter() {
1193                            temp_storage.clear();
1194                            let datums = datums.borrow_with(row);
1195                            let key_iter = key.iter().map(|k| k.eval(&datums, &temp_storage));
1196                            match key_buf.packer().try_extend(key_iter) {
1197                                Ok(()) => {
1198                                    let val_datum_iter = thinning.iter().map(|c| datums[*c]);
1199                                    val_buf.packer().extend(val_datum_iter);
1200                                    ok_session.give(((&*key_buf, &*val_buf), t, d));
1201                                }
1202                                Err(e) => {
1203                                    err_session.give((
1204                                        e.into(),
1205                                        Columnar::into_owned(t),
1206                                        Columnar::into_owned(d),
1207                                    ));
1208                                }
1209                            }
1210                        }
1211                        passthrough_output
1212                            .session_with_builder(&time)
1213                            .give_container(data);
1214                    });
1215                }
1216            });
1217            (ok_stream, err_stream, passthrough_stream.as_collection())
1218        };
1219
1220        let exchange =
1221            ExchangeCore::<ColumnBuilder<_>, _>::new_core(columnar_exchange::<Row, Row, T, Diff>);
1222        let oks = match batcher {
1223            ArrangementBatcher::Chunked => ok_stream
1224                .mz_arrange_core::<_, RowRowChunkedBatcher<T>, RowRowSpine<_, _>>(exchange, name),
1225            ArrangementBatcher::Columnar => ok_stream
1226                .mz_arrange_core::<_, RowRowColumnarBatcher<T>, RowRowSpine<_, _>>(exchange, name),
1227            ArrangementBatcher::Columnation => ok_stream
1228                .mz_arrange_core::<_, RowRowColumnationBatcher<_, T>, RowRowSpine<_, _>>(
1229                    exchange, name,
1230                ),
1231        };
1232        (oks, err_stream.as_collection(), passthrough)
1233    }
1234}
1235
1236/// A session over one output of an arrangement-reading operator.
1237///
1238/// The container builder `CB` is left to the caller, so sessions can drive consolidating,
1239/// capacity, or columnar output builders without changing call sites.
1240///
1241/// The capability is a whole [`CapabilitySet`]: a batch message's stamp carries every capability
1242/// the arrange operator retired with it, and need not be a singleton.
1243pub(crate) type Session<'a, 'b, T, CB> =
1244    timely::dataflow::operators::generic::Session<'a, 'b, T, CB, CapabilitySet<T>>;
1245
1246/// Container builder used for the err output of every flat_map variant. Pre-refactor the
1247/// merged Ok/Err stream flowed through a [`ConsolidatingContainerBuilder`] before the
1248/// `map_fallible` demux split it; we preserve that consolidation here so errors with the
1249/// same `(error, time)` cancel within a batch rather than propagating to downstream.
1250pub(crate) type ECB<T> = ConsolidatingContainerBuilder<Vec<(DataflowErrorSer, T, Diff)>>;
1251
1252/// Number of output records the arrangement flat_map operators may produce before yielding.
1253/// See [`ArrangementFlavor::flat_map`] for the fuel rationale; the constant is a pragmatic
1254/// compromise and not tuned empirically.
1255const REFUEL: usize = 1_000_000;
1256
1257struct PendingWork<C>
1258where
1259    C: Cursor,
1260{
1261    /// Capabilities for the `ok` output (output port 0), covering the batch's stamp.
1262    ok_capability: CapabilitySet<C::Time>,
1263    /// Capabilities for the `err` output (output port 1), covering the batch's stamp.
1264    err_capability: CapabilitySet<C::Time>,
1265    cursor: C,
1266    batch: C::Storage,
1267}
1268
1269impl<C> PendingWork<C>
1270where
1271    C: Cursor<KeyContainer: BatchContainer<Owned: PartialEq + Sized>>,
1272{
1273    /// Create a new bundle of pending work, from a pair of capabilities (one per output),
1274    /// a cursor, and backing storage.
1275    fn new(
1276        ok_capability: CapabilitySet<C::Time>,
1277        err_capability: CapabilitySet<C::Time>,
1278        cursor: C,
1279        batch: C::Storage,
1280    ) -> Self {
1281        Self {
1282            ok_capability,
1283            err_capability,
1284            cursor,
1285            batch,
1286        }
1287    }
1288    /// Perform roughly `fuel` work through the cursor, applying `logic` and sending results to
1289    /// the two output sessions.
1290    fn do_work<DCB, L>(
1291        &mut self,
1292        key: Option<&C::Key<'_>>,
1293        logic: &mut L,
1294        fuel: &mut usize,
1295        ok_output: &mut OutputBuilderSession<'_, C::Time, DCB>,
1296        err_output: &mut OutputBuilderSession<'_, C::Time, ECB<C::Time>>,
1297    ) where
1298        DCB: ContainerBuilder,
1299        L: FnMut(
1300            C::Key<'_>,
1301            C::Val<'_>,
1302            C::Time,
1303            C::Diff,
1304            &mut Session<C::Time, DCB>,
1305            &mut Session<C::Time, ECB<C::Time>>,
1306        ) -> usize,
1307    {
1308        let mut ok_session = ok_output.session_with_builder(&self.ok_capability);
1309        let mut err_session = err_output.session_with_builder(&self.err_capability);
1310        walk_cursor(&mut self.cursor, &self.batch, key, fuel, |k, v, t, d| {
1311            logic(k, v, t, d, &mut ok_session, &mut err_session)
1312        });
1313    }
1314}
1315
1316/// Pending work for the Ok-only variant of `flat_map_core_fallible`. Holds a single capability since
1317/// the operator has only one output port.
1318struct PendingWorkOk<C>
1319where
1320    C: Cursor,
1321{
1322    capability: CapabilitySet<C::Time>,
1323    cursor: C,
1324    batch: C::Storage,
1325}
1326
1327impl<C> PendingWorkOk<C>
1328where
1329    C: Cursor<KeyContainer: BatchContainer<Owned: PartialEq + Sized>>,
1330{
1331    fn new(capability: CapabilitySet<C::Time>, cursor: C, batch: C::Storage) -> Self {
1332        Self {
1333            capability,
1334            cursor,
1335            batch,
1336        }
1337    }
1338
1339    /// Perform roughly `fuel` work through the cursor, applying `logic` and sending results to
1340    /// the single output session.
1341    fn do_work<DCB, L>(
1342        &mut self,
1343        key: Option<&C::Key<'_>>,
1344        logic: &mut L,
1345        fuel: &mut usize,
1346        ok_output: &mut OutputBuilderSession<'_, C::Time, DCB>,
1347    ) where
1348        DCB: ContainerBuilder,
1349        L: FnMut(C::Key<'_>, C::Val<'_>, C::Time, C::Diff, &mut Session<C::Time, DCB>) -> usize,
1350    {
1351        let mut ok_session = ok_output.session_with_builder(&self.capability);
1352        walk_cursor(&mut self.cursor, &self.batch, key, fuel, |k, v, t, d| {
1353            logic(k, v, t, d, &mut ok_session)
1354        });
1355    }
1356}
1357
1358/// Walk a cursor, calling `emit` for each consolidated `(key, val, time, diff)` tuple. If
1359/// `key` is set, the cursor is seeked to it and only values for that key are produced.
1360///
1361/// `emit` returns the number of records it produced for the given input tuple. The cursor
1362/// stops as soon as the accumulated emit count reaches `*fuel`, leaving the cursor in place
1363/// so work can resume on a later call. Within a batch, both the inner val loop and the
1364/// outer key loop are bounded only by emit count, so selective filters (`emit` returns 0)
1365/// run to batch completion in a single activation — see [`ArrangementFlavor::flat_map`]
1366/// for why fuel counts output rather than input.
1367fn walk_cursor<C, F>(
1368    cursor: &mut C,
1369    batch: &C::Storage,
1370    key: Option<&C::Key<'_>>,
1371    fuel: &mut usize,
1372    mut emit: F,
1373) where
1374    C: Cursor<KeyContainer: BatchContainer<Owned: PartialEq + Sized>>,
1375    F: FnMut(C::Key<'_>, C::Val<'_>, C::Time, C::Diff) -> usize,
1376{
1377    use differential_dataflow::consolidation::consolidate;
1378
1379    let mut work: usize = 0;
1380    let mut buffer = Vec::new();
1381    if let Some(key) = key {
1382        let key = C::KeyContainer::reborrow(*key);
1383        if cursor.get_key(batch).map(|k| k == key) != Some(true) {
1384            cursor.seek_key(batch, key);
1385        }
1386        if cursor.get_key(batch).map(|k| k == key) == Some(true) {
1387            let key = cursor.key(batch);
1388            while let Some(val) = cursor.get_val(batch) {
1389                cursor.map_times(batch, |time, diff| {
1390                    buffer.push((C::owned_time(time), C::owned_diff(diff)));
1391                });
1392                consolidate(&mut buffer);
1393                for (time, diff) in buffer.drain(..) {
1394                    work += emit(key, val, time, diff);
1395                }
1396                cursor.step_val(batch);
1397                if work >= *fuel {
1398                    *fuel = 0;
1399                    return;
1400                }
1401            }
1402        }
1403    } else {
1404        while let Some(key) = cursor.get_key(batch) {
1405            while let Some(val) = cursor.get_val(batch) {
1406                cursor.map_times(batch, |time, diff| {
1407                    buffer.push((C::owned_time(time), C::owned_diff(diff)));
1408                });
1409                consolidate(&mut buffer);
1410                for (time, diff) in buffer.drain(..) {
1411                    work += emit(key, val, time, diff);
1412                }
1413                cursor.step_val(batch);
1414                if work >= *fuel {
1415                    *fuel = 0;
1416                    return;
1417                }
1418            }
1419            cursor.step_key(batch);
1420        }
1421    }
1422    *fuel -= work;
1423}
1424
1425#[cfg(test)]
1426mod tests {
1427    use differential_dataflow::input::Input;
1428    use mz_expr::{EvalError, MapFilterProject};
1429    use mz_repr::{Datum, ReprScalarType, Timestamp};
1430    use timely::dataflow::operators::Capture;
1431    use timely::dataflow::operators::capture::{Event, Extract};
1432
1433    use super::*;
1434    use crate::render::columnar::{columnar_to_vec, vec_to_columnar};
1435
1436    type OkUpdate = ((Row, Row), Timestamp, Diff);
1437    type ErrUpdate = (DataflowErrorSer, Timestamp, Diff);
1438    type Captured<D> = std::sync::mpsc::Receiver<Event<Timestamp, Vec<D>>>;
1439
1440    fn extract_ok(captured: Captured<OkUpdate>) -> Vec<OkUpdate> {
1441        let mut updates: Vec<_> = captured
1442            .extract()
1443            .into_iter()
1444            .flat_map(|(_, data)| data)
1445            .collect();
1446        updates.sort();
1447        updates
1448    }
1449
1450    // `DataflowErrorSer` is not `Ord`, so order by the error's debug string.
1451    fn extract_err(captured: Captured<ErrUpdate>) -> Vec<(String, Timestamp, Diff)> {
1452        let mut updates: Vec<_> = captured
1453            .extract()
1454            .into_iter()
1455            .flat_map(|(_, data)| data)
1456            .map(|(e, t, d)| (format!("{e:?}"), t, d))
1457            .collect();
1458        updates.sort();
1459        updates
1460    }
1461
1462    /// Arranges `rows`, returning the sorted ok and err output.
1463    fn arrange_columnar(
1464        rows: Vec<(Row, u64)>,
1465        key: Vec<LirScalarExpr>,
1466    ) -> (Vec<OkUpdate>, Vec<(String, Timestamp, Diff)>) {
1467        let thinning = vec![0, 1];
1468        let (ok, err) = timely::execute_directly(move |worker| {
1469            worker.dataflow::<Timestamp, _, _>(|scope| {
1470                let (mut input, collection) = scope.new_collection();
1471                let (arranged, errs, _passthrough) =
1472                    CollectionBundle::<Timestamp>::arrange_collection(
1473                        &"col".to_string(),
1474                        vec_to_columnar(collection),
1475                        key,
1476                        thinning,
1477                        ArrangementBatcher::Columnation,
1478                    );
1479                let ok = arranged
1480                    .as_collection(|k, v| (k.to_row(), v.to_row()))
1481                    .inner
1482                    .capture();
1483                let err = errs.inner.capture();
1484
1485                let max_time = rows.iter().map(|(_, t)| *t).max().unwrap_or(0);
1486                for (row, time) in rows {
1487                    input.update_at(row, Timestamp::from(time), Diff::ONE);
1488                }
1489                input.advance_to(Timestamp::from(max_time + 1));
1490                input.flush();
1491                (ok, err)
1492            })
1493        });
1494        (extract_ok(ok), extract_err(err))
1495    }
1496
1497    // Uniform two columns so `Column(0)` and full-row thinning are in bounds, over three
1498    // distinct times so per-record time handling is exercised.
1499    fn test_rows() -> Vec<(Row, u64)> {
1500        vec![
1501            (Row::pack_slice(&[Datum::Int32(1), Datum::String("a")]), 0),
1502            (Row::pack_slice(&[Datum::Int32(2), Datum::String("b")]), 1),
1503            (Row::pack_slice(&[Datum::Int32(1), Datum::String("a")]), 1),
1504            (Row::pack_slice(&[Datum::Int32(3), Datum::Null]), 2),
1505        ]
1506    }
1507
1508    /// Agreeing contents do not rule out a silent `columnar_to_vec` on the ok path. That the
1509    /// operator never decodes holds by inspection, not by this test.
1510    #[mz_ore::test]
1511    fn arrange_collection_keys_correctly() {
1512        let rows = test_rows();
1513        let mut expected: Vec<OkUpdate> = rows
1514            .iter()
1515            .map(|(row, t)| {
1516                let key = Row::pack_slice(&[row.iter().next().unwrap()]);
1517                ((key, row.clone()), Timestamp::from(*t), Diff::ONE)
1518            })
1519            .collect();
1520        expected.sort();
1521
1522        let (ok, err) = arrange_columnar(rows, vec![LirScalarExpr::column(0)]);
1523        assert_eq!(ok, expected);
1524        assert!(err.is_empty());
1525    }
1526
1527    /// A key expression that always errors drives every record onto the error path.
1528    #[mz_ore::test]
1529    fn arrange_collection_error_path() {
1530        let key = vec![LirScalarExpr::literal(
1531            Err(EvalError::DivisionByZero),
1532            ReprScalarType::Int32,
1533        )];
1534        let (ok, err) = arrange_columnar(test_rows(), key);
1535
1536        assert!(ok.is_empty());
1537        assert!(!err.is_empty());
1538    }
1539
1540    /// The passthrough forwards every input record, including those whose key
1541    /// evaluation errored, so a consumer of the bundle's collection sees the
1542    /// unarranged input rather than the ok side of the arrangement.
1543    #[mz_ore::test]
1544    fn arrange_collection_passthrough_forwards_input() {
1545        let rows = test_rows();
1546        let mut expected: Vec<(Row, Timestamp, Diff)> = rows
1547            .iter()
1548            .map(|(row, t)| (row.clone(), Timestamp::from(*t), Diff::ONE))
1549            .collect();
1550        expected.sort();
1551
1552        let key = vec![LirScalarExpr::literal(
1553            Err(EvalError::DivisionByZero),
1554            ReprScalarType::Int32,
1555        )];
1556        let captured = timely::execute_directly(move |worker| {
1557            worker.dataflow::<Timestamp, _, _>(|scope| {
1558                let (mut input, collection) = scope.new_collection();
1559                let (_arranged, _errs, passthrough) =
1560                    CollectionBundle::<Timestamp>::arrange_collection(
1561                        &"col".to_string(),
1562                        vec_to_columnar(collection),
1563                        key,
1564                        vec![0, 1],
1565                        ArrangementBatcher::Columnation,
1566                    );
1567                let captured = columnar_to_vec(passthrough).inner.capture();
1568
1569                let max_time = rows.iter().map(|(_, t)| *t).max().unwrap_or(0);
1570                for (row, time) in rows {
1571                    input.update_at(row, Timestamp::from(time), Diff::ONE);
1572                }
1573                input.advance_to(Timestamp::from(max_time + 1));
1574                input.flush();
1575                captured
1576            })
1577        });
1578
1579        assert_eq!(extract_row_updates(captured), expected);
1580    }
1581
1582    fn extract_row_updates(
1583        captured: Captured<(Row, Timestamp, Diff)>,
1584    ) -> Vec<(Row, Timestamp, Diff)> {
1585        let mut updates: Vec<_> = captured
1586            .extract()
1587            .into_iter()
1588            .flat_map(|(_, data)| data)
1589            .collect();
1590        updates.sort();
1591        updates
1592    }
1593
1594    /// Arrange correctness itself is covered by `arrange_collection_arms_agree`; this only
1595    /// asserts the columnar variant survives the hand-off.
1596    #[mz_ore::test]
1597    fn get_arrange_by_produces_projected_rows() {
1598        let rows = vec![
1599            (Row::pack_slice(&[Datum::Int64(1), Datum::Int64(10)]), 0u64),
1600            (Row::pack_slice(&[Datum::Int64(2), Datum::Int64(20)]), 1),
1601            (Row::pack_slice(&[Datum::Int64(1), Datum::Int64(10)]), 1),
1602        ];
1603        // A projection is non-identity, so `as_collection_core` takes the producer path
1604        // rather than the identity passthrough.
1605        let mfp = MapFilterProject::<LirScalarExpr>::new(2)
1606            .project(vec![0])
1607            .into_plan()
1608            .expect("mfp");
1609        let mut expected: Vec<(Row, Timestamp, Diff)> = rows
1610            .iter()
1611            .map(|(r, t)| {
1612                let col0 = r.iter().next().unwrap();
1613                (Row::pack_slice(&[col0]), Timestamp::from(*t), Diff::ONE)
1614            })
1615            .collect();
1616        expected.sort();
1617
1618        let produced = timely::execute_directly(move |worker| {
1619            worker.dataflow::<Timestamp, _, _>(|scope| {
1620                let (mut input, collection) = scope.new_collection();
1621                let (_err_input, errs) = scope.new_collection::<DataflowErrorSer, Diff>();
1622                let bundle = CollectionBundle::from_edge(vec_to_columnar(collection), errs);
1623                let (edge, _errs) = bundle.as_collection_core(mfp, None, Antichain::new());
1624                let produced = columnar_to_vec(edge.clone()).inner.capture();
1625                let (_arranged, _arrange_errs, _passthrough) =
1626                    CollectionBundle::<Timestamp>::arrange_collection(
1627                        &"arrange".to_string(),
1628                        edge,
1629                        vec![LirScalarExpr::column(0)],
1630                        vec![0],
1631                        ArrangementBatcher::Columnation,
1632                    );
1633
1634                let max_time = rows.iter().map(|(_, t)| *t).max().unwrap();
1635                for (row, time) in rows {
1636                    input.update_at(row, Timestamp::from(time), Diff::ONE);
1637                }
1638                input.advance_to(Timestamp::from(max_time + 1));
1639                input.flush();
1640                produced
1641            })
1642        });
1643
1644        assert_eq!(extract_row_updates(produced), expected);
1645    }
1646
1647    /// The identity fast-path returns the unarranged input edge unchanged, with no
1648    /// repack, so its contents pass straight through.
1649    #[mz_ore::test]
1650    fn as_collection_core_identity_passes_edge_through() {
1651        let expected = vec![(
1652            Row::pack_slice(&[Datum::Int64(1)]),
1653            Timestamp::from(0u64),
1654            Diff::ONE,
1655        )];
1656        let captured = timely::execute_directly(move |worker| {
1657            worker.dataflow::<Timestamp, _, _>(|scope| {
1658                let (mut input, collection) = scope.new_collection::<Row, Diff>();
1659                let (_err_input, errs) = scope.new_collection::<DataflowErrorSer, Diff>();
1660                let bundle = CollectionBundle::from_edge(vec_to_columnar(collection), errs);
1661                let identity = MapFilterProject::<LirScalarExpr>::new(1)
1662                    .into_plan()
1663                    .expect("identity mfp");
1664                let (out, _errs) = bundle.as_collection_core(identity, None, Antichain::new());
1665                let captured = columnar_to_vec(out).inner.capture();
1666                input.update_at(
1667                    Row::pack_slice(&[Datum::Int64(1)]),
1668                    Timestamp::from(0u64),
1669                    Diff::ONE,
1670                );
1671                input.advance_to(Timestamp::from(1u64));
1672                input.flush();
1673                captured
1674            })
1675        });
1676        assert_eq!(extract_row_updates(captured), expected);
1677    }
1678
1679    /// Input rows that project to the same output row at the same time collapse to one
1680    /// record with summed diff. A plain `ColumnBuilder` would emit both.
1681    #[mz_ore::test]
1682    fn as_collection_core_consolidates_within_batch() {
1683        // `[1, 10]` and `[1, 20]` both project (dropping column 1) to `[1]` at
1684        // t=0, so their `+1` diffs must fold to `+2`. `[2, 30]` projects to a
1685        // distinct record.
1686        let rows = vec![
1687            Row::pack_slice(&[Datum::Int64(1), Datum::Int64(10)]),
1688            Row::pack_slice(&[Datum::Int64(1), Datum::Int64(20)]),
1689            Row::pack_slice(&[Datum::Int64(2), Datum::Int64(30)]),
1690        ];
1691        let mfp = MapFilterProject::<LirScalarExpr>::new(2)
1692            .project(vec![0])
1693            .into_plan()
1694            .expect("mfp");
1695        let expected = vec![
1696            (
1697                Row::pack_slice(&[Datum::Int64(1)]),
1698                Timestamp::from(0u64),
1699                Diff::from(2),
1700            ),
1701            (
1702                Row::pack_slice(&[Datum::Int64(2)]),
1703                Timestamp::from(0u64),
1704                Diff::ONE,
1705            ),
1706        ];
1707
1708        let captured = timely::execute_directly(move |worker| {
1709            worker.dataflow::<Timestamp, _, _>(|scope| {
1710                let (mut input, collection) = scope.new_collection();
1711                let (_err_input, errs) = scope.new_collection::<DataflowErrorSer, Diff>();
1712                let bundle = CollectionBundle::from_edge(vec_to_columnar(collection), errs);
1713                let (edge, _errs) = bundle.as_collection_core(mfp, None, Antichain::new());
1714                let captured = columnar_to_vec(edge).inner.capture();
1715                // Feed all rows at the same time in one batch so the fold is
1716                // within-batch, not a downstream re-consolidation.
1717                for row in rows {
1718                    input.update_at(row, Timestamp::from(0u64), Diff::ONE);
1719                }
1720                input.advance_to(Timestamp::from(1u64));
1721                input.flush();
1722                captured
1723            })
1724        });
1725
1726        assert_eq!(extract_row_updates(captured), expected);
1727    }
1728
1729    /// Keying by column 0 and thinning the value to column 1 reconstructs the original
1730    /// two-column row. The decode below belongs to the capture harness.
1731    #[mz_ore::test]
1732    fn as_specific_collection_materializes_columnar() {
1733        let rows = test_rows();
1734        let key = vec![LirScalarExpr::column(0)];
1735        let mut expected: Vec<(Row, Timestamp, Diff)> = rows
1736            .iter()
1737            .map(|(r, t)| (r.clone(), Timestamp::from(*t), Diff::ONE))
1738            .collect();
1739        expected.sort();
1740
1741        let captured = timely::execute_directly(move |worker| {
1742            worker.dataflow::<Timestamp, _, _>(|scope| {
1743                let (mut input, collection) = scope.new_collection();
1744                let (arranged, arr_errs, _passthrough) =
1745                    CollectionBundle::<Timestamp>::arrange_collection(
1746                        &"agg".to_string(),
1747                        vec_to_columnar(collection),
1748                        key.clone(),
1749                        vec![1],
1750                        ArrangementBatcher::Columnation,
1751                    );
1752                let err_arranged = {
1753                    let kc: KeyCollection<_, _, _> = arr_errs.into();
1754                    kc.mz_arrange::<ErrBatcher<_, _>, ErrSpine<_, _>>("agg-errs")
1755                };
1756                // An arrangement-only bundle, as Reduce/Threshold/TopK produce.
1757                let bundle = CollectionBundle::from_columns(
1758                    0..1,
1759                    ArrangementFlavor::Local(arranged, err_arranged),
1760                );
1761                let (edge, _errs) = bundle.as_specific_collection(Some(&key));
1762                let captured = columnar_to_vec(edge).inner.capture();
1763
1764                let max_time = rows.iter().map(|(_, t)| *t).max().unwrap();
1765                for (row, time) in rows {
1766                    input.update_at(row, Timestamp::from(time), Diff::ONE);
1767                }
1768                input.advance_to(Timestamp::from(max_time + 1));
1769                input.flush();
1770                captured
1771            })
1772        });
1773
1774        assert_eq!(extract_row_updates(captured), expected);
1775    }
1776}