1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

//! Management of dataflow-local state, like arrangements, while building a
//! dataflow.

use std::collections::BTreeMap;
use std::rc::Weak;
use std::sync::mpsc;

use differential_dataflow::consolidation::ConsolidatingContainerBuilder;
use differential_dataflow::lattice::Lattice;
use differential_dataflow::operators::arrange::Arranged;
use differential_dataflow::trace::cursor::IntoOwned;
use differential_dataflow::trace::{BatchReader, Cursor, TraceReader};
use differential_dataflow::{Collection, Data};
use mz_compute_types::dataflows::DataflowDescription;
use mz_compute_types::plan::{AvailableCollections, LirId};
use mz_expr::{Id, MapFilterProject, MirScalarExpr};
use mz_repr::fixed_length::{FromDatumIter, ToDatumIter};
use mz_repr::{DatumVec, DatumVecBorrow, Diff, GlobalId, Row, RowArena, SharedRow};
use mz_storage_types::controller::CollectionMetadata;
use mz_storage_types::errors::DataflowError;
use mz_timely_util::operator::{CollectionExt, StreamExt};
use timely::container::columnation::Columnation;
use timely::container::CapacityContainerBuilder;
use timely::dataflow::channels::pact::Pipeline;
use timely::dataflow::operators::generic::OutputHandleCore;
use timely::dataflow::operators::Capability;
use timely::dataflow::scopes::Child;
use timely::dataflow::{Scope, ScopeParent};
use timely::progress::timestamp::Refines;
use timely::progress::{Antichain, Timestamp};
use tracing::error;

use crate::arrangement::manager::SpecializedTraceHandle;
use crate::compute_state::{ComputeState, HydrationEvent};
use crate::extensions::arrange::{KeyCollection, MzArrange};
use crate::render::errors::ErrorLogger;
use crate::render::{LinearJoinSpec, RenderTimestamp};
use crate::typedefs::{ErrAgent, ErrEnter, ErrSpine, RowRowAgent, RowRowEnter, RowRowSpine};

/// Dataflow-local collections and arrangements.
///
/// A context means to wrap available data assets and present them in an easy-to-use manner.
/// These assets include dataflow-local collections and arrangements, as well as imported
/// arrangements from outside the dataflow.
///
/// Context has two timestamp types, one from `S::Timestamp` and one from `T`, where the
/// former must refine the latter. The former is the timestamp used by the scope in question,
/// and the latter is the timestamp of imported traces. The two may be different in the case
/// of regions or iteration.
pub struct Context<S: Scope, T = mz_repr::Timestamp>
where
    T: Timestamp + Lattice + Columnation,
    S::Timestamp: Lattice + Refines<T> + Columnation,
{
    /// The scope within which all managed collections exist.
    ///
    /// It is an error to add any collections not contained in this scope.
    pub(crate) scope: S,
    /// The debug name of the dataflow associated with this context.
    pub debug_name: String,
    /// The Timely ID of the dataflow associated with this context.
    pub dataflow_id: usize,
    /// Frontier before which updates should not be emitted.
    ///
    /// We *must* apply it to sinks, to ensure correct outputs.
    /// We *should* apply it to sources and imported traces, because it improves performance.
    pub as_of_frontier: Antichain<T>,
    /// Frontier after which updates should not be emitted.
    /// Used to limit the amount of work done when appropriate.
    pub until: Antichain<T>,
    /// Bindings of identifiers to collections.
    pub bindings: BTreeMap<Id, CollectionBundle<S, T>>,
    /// A token that operators can probe to know whether the dataflow is shutting down.
    pub(super) shutdown_token: ShutdownToken,
    /// A logger that operators can use to report hydration events.
    ///
    /// `None` if no hydration events should be logged in this context.
    pub(super) hydration_logger: Option<HydrationLogger>,
    /// The logger, from Timely's logging framework, if logs are enabled.
    pub(super) compute_logger: Option<crate::logging::compute::Logger>,
    /// Specification for rendering linear joins.
    pub(super) linear_join_spec: LinearJoinSpec,
    /// The expiration time for dataflows in this context. The output's frontier should never advance
    /// past this frontier, except the empty frontier.
    pub dataflow_expiration: Antichain<T>,
}

impl<S: Scope> Context<S>
where
    S::Timestamp: Lattice + Refines<mz_repr::Timestamp> + Columnation,
{
    /// Creates a new empty Context.
    pub fn for_dataflow_in<Plan>(
        dataflow: &DataflowDescription<Plan, CollectionMetadata>,
        scope: S,
        compute_state: &ComputeState,
        until: Antichain<mz_repr::Timestamp>,
        dataflow_expiration: Antichain<mz_repr::Timestamp>,
    ) -> Self {
        use mz_ore::collections::CollectionExt as IteratorExt;
        let dataflow_id = *scope.addr().into_first();
        let as_of_frontier = dataflow
            .as_of
            .clone()
            .unwrap_or_else(|| Antichain::from_elem(Timestamp::minimum()));

        // Skip operator hydration logging for transient dataflows. We do this to avoid overhead
        // for slow-path peeks, but it also affects subscribes. For now that seems fine, but we may
        // want to reconsider in the future.
        //
        // Similarly, we won't capture a compute_logger for logging LIR->address mappings for transient dataflows.
        let (hydration_logger, compute_logger) = if dataflow.is_transient() {
            (None, None)
        } else {
            (
                Some(HydrationLogger {
                    export_ids: dataflow.export_ids().collect(),
                    tx: compute_state.hydration_tx.clone(),
                }),
                compute_state.compute_logger.clone(),
            )
        };

        Self {
            scope,
            debug_name: dataflow.debug_name.clone(),
            dataflow_id,
            as_of_frontier,
            until,
            bindings: BTreeMap::new(),
            shutdown_token: Default::default(),
            hydration_logger,
            compute_logger,
            linear_join_spec: compute_state.linear_join_spec,
            dataflow_expiration,
        }
    }
}

impl<S: Scope, T> Context<S, T>
where
    T: Timestamp + Lattice + Columnation,
    S::Timestamp: Lattice + Refines<T> + Columnation,
{
    /// Insert a collection bundle by an identifier.
    ///
    /// This is expected to be used to install external collections (sources, indexes, other views),
    /// as well as for `Let` bindings of local collections.
    pub fn insert_id(
        &mut self,
        id: Id,
        collection: CollectionBundle<S, T>,
    ) -> Option<CollectionBundle<S, T>> {
        self.bindings.insert(id, collection)
    }
    /// Remove a collection bundle by an identifier.
    ///
    /// The primary use of this method is uninstalling `Let` bindings.
    pub fn remove_id(&mut self, id: Id) -> Option<CollectionBundle<S, T>> {
        self.bindings.remove(&id)
    }
    /// Melds a collection bundle to whatever exists.
    pub fn update_id(&mut self, id: Id, collection: CollectionBundle<S, T>) {
        if !self.bindings.contains_key(&id) {
            self.bindings.insert(id, collection);
        } else {
            let binding = self
                .bindings
                .get_mut(&id)
                .expect("Binding verified to exist");
            if collection.collection.is_some() {
                binding.collection = collection.collection;
            }
            for (key, flavor) in collection.arranged.into_iter() {
                binding.arranged.insert(key, flavor);
            }
        }
    }
    /// Look up a collection bundle by an identifier.
    pub fn lookup_id(&self, id: Id) -> Option<CollectionBundle<S, T>> {
        self.bindings.get(&id).cloned()
    }

    pub(super) fn error_logger(&self) -> ErrorLogger {
        ErrorLogger::new(self.shutdown_token.clone(), self.debug_name.clone())
    }
}

impl<S: Scope, T> Context<S, T>
where
    T: Timestamp + Lattice + Columnation,
    S::Timestamp: Lattice + Refines<T> + Columnation,
{
    /// Brings the underlying arrangements and collections into a region.
    pub fn enter_region<'a>(
        &self,
        region: &Child<'a, S, S::Timestamp>,
        bindings: Option<&std::collections::BTreeSet<Id>>,
    ) -> Context<Child<'a, S, S::Timestamp>, T> {
        let bindings = self
            .bindings
            .iter()
            .filter(|(key, _)| bindings.as_ref().map(|b| b.contains(key)).unwrap_or(true))
            .map(|(key, bundle)| (*key, bundle.enter_region(region)))
            .collect();

        Context {
            scope: region.clone(),
            debug_name: self.debug_name.clone(),
            dataflow_id: self.dataflow_id.clone(),
            as_of_frontier: self.as_of_frontier.clone(),
            until: self.until.clone(),
            shutdown_token: self.shutdown_token.clone(),
            hydration_logger: self.hydration_logger.clone(),
            compute_logger: self.compute_logger.clone(),
            linear_join_spec: self.linear_join_spec.clone(),
            bindings,
            dataflow_expiration: self.dataflow_expiration.clone(),
        }
    }
}

/// Convenient wrapper around an optional `Weak` instance that can be used to check whether a
/// datalow is shutting down.
///
/// Instances created through the `Default` impl act as if the dataflow never shuts down.
/// Instances created through [`ShutdownToken::new`] defer to the wrapped token.
#[derive(Clone, Default)]
pub(super) struct ShutdownToken(Option<Weak<()>>);

impl ShutdownToken {
    /// Construct a `ShutdownToken` instance that defers to `token`.
    pub(super) fn new(token: Weak<()>) -> Self {
        Self(Some(token))
    }

    /// Probe the token for dataflow shutdown.
    ///
    /// This method is meant to be used with the `?` operator: It returns `None` if the dataflow is
    /// in the process of shutting down and `Some` otherwise.
    pub(super) fn probe(&self) -> Option<()> {
        match &self.0 {
            Some(t) => t.upgrade().map(|_| ()),
            None => Some(()),
        }
    }

    /// Returns whether the dataflow is in the process of shutting down.
    pub(super) fn in_shutdown(&self) -> bool {
        self.probe().is_none()
    }

    /// Returns a reference to the wrapped `Weak`.
    pub(crate) fn get_inner(&self) -> Option<&Weak<()>> {
        self.0.as_ref()
    }
}

/// A logger for operator hydration events emitted for a dataflow export.
#[derive(Clone)]
pub(super) struct HydrationLogger {
    export_ids: Vec<GlobalId>,
    tx: mpsc::Sender<HydrationEvent>,
}

impl HydrationLogger {
    /// Log a hydration event for the identified LIR node.
    ///
    /// The expectation is that rendering code arranges for `hydrated = false` to be logged for
    /// each LIR node when a dataflow is first created. Then `hydrated = true` should be logged as
    /// operators become hydrated.
    pub fn log(&self, lir_id: LirId, hydrated: bool) {
        for &export_id in &self.export_ids {
            let event = HydrationEvent {
                export_id,
                lir_id,
                hydrated,
            };
            if self.tx.send(event).is_err() {
                error!("hydration event receiver dropped unexpectely");
            }
        }
    }
}

/// An abstraction of an arrangement.
///
/// This type exists as an `enum` to support potential experimentation with alternate
/// representation and layouts.
#[derive(Clone)]
pub enum MzArrangement<S: Scope>
where
    <S as ScopeParent>::Timestamp: Lattice + Columnation,
{
    RowRow(Arranged<S, RowRowAgent<<S as ScopeParent>::Timestamp, Diff>>),
}

impl<S: Scope> MzArrangement<S>
where
    <S as ScopeParent>::Timestamp: Lattice + Columnation,
{
    /// The scope of the underlying arrangement's stream.
    pub fn scope(&self) -> S {
        match self {
            MzArrangement::RowRow(inner) => inner.stream.scope(),
        }
    }

    /// Panic if the frontier of the underlying arrangement's stream exceeds `expiration` time.
    pub fn expire_arrangement_at(&mut self, name: &str, expiration: S::Timestamp, token: Weak<()>) {
        match self {
            MzArrangement::RowRow(inner) => {
                inner.stream = inner.stream.expire_stream_at(name, expiration, token);
            }
        }
    }

    /// Brings the underlying arrangement into a region.
    pub fn enter_region<'a>(
        &self,
        region: &Child<'a, S, S::Timestamp>,
    ) -> MzArrangement<Child<'a, S, S::Timestamp>> {
        match self {
            MzArrangement::RowRow(inner) => MzArrangement::RowRow(inner.enter_region(region)),
        }
    }

    /// Extracts the underlying arrangement as a stream of updates.
    pub fn as_collection<L>(&self, mut logic: L) -> Collection<S, Row, Diff>
    where
        L: for<'a, 'b> FnMut(&'a DatumVecBorrow<'b>) -> Row + 'static,
    {
        let mut datums = DatumVec::new();
        match self {
            MzArrangement::RowRow(inner) => inner.as_collection(move |k, v| {
                let mut datums_borrow = datums.borrow();
                datums_borrow.extend(k.to_datum_iter());
                datums_borrow.extend(v.to_datum_iter());
                logic(&datums_borrow)
            }),
        }
    }

    /// Applies logic to elements of the underlying arrangement and returns the results.
    pub fn flat_map<D, I, L, T>(
        &self,
        key: Option<Row>,
        mut logic: L,
        refuel: usize,
    ) -> timely::dataflow::Stream<S, I::Item>
    where
        T: Timestamp + Lattice + Columnation,
        <S as ScopeParent>::Timestamp: Lattice + Refines<T>,
        I: IntoIterator<Item = (D, S::Timestamp, Diff)>,
        D: Data,
        L: for<'a, 'b> FnMut(&'a mut DatumVecBorrow<'b>, &'a S::Timestamp, &'a Diff) -> I + 'static,
    {
        use differential_dataflow::operators::arrange::TraceAgent;
        let mut datums = DatumVec::new();
        match self {
            MzArrangement::RowRow(inner) => {
                CollectionBundle::<S, T>::flat_map_core::<TraceAgent<RowRowSpine<_, _>>, Row, _, _, _>(
                    inner,
                    key,
                    move |k, v, t, d| {
                        let mut datums_borrow = datums.borrow();
                        datums_borrow.extend(k.to_datum_iter());
                        datums_borrow.extend(v.to_datum_iter());
                        logic(&mut datums_borrow, t, d)
                    },
                    refuel,
                )
            }
        }
    }
}

impl<'a, S: Scope> MzArrangement<Child<'a, S, S::Timestamp>>
where
    <S as ScopeParent>::Timestamp: Lattice + Columnation,
{
    /// Extracts the underlying arrangement flavor from a region.
    pub fn leave_region(&self) -> MzArrangement<S> {
        match self {
            MzArrangement::RowRow(inner) => MzArrangement::RowRow(inner.leave_region()),
        }
    }
}

impl<S: Scope> MzArrangement<S>
where
    S: ScopeParent<Timestamp = mz_repr::Timestamp>,
{
    /// Obtains a `SpecializedTraceHandle` for the underlying arrangement.
    pub fn trace_handle(&self) -> SpecializedTraceHandle {
        match self {
            MzArrangement::RowRow(inner) => inner.trace.clone().into(),
        }
    }
}

/// An abstraction of an imported arrangement.
///
/// This type exists as an `enum` to support potential experimentation with alternate
/// representation and layouts.
#[derive(Clone)]
pub enum MzArrangementImport<S: Scope, T = mz_repr::Timestamp>
where
    T: Timestamp + Lattice + Columnation,
    <S as ScopeParent>::Timestamp: Lattice + Refines<T>,
{
    RowRow(Arranged<S, RowRowEnter<T, Diff, <S as ScopeParent>::Timestamp>>),
}

impl<S: Scope, T> MzArrangementImport<S, T>
where
    T: Timestamp + Lattice + Columnation,
    <S as ScopeParent>::Timestamp: Lattice + Refines<T> + Columnation,
{
    /// The scope of the underlying trace's stream.
    pub fn scope(&self) -> S {
        match self {
            MzArrangementImport::RowRow(inner) => inner.stream.scope(),
        }
    }

    /// Brings the underlying trace into a region.
    pub fn enter_region<'a>(
        &self,
        region: &Child<'a, S, S::Timestamp>,
    ) -> MzArrangementImport<Child<'a, S, S::Timestamp>, T> {
        match self {
            MzArrangementImport::RowRow(inner) => {
                MzArrangementImport::RowRow(inner.enter_region(region))
            }
        }
    }

    /// Extracts the underlying trace as a stream of updates.
    pub fn as_collection<L>(&self, mut logic: L) -> Collection<S, Row, Diff>
    where
        L: for<'a, 'b> FnMut(&'a DatumVecBorrow<'b>) -> Row + 'static,
    {
        let mut datums = DatumVec::new();
        match self {
            MzArrangementImport::RowRow(inner) => inner.as_collection(move |k, v| {
                let mut datums_borrow = datums.borrow();
                datums_borrow.extend(k.to_datum_iter());
                datums_borrow.extend(v.to_datum_iter());
                logic(&datums_borrow)
            }),
        }
    }

    /// Applies logic to elements of the underlying arrangement and returns the results.
    pub fn flat_map<D, I, L>(
        &self,
        key: Option<Row>,
        mut logic: L,
        refuel: usize,
    ) -> timely::dataflow::Stream<S, I::Item>
    where
        I: IntoIterator<Item = (D, S::Timestamp, Diff)>,
        D: Data,
        L: for<'a, 'b> FnMut(&'a mut DatumVecBorrow<'b>, &'a S::Timestamp, &'a Diff) -> I + 'static,
    {
        let mut datums = DatumVec::new();
        match self {
            MzArrangementImport::RowRow(inner) => CollectionBundle::<S, T>::flat_map_core::<
                RowRowEnter<T, Diff, S::Timestamp>,
                Row,
                _,
                _,
                _,
            >(
                inner,
                key,
                move |k, v, t, d| {
                    let mut datums_borrow = datums.borrow();
                    datums_borrow.extend(k.to_datum_iter());
                    datums_borrow.extend(v.to_datum_iter());
                    logic(&mut datums_borrow, t, d)
                },
                refuel,
            ),
        }
    }
}

impl<'a, S: Scope, T> MzArrangementImport<Child<'a, S, S::Timestamp>, T>
where
    T: Timestamp + Lattice + Columnation,
    <S as ScopeParent>::Timestamp: Lattice + Refines<T>,
{
    /// Extracts the underlying arrangement flavor from a region.
    pub fn leave_region(&self) -> MzArrangementImport<S, T> {
        match self {
            MzArrangementImport::RowRow(inner) => MzArrangementImport::RowRow(inner.leave_region()),
        }
    }
}

/// Describes flavor of arrangement: local or imported trace.
#[derive(Clone)]
pub enum ArrangementFlavor<S: Scope, T = mz_repr::Timestamp>
where
    T: Timestamp + Lattice + Columnation,
    S::Timestamp: Lattice + Refines<T> + Columnation,
{
    /// A dataflow-local arrangement.
    Local(
        MzArrangement<S>,
        Arranged<S, ErrAgent<<S as ScopeParent>::Timestamp, Diff>>,
    ),
    /// An imported trace from outside the dataflow.
    ///
    /// The `GlobalId` identifier exists so that exports of this same trace
    /// can refer back to and depend on the original instance.
    Trace(
        GlobalId,
        MzArrangementImport<S, T>,
        Arranged<S, ErrEnter<T, <S as ScopeParent>::Timestamp>>,
    ),
}

impl<S: Scope, T> ArrangementFlavor<S, T>
where
    T: Timestamp + Lattice + Columnation,
    S::Timestamp: Lattice + Refines<T> + Columnation,
{
    /// Presents `self` as a stream of updates.
    ///
    /// This method presents the contents as they are, without further computation.
    /// If you have logic that could be applied to each record, consider using the
    /// `flat_map` methods which allows this and can reduce the work done.
    pub fn as_collection(&self) -> (Collection<S, Row, Diff>, Collection<S, DataflowError, Diff>) {
        match &self {
            ArrangementFlavor::Local(oks, errs) => (
                oks.as_collection(move |borrow| SharedRow::pack(&**borrow)),
                errs.as_collection(|k, &()| k.clone()),
            ),
            ArrangementFlavor::Trace(_, oks, errs) => (
                oks.as_collection(move |borrow| SharedRow::pack(&**borrow)),
                errs.as_collection(|k, &()| k.clone()),
            ),
        }
    }

    /// Constructs and applies logic to elements of `self` and returns the results.
    ///
    /// `constructor` takes a permutation and produces the logic to apply on elements. The logic
    /// conceptually receives `(&Row, &Row)` pairs in the form of a slice. Only after borrowing
    /// the elements and applying the permutation the datums will be in the expected order.
    ///
    /// If `key` is set, this is a promise that `logic` will produce no results on
    /// records for which the key does not evaluate to the value. This is used to
    /// leap directly to exactly those records.
    pub fn flat_map<D, I, C, L>(
        &self,
        key: Option<Row>,
        constructor: C,
    ) -> (
        timely::dataflow::Stream<S, I::Item>,
        Collection<S, DataflowError, Diff>,
    )
    where
        I: IntoIterator<Item = (D, S::Timestamp, Diff)>,
        D: Data,
        C: FnOnce() -> L,
        L: for<'a, 'b> FnMut(&'a mut DatumVecBorrow<'b>, &'a S::Timestamp, &'a Diff) -> I + 'static,
    {
        // Set a number of tuples after which the operator should yield.
        // This allows us to remain responsive even when enumerating a substantial
        // arrangement, as well as provides time to accumulate our produced output.
        let refuel = 1000000;

        match &self {
            ArrangementFlavor::Local(oks, errs) => {
                let logic = constructor();
                let oks = oks.flat_map(key, logic, refuel);
                let errs = errs.as_collection(|k, &()| k.clone());
                (oks, errs)
            }
            ArrangementFlavor::Trace(_, oks, errs) => {
                let logic = constructor();
                let oks = oks.flat_map(key, logic, refuel);
                let errs = errs.as_collection(|k, &()| k.clone());
                (oks, errs)
            }
        }
    }
}
impl<S: Scope, T> ArrangementFlavor<S, T>
where
    T: Timestamp + Lattice + Columnation,
    S::Timestamp: Lattice + Refines<T> + Columnation,
{
    /// The scope containing the collection bundle.
    pub fn scope(&self) -> S {
        match self {
            ArrangementFlavor::Local(oks, _errs) => oks.scope(),
            ArrangementFlavor::Trace(_gid, oks, _errs) => oks.scope(),
        }
    }

    /// Brings the arrangement flavor into a region.
    pub fn enter_region<'a>(
        &self,
        region: &Child<'a, S, S::Timestamp>,
    ) -> ArrangementFlavor<Child<'a, S, S::Timestamp>, T> {
        match self {
            ArrangementFlavor::Local(oks, errs) => {
                ArrangementFlavor::Local(oks.enter_region(region), errs.enter_region(region))
            }
            ArrangementFlavor::Trace(gid, oks, errs) => {
                ArrangementFlavor::Trace(*gid, oks.enter_region(region), errs.enter_region(region))
            }
        }
    }
}
impl<'a, S: Scope, T> ArrangementFlavor<Child<'a, S, S::Timestamp>, T>
where
    T: Timestamp + Lattice + Columnation,
    S::Timestamp: Lattice + Refines<T> + Columnation,
{
    /// Extracts the arrangement flavor from a region.
    pub fn leave_region(&self) -> ArrangementFlavor<S, T> {
        match self {
            ArrangementFlavor::Local(oks, errs) => {
                ArrangementFlavor::Local(oks.leave_region(), errs.leave_region())
            }
            ArrangementFlavor::Trace(gid, oks, errs) => {
                ArrangementFlavor::Trace(*gid, oks.leave_region(), errs.leave_region())
            }
        }
    }
}

/// A bundle of the various ways a collection can be represented.
///
/// This type maintains the invariant that it does contain at least one valid
/// source of data, either a collection or at least one arrangement.
#[derive(Clone)]
pub struct CollectionBundle<S: Scope, T = mz_repr::Timestamp>
where
    T: Timestamp + Lattice + Columnation,
    S::Timestamp: Lattice + Refines<T> + Columnation,
{
    pub collection: Option<(Collection<S, Row, Diff>, Collection<S, DataflowError, Diff>)>,
    pub arranged: BTreeMap<Vec<MirScalarExpr>, ArrangementFlavor<S, T>>,
}

impl<S: Scope, T: Lattice> CollectionBundle<S, T>
where
    T: Timestamp + Lattice + Columnation,
    S::Timestamp: Lattice + Refines<T> + Columnation,
{
    /// Construct a new collection bundle from update streams.
    pub fn from_collections(
        oks: Collection<S, Row, Diff>,
        errs: Collection<S, DataflowError, Diff>,
    ) -> Self {
        Self {
            collection: Some((oks, errs)),
            arranged: BTreeMap::default(),
        }
    }

    /// Inserts arrangements by the expressions on which they are keyed.
    pub fn from_expressions(
        exprs: Vec<MirScalarExpr>,
        arrangements: ArrangementFlavor<S, T>,
    ) -> Self {
        let mut arranged = BTreeMap::new();
        arranged.insert(exprs, arrangements);
        Self {
            collection: None,
            arranged,
        }
    }

    /// Inserts arrangements by the columns on which they are keyed.
    pub fn from_columns<I: IntoIterator<Item = usize>>(
        columns: I,
        arrangements: ArrangementFlavor<S, T>,
    ) -> Self {
        let mut keys = Vec::new();
        for column in columns {
            keys.push(MirScalarExpr::Column(column));
        }
        Self::from_expressions(keys, arrangements)
    }

    /// The scope containing the collection bundle.
    pub fn scope(&self) -> S {
        if let Some((oks, _errs)) = &self.collection {
            oks.inner.scope()
        } else {
            self.arranged
                .values()
                .next()
                .expect("Must contain a valid collection")
                .scope()
        }
    }

    /// Brings the collection bundle into a region.
    pub fn enter_region<'a>(
        &self,
        region: &Child<'a, S, S::Timestamp>,
    ) -> CollectionBundle<Child<'a, S, S::Timestamp>, T> {
        CollectionBundle {
            collection: self
                .collection
                .as_ref()
                .map(|(oks, errs)| (oks.enter_region(region), errs.enter_region(region))),
            arranged: self
                .arranged
                .iter()
                .map(|(key, bundle)| (key.clone(), bundle.enter_region(region)))
                .collect(),
        }
    }
}

impl<'a, S: Scope, T> CollectionBundle<Child<'a, S, S::Timestamp>, T>
where
    T: Timestamp + Lattice + Columnation,
    S::Timestamp: Lattice + Refines<T> + Columnation,
{
    /// Extracts the collection bundle from a region.
    pub fn leave_region(&self) -> CollectionBundle<S, T> {
        CollectionBundle {
            collection: self
                .collection
                .as_ref()
                .map(|(oks, errs)| (oks.leave_region(), errs.leave_region())),
            arranged: self
                .arranged
                .iter()
                .map(|(key, bundle)| (key.clone(), bundle.leave_region()))
                .collect(),
        }
    }
}

impl<S: Scope, T> CollectionBundle<S, T>
where
    T: Timestamp + Lattice + Columnation,
    S::Timestamp: Lattice + Refines<T> + Columnation,
{
    /// Asserts that the arrangement for a specific key
    /// (or the raw collection for no key) exists,
    /// and returns the corresponding collection.
    ///
    /// This returns the collection as-is, without
    /// doing any unthinning transformation.
    /// Therefore, it should be used when the appropriate transformation
    /// was planned as part of a following MFP.
    pub fn as_specific_collection(
        &self,
        key: Option<&[MirScalarExpr]>,
    ) -> (Collection<S, Row, Diff>, Collection<S, DataflowError, Diff>) {
        // Any operator that uses this method was told to use a particular
        // collection during LIR planning, where we should have made
        // sure that that collection exists.
        //
        // If it doesn't, we panic.
        match key {
            None => self
                .collection
                .clone()
                .expect("The unarranged collection doesn't exist."),
            Some(key) => self
                .arranged
                .get(key)
                .unwrap_or_else(|| panic!("The collection arranged by {:?} doesn't exist.", key))
                .as_collection(),
        }
    }

    /// Constructs and applies logic to elements of a collection and returns the results.
    ///
    /// `constructor` takes a permutation and produces the logic to apply on elements. The logic
    /// conceptually receives `(&Row, &Row)` pairs in the form of a slice. Only after borrowing
    /// the elements and applying the permutation the datums will be in the expected order.
    ///
    /// If `key_val` is set, this is a promise that `logic` will produce no results on
    /// records for which the key does not evaluate to the value. This is used when we
    /// have an arrangement by that key to leap directly to exactly those records.
    /// It is important that `logic` still guard against data that does not satisfy
    /// this constraint, as this method does not statically know that it will have
    /// that arrangement.
    pub fn flat_map<D, I, C, L>(
        &self,
        key_val: Option<(Vec<MirScalarExpr>, Option<Row>)>,
        constructor: C,
    ) -> (
        timely::dataflow::Stream<S, I::Item>,
        Collection<S, DataflowError, Diff>,
    )
    where
        I: IntoIterator<Item = (D, S::Timestamp, Diff)>,
        D: Data,
        C: FnOnce() -> L,
        L: for<'a, 'b> FnMut(&'a mut DatumVecBorrow<'b>, &'a S::Timestamp, &'a Diff) -> I + 'static,
    {
        // If `key_val` is set, we should have use the corresponding arrangement.
        // If there isn't one, that implies an error in the contract between
        // key-production and available arrangements.
        if let Some((key, val)) = key_val {
            let flavor = self
                .arrangement(&key)
                .expect("Should have ensured during planning that this arrangement exists.");
            flavor.flat_map(val, constructor)
        } else {
            use timely::dataflow::operators::Map;
            let (oks, errs) = self
                .collection
                .clone()
                .expect("Invariant violated: CollectionBundle contains no collection.");
            let mut logic = constructor();
            let mut datums = DatumVec::new();
            (
                oks.inner
                    .flat_map(move |(v, t, d)| logic(&mut datums.borrow_with(&v), &t, &d)),
                errs,
            )
        }
    }

    /// Factored out common logic for using literal keys in general traces.
    ///
    /// This logic is sufficiently interesting that we want to write it only
    /// once, and thereby avoid any skew in the two uses of the logic.
    ///
    /// The function presents the contents of the trace as `(key, value, time, delta)` tuples,
    /// where key and value are potentially specialized, but convertible into rows.
    fn flat_map_core<Tr, K, D, I, L>(
        trace: &Arranged<S, Tr>,
        key: Option<K>,
        mut logic: L,
        refuel: usize,
    ) -> timely::dataflow::Stream<S, I::Item>
    where
        for<'a> Tr::Key<'a>: ToDatumIter + IntoOwned<'a, Owned = K>,
        for<'a> Tr::Val<'a>: ToDatumIter,
        Tr: TraceReader<Time = S::Timestamp, Diff = mz_repr::Diff> + Clone + 'static,
        K: PartialEq + 'static,
        I: IntoIterator<Item = (D, Tr::Time, Tr::Diff)>,
        D: Data,
        L: for<'a, 'b> FnMut(Tr::Key<'_>, Tr::Val<'_>, &'a S::Timestamp, &'a mz_repr::Diff) -> I
            + 'static,
    {
        use differential_dataflow::consolidation::ConsolidatingContainerBuilder as CB;

        let mode = if key.is_some() { "index" } else { "scan" };
        let name = format!("ArrangementFlatMap({})", mode);
        use timely::dataflow::operators::Operator;
        trace
            .stream
            .unary::<CB<_>, _, _, _>(Pipeline, &name, move |_, info| {
                // Acquire an activator to reschedule the operator when it has unfinished work.
                let activator = trace.stream.scope().activator_for(info.address);
                // Maintain a list of work to do, cursor to navigate and process.
                let mut todo = std::collections::VecDeque::new();
                move |input, output| {
                    // First, dequeue all batches.
                    input.for_each(|time, data| {
                        let capability = time.retain();
                        for batch in data.iter() {
                            // enqueue a capability, cursor, and batch.
                            todo.push_back(PendingWork::new(
                                capability.clone(),
                                batch.cursor(),
                                batch.clone(),
                            ));
                        }
                    });

                    // Second, make progress on `todo`.
                    let mut fuel = refuel;
                    while !todo.is_empty() && fuel > 0 {
                        todo.front_mut()
                            .unwrap()
                            .do_work(&key, &mut logic, &mut fuel, output);
                        if fuel > 0 {
                            todo.pop_front();
                        }
                    }
                    // If we have not finished all work, re-activate the operator.
                    if !todo.is_empty() {
                        activator.activate();
                    }
                }
            })
    }

    /// Look up an arrangement by the expressions that form the key.
    ///
    /// The result may be `None` if no such arrangement exists, or it may be one of many
    /// "arrangement flavors" that represent the types of arranged data we might have.
    pub fn arrangement(&self, key: &[MirScalarExpr]) -> Option<ArrangementFlavor<S, T>> {
        self.arranged.get(key).map(|x| x.clone())
    }
}

impl<S, T> CollectionBundle<S, T>
where
    T: timely::progress::Timestamp + Lattice + Columnation,
    S: Scope,
    S::Timestamp:
        Refines<T> + Lattice + timely::progress::Timestamp + crate::render::RenderTimestamp,
{
    /// Presents `self` as a stream of updates, having been subjected to `mfp`.
    ///
    /// This operator is able to apply the logic of `mfp` early, which can substantially
    /// reduce the amount of data produced when `mfp` is non-trivial.
    ///
    /// The `key_val` argument, when present, indicates that a specific arrangement should
    /// be used, and if, in addition, the `val` component is present,
    /// that we can seek to the supplied row.
    pub fn as_collection_core(
        &self,
        mut mfp: MapFilterProject,
        key_val: Option<(Vec<MirScalarExpr>, Option<Row>)>,
        until: Antichain<mz_repr::Timestamp>,
    ) -> (
        Collection<S, mz_repr::Row, Diff>,
        Collection<S, DataflowError, Diff>,
    ) {
        mfp.optimize();
        let mfp_plan = mfp.into_plan().unwrap();

        // If the MFP is trivial, we can just call `as_collection`.
        // In the case that we weren't going to apply the `key_val` optimization,
        // this path results in a slightly smaller and faster
        // dataflow graph, and is intended to fix
        // https://github.com/MaterializeInc/database-issues/issues/3111
        let has_key_val = if let Some((_key, Some(_val))) = &key_val {
            true
        } else {
            false
        };

        if mfp_plan.is_identity() && !has_key_val {
            let key = key_val.map(|(k, _v)| k);
            return self.as_specific_collection(key.as_deref());
        }
        let (stream, errors) = self.flat_map(key_val, || {
            let mut datum_vec = DatumVec::new();
            // Wrap in an `Rc` so that lifetimes work out.
            let until = std::rc::Rc::new(until);
            move |row_datums, time, diff| {
                let binding = SharedRow::get();
                let mut row_builder = binding.borrow_mut();
                let until = std::rc::Rc::clone(&until);
                let temp_storage = RowArena::new();
                let row_iter = row_datums.iter();
                let mut datums_local = datum_vec.borrow();
                datums_local.extend(row_iter);
                let time = time.clone();
                let event_time = time.event_time();
                mfp_plan
                    .evaluate(
                        &mut datums_local,
                        &temp_storage,
                        event_time,
                        diff.clone(),
                        move |time| !until.less_equal(time),
                        &mut row_builder,
                    )
                    .map(move |x| match x {
                        Ok((row, event_time, diff)) => {
                            // Copy the whole time, and re-populate event time.
                            let mut time: S::Timestamp = time.clone();
                            *time.event_time_mut() = event_time;
                            (Ok(row), time, diff)
                        }
                        Err((e, event_time, diff)) => {
                            // Copy the whole time, and re-populate event time.
                            let mut time: S::Timestamp = time.clone();
                            *time.event_time_mut() = event_time;
                            (Err(e), time, diff)
                        }
                    })
            }
        });

        use differential_dataflow::AsCollection;
        let (oks, errs) = stream
            .as_collection()
            .map_fallible::<CapacityContainerBuilder<_>, CapacityContainerBuilder<_>, _, _, _>(
                "OkErr",
                |x| x,
            );

        (oks, errors.concat(&errs))
    }
    pub fn ensure_collections(
        mut self,
        collections: AvailableCollections,
        input_key: Option<Vec<MirScalarExpr>>,
        input_mfp: MapFilterProject,
        until: Antichain<mz_repr::Timestamp>,
    ) -> Self {
        if collections == Default::default() {
            return self;
        }
        // Cache collection to avoid reforming it each time.
        //
        // TODO(mcsherry): In theory this could be faster run out of another arrangement,
        // as the `map_fallible` that follows could be run against an arrangement itself.
        //
        // Note(btv): If we ever do that, we would then only need to make the raw collection here
        // if `collections.raw` is true.

        // We need the collection if either (1) it is explicitly demanded, or (2) we are going to render any arrangement
        let form_raw_collection = collections.raw
            || collections
                .arranged
                .iter()
                .any(|(key, _, _)| !self.arranged.contains_key(key));
        if form_raw_collection && self.collection.is_none() {
            self.collection =
                Some(self.as_collection_core(input_mfp, input_key.map(|k| (k, None)), until));
        }
        for (key, _, thinning) in collections.arranged {
            if !self.arranged.contains_key(&key) {
                // TODO: Consider allowing more expressive names.
                let name = format!("ArrangeBy[{:?}]", key);

                let (oks, errs) = self
                    .collection
                    .clone()
                    .expect("Collection constructed above");
                let (oks, errs_keyed) = Self::specialized_arrange(&name, oks, &key, &thinning);
                let errs: KeyCollection<_, _, _> = errs.concat(&errs_keyed).into();
                let errs = errs.mz_arrange::<ErrSpine<_, _>>(&format!("{}-errors", name));
                self.arranged
                    .insert(key, ArrangementFlavor::Local(oks, errs));
            }
        }
        self
    }

    /// Builds a specialized arrangement to provided types. The specialization for key and
    /// value types of the arrangement is based on the bit length derived from the corresponding
    /// type descriptions.
    fn specialized_arrange(
        name: &String,
        oks: Collection<S, Row, i64>,
        key: &Vec<MirScalarExpr>,
        thinning: &Vec<usize>,
    ) -> (MzArrangement<S>, Collection<S, DataflowError, i64>) {
        // Catch-all: Just use RowRow.
        let (oks, errs) = oks
            .map_fallible::<CapacityContainerBuilder<_>, CapacityContainerBuilder<_>, _, _, _>(
                "FormArrangementKey",
                specialized_arrangement_key(key.clone(), thinning.clone()),
            );
        let oks = oks.mz_arrange::<RowRowSpine<_, _>>(name);
        (MzArrangement::RowRow(oks), errs)
    }
}

/// Obtains a function that maps input rows to (key, value) pairs according to
/// the given key and thinning expressions. This function allows for specialization
/// of key and value types and is intended to use to form arrangement keys.
fn specialized_arrangement_key<K, V>(
    key: Vec<MirScalarExpr>,
    thinning: Vec<usize>,
) -> impl FnMut(Row) -> Result<(K, V), DataflowError>
where
    K: Columnation + Data + FromDatumIter,
    V: Columnation + Data + FromDatumIter,
{
    let mut key_buf = K::default();
    let mut val_buf = V::default();
    let mut datums = DatumVec::new();
    move |row| {
        // TODO: Consider reusing the `row` allocation; probably in *next* invocation.
        let datums = datums.borrow_with(&row);
        let temp_storage = RowArena::new();
        let val_datum_iter = thinning.iter().map(|c| datums[*c]);
        Ok::<(K, V), DataflowError>((
            key_buf.try_from_datum_iter(key.iter().map(|k| k.eval(&datums, &temp_storage)))?,
            val_buf.from_datum_iter(val_datum_iter),
        ))
    }
}

struct PendingWork<C>
where
    C: Cursor,
    C::Time: Timestamp,
{
    capability: Capability<C::Time>,
    cursor: C,
    batch: C::Storage,
}

impl<C> PendingWork<C>
where
    C: Cursor,
    C::Time: Timestamp,
{
    /// Create a new bundle of pending work, from the capability, cursor, and backing storage.
    fn new(capability: Capability<C::Time>, cursor: C, batch: C::Storage) -> Self {
        Self {
            capability,
            cursor,
            batch,
        }
    }
    /// Perform roughly `fuel` work through the cursor, applying `logic` and sending results to `output`.
    fn do_work<I, D, L, K>(
        &mut self,
        key: &Option<K>,
        logic: &mut L,
        fuel: &mut usize,
        output: &mut OutputHandleCore<
            '_,
            C::Time,
            ConsolidatingContainerBuilder<Vec<I::Item>>,
            timely::dataflow::channels::pushers::Tee<C::Time, Vec<I::Item>>,
        >,
    ) where
        I: IntoIterator<Item = (D, C::Time, C::Diff)>,
        D: Data,
        L: for<'a, 'b> FnMut(C::Key<'_>, C::Val<'b>, &'a C::Time, &'a C::Diff) -> I + 'static,
        K: PartialEq + Sized,
        for<'a> C::Key<'a>: IntoOwned<'a, Owned = K>,
    {
        use differential_dataflow::consolidation::consolidate;

        // Attempt to make progress on this batch.
        let mut work: usize = 0;
        let mut session = output.session_with_builder(&self.capability);
        let mut buffer = Vec::new();
        if let Some(key) = key {
            if self
                .cursor
                .get_key(&self.batch)
                .map(|k| k == IntoOwned::borrow_as(key))
                != Some(true)
            {
                self.cursor.seek_key(&self.batch, IntoOwned::borrow_as(key));
            }
            if self
                .cursor
                .get_key(&self.batch)
                .map(|k| k == IntoOwned::borrow_as(key))
                == Some(true)
            {
                let key = self.cursor.key(&self.batch);
                while let Some(val) = self.cursor.get_val(&self.batch) {
                    self.cursor.map_times(&self.batch, |time, diff| {
                        buffer.push((time.into_owned(), diff.into_owned()));
                    });
                    consolidate(&mut buffer);
                    for (time, diff) in buffer.drain(..) {
                        for datum in logic(key, val, &time, &diff) {
                            session.give(datum);
                            work += 1;
                        }
                    }
                    self.cursor.step_val(&self.batch);
                    if work >= *fuel {
                        *fuel = 0;
                        return;
                    }
                }
            }
        } else {
            while let Some(key) = self.cursor.get_key(&self.batch) {
                while let Some(val) = self.cursor.get_val(&self.batch) {
                    self.cursor.map_times(&self.batch, |time, diff| {
                        buffer.push((time.into_owned(), diff.into_owned()));
                    });
                    consolidate(&mut buffer);
                    for (time, diff) in buffer.drain(..) {
                        for datum in logic(key, val, &time, &diff) {
                            session.give(datum);
                            work += 1;
                        }
                    }
                    self.cursor.step_val(&self.batch);
                    if work >= *fuel {
                        *fuel = 0;
                        return;
                    }
                }
                self.cursor.step_key(&self.batch);
            }
        }
        *fuel -= work;
    }
}