mz_compute/render/join/delta_join.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//! Delta join execution dataflow construction.
11//!
12//! Consult [DeltaJoinPlan] documentation for details.
13
14#![allow(clippy::op_ref)]
15
16use std::collections::{BTreeMap, BTreeSet};
17
18use std::rc::Rc;
19
20use differential_dataflow::consolidation::ConsolidatingContainerBuilder;
21use differential_dataflow::operators::arrange::Arranged;
22use differential_dataflow::trace::implementations::BatchContainer;
23use differential_dataflow::trace::{BatchReader, Cursor, TraceReader};
24use differential_dataflow::{AsCollection, VecCollection};
25use mz_compute_types::dyncfgs::ENABLE_HALF_JOIN2;
26use mz_compute_types::plan::join::JoinClosure;
27use mz_compute_types::plan::join::delta_join::{DeltaJoinPlan, DeltaPathPlan, DeltaStagePlan};
28use mz_compute_types::plan::scalar::LirScalarExpr;
29use mz_dyncfg::ConfigSet;
30use mz_expr::Eval;
31use mz_repr::fixed_length::ExtendDatums;
32use mz_repr::{DatumVec, Diff, Row, RowArena, SharedRow};
33use mz_timely_util::operator::{CollectionExt, StreamExt};
34use timely::container::CapacityContainerBuilder;
35use timely::dataflow::channels::pact::Pipeline;
36use timely::dataflow::operators::OkErr;
37use timely::dataflow::operators::generic::Session;
38use timely::dataflow::operators::vec::Map;
39use timely::progress::Antichain;
40
41use crate::render::RenderTimestamp;
42use crate::render::context::{ArrangementFlavor, CollectionBundle, Context};
43use crate::render::errors::DataflowErrorSer;
44use crate::typedefs::{RowRowAgent, RowRowEnter};
45
46impl<'scope, T: RenderTimestamp> Context<'scope, T> {
47 /// Renders `MirRelationExpr:Join` using dogs^3 delta query dataflows.
48 ///
49 /// The join is followed by the application of `map_filter_project`, whose
50 /// implementation will be pushed in to the join pipeline if at all possible.
51 pub fn render_delta_join(
52 &self,
53 inputs: Vec<CollectionBundle<'scope, T>>,
54 join_plan: DeltaJoinPlan,
55 ) -> CollectionBundle<'scope, T> {
56 // We create a new region to contain the dataflow paths for the delta join.
57 let (oks, errs) = self.scope.clone().region_named("Join(Delta)", |inner| {
58 // Collects error streams for the ambient scope.
59 let mut inner_errs = Vec::new();
60
61 // Deduplicate the error streams of multiply used arrangements.
62 let mut err_dedup = BTreeSet::new();
63
64 // Our plan is to iterate through each input relation, and attempt
65 // to find a plan that maximally uses existing keys (better: uses
66 // existing arrangements, to which we have access).
67 let mut join_results = Vec::new();
68
69 // First let's prepare the input arrangements we will need.
70 // This reduces redundant imports, and simplifies the dataflow structure.
71 // As the arrangements are all shared, it should not dramatically improve
72 // the efficiency, but the dataflow simplification is worth doing.
73 let mut arrangements = BTreeMap::new();
74 for path_plan in join_plan.path_plans.iter() {
75 for stage_plan in path_plan.stage_plans.iter() {
76 let lookup_idx = stage_plan.lookup_relation;
77 let lookup_key = stage_plan.lookup_key.clone();
78 arrangements
79 .entry((lookup_idx, lookup_key.clone()))
80 .or_insert_with(|| {
81 match inputs[lookup_idx]
82 .arrangement(&lookup_key)
83 .unwrap_or_else(|| {
84 panic!(
85 "Arrangement alarmingly absent!: {}, {:?}",
86 lookup_idx, lookup_key,
87 )
88 }) {
89 ArrangementFlavor::Local(oks, errs) => {
90 if err_dedup.insert((lookup_idx, lookup_key)) {
91 inner_errs.push(
92 errs.enter_region(inner)
93 .as_collection(|k, _v| k.clone()),
94 );
95 }
96 Ok(oks.enter_region(inner))
97 }
98 ArrangementFlavor::Trace(_gid, oks, errs) => {
99 if err_dedup.insert((lookup_idx, lookup_key)) {
100 inner_errs.push(
101 errs.enter_region(inner)
102 .as_collection(|k, _v| k.clone()),
103 );
104 }
105 Err(oks.enter_region(inner))
106 }
107 }
108 });
109 }
110 }
111
112 for path_plan in join_plan.path_plans {
113 // Deconstruct the stages of the path plan.
114 let DeltaPathPlan {
115 source_relation,
116 initial_closure,
117 stage_plans,
118 final_closure,
119 source_key,
120 } = path_plan;
121
122 // This collection determines changes that result from updates inbound
123 // from `inputs[relation]` and reflects all strictly prior updates and
124 // concurrent updates from relations prior to `relation`.
125 let name = format!("delta path {}", source_relation);
126 let path_results = inner.clone().region_named(&name, |region| {
127 // The plan is to move through each relation, starting from `relation` and in the order
128 // indicated in `orders[relation]`. At each moment, we will have the columns from the
129 // subset of relations encountered so far, and we will have applied as much as we can
130 // of the filters in `equivalences` and the logic in `map_filter_project`, based on the
131 // available columns.
132 //
133 // As we go, we will track the physical locations of each intended output column, as well
134 // as the locations of intermediate results from partial application of `map_filter_project`.
135 //
136 // Just before we apply the `lookup` function to perform a join, we will first use our
137 // available information to determine the filtering and logic that we can apply, and
138 // introduce that in to the `lookup` logic to cause it to happen in that operator.
139
140 // Collects error streams for the region scope. Concats before leaving.
141 let mut region_errs = Vec::with_capacity(inputs.len());
142
143 // Ensure this input is rendered, and extract its update stream.
144 let val = arrangements
145 .get(&(source_relation, source_key))
146 .expect("Arrangement promised by the planner is absent!");
147 let as_of = self.as_of_frontier.clone();
148 let update_stream = match val {
149 Ok(local) => {
150 let arranged = local.clone().enter_region(region);
151 let (update_stream, err_stream) =
152 build_update_stream::<_, RowRowAgent<_, _>>(
153 arranged,
154 as_of,
155 source_relation,
156 initial_closure,
157 );
158 region_errs.push(err_stream);
159 update_stream
160 }
161 Err(trace) => {
162 let arranged = trace.clone().enter_region(region);
163 let (update_stream, err_stream) =
164 build_update_stream::<_, RowRowEnter<_, _, _>>(
165 arranged,
166 as_of,
167 source_relation,
168 initial_closure,
169 );
170 region_errs.push(err_stream);
171 update_stream
172 }
173 };
174 // Promote `time` to a datum element.
175 //
176 // The `half_join` operator manipulates as "data" a pair `(data, time)`,
177 // while tracking the initial time `init_time` separately and without
178 // modification. The initial value for both times is the initial time.
179 let mut update_stream = update_stream
180 .inner
181 .map(|(v, t, d)| ((v, t.clone()), t, d))
182 .as_collection();
183
184 // Repeatedly update `update_stream` to reflect joins with more and more
185 // other relations, in the specified order.
186 for stage_plan in stage_plans {
187 let DeltaStagePlan {
188 lookup_relation,
189 stream_key,
190 stream_thinning,
191 lookup_key,
192 closure,
193 } = stage_plan;
194
195 // We require different logic based on the relative order of the two inputs.
196 // If the `source` relation precedes the `lookup` relation, we present all
197 // updates with less or equal `time`, and otherwise we present only updates
198 // with strictly less `time`.
199 //
200 // We need to write the logic twice, as there are two types of arrangement
201 // we might have: either dataflow-local or an imported trace.
202 let (oks, errs) =
203 match arrangements.get(&(lookup_relation, lookup_key)).unwrap() {
204 Ok(local) => {
205 if source_relation < lookup_relation {
206 build_halfjoin::<_, RowRowAgent<_, _>, _>(
207 update_stream,
208 local.clone().enter_region(region),
209 stream_key,
210 stream_thinning,
211 |t1, t2| t1.le(t2),
212 closure,
213 Rc::clone(&self.config_set),
214 )
215 } else {
216 build_halfjoin::<_, RowRowAgent<_, _>, _>(
217 update_stream,
218 local.clone().enter_region(region),
219 stream_key,
220 stream_thinning,
221 |t1, t2| t1.lt(t2),
222 closure,
223 Rc::clone(&self.config_set),
224 )
225 }
226 }
227 Err(trace) => {
228 if source_relation < lookup_relation {
229 build_halfjoin::<_, RowRowEnter<_, _, _>, _>(
230 update_stream,
231 trace.clone().enter_region(region),
232 stream_key,
233 stream_thinning,
234 |t1, t2| t1.le(t2),
235 closure,
236 Rc::clone(&self.config_set),
237 )
238 } else {
239 build_halfjoin::<_, RowRowEnter<_, _, _>, _>(
240 update_stream,
241 trace.clone().enter_region(region),
242 stream_key,
243 stream_thinning,
244 |t1, t2| t1.lt(t2),
245 closure,
246 Rc::clone(&self.config_set),
247 )
248 }
249 }
250 };
251 update_stream = oks;
252 region_errs.push(errs);
253 }
254
255 // Delay updates as appropriate.
256 //
257 // The `half_join` operator maintains a time that we now discard (the `_`),
258 // and replace with the `time` that is maintained with the data. The former
259 // exists to pin a consistent total order on updates throughout the process,
260 // while allowing `time` to vary upwards as a result of actions on time.
261 let mut update_stream = update_stream
262 .inner
263 .map(|((row, time), _, diff)| (row, time, diff))
264 .as_collection();
265
266 // We have completed the join building, but may have work remaining.
267 // For example, we may have expressions not pushed down (e.g. literals)
268 // and projections that could not be applied (e.g. column repetition).
269 if let Some(final_closure) = final_closure {
270 let name = "DeltaJoinFinalization";
271 type CB<C> = ConsolidatingContainerBuilder<C>;
272 let (updates, errors) = update_stream
273 .flat_map_fallible::<CB<_>, CB<_>, _, _, _, _>(name, {
274 // Reuseable allocation for unpacking.
275 let mut datums = DatumVec::new();
276 move |row| {
277 let mut row_builder = SharedRow::get();
278 let temp_storage = RowArena::new();
279 let mut datums_local = datums.borrow_with(&row);
280 // TODO(mcsherry): re-use `row` allocation.
281 final_closure
282 .apply(&mut datums_local, &temp_storage, &mut row_builder)
283 .map(|row| row.cloned())
284 .map_err(DataflowErrorSer::from)
285 .transpose()
286 }
287 });
288
289 update_stream = updates;
290 region_errs.push(errors);
291 }
292
293 inner_errs.push(
294 differential_dataflow::collection::concatenate(region, region_errs)
295 .leave_region(inner),
296 );
297 update_stream.leave_region(inner)
298 });
299
300 join_results.push(path_results);
301 }
302
303 // Concatenate the results of each delta query as the accumulated results.
304 (
305 differential_dataflow::collection::concatenate(inner, join_results)
306 .leave_region(self.scope),
307 differential_dataflow::collection::concatenate(inner, inner_errs)
308 .leave_region(self.scope),
309 )
310 });
311 CollectionBundle::from_collections(oks, errs)
312 }
313}
314
315/// Constructs a `half_join` from supplied arguments.
316///
317/// This method exists to factor common logic from four code paths that are generic over the type of trace.
318/// The `comparison` function should either be `le` or `lt` depending on which relation comes first in the
319/// total order on relations (in order to break ties consistently).
320///
321/// The input and output streams are of pairs `(data, time)` where the `time` component can be greater than
322/// the time of the update. This operator may manipulate `time` as part of this pair, but will not manipulate
323/// the time of the update. This is crucial for correctness, as the total order on times of updates is used
324/// to ensure that any two updates are matched at most once.
325fn build_halfjoin<'scope, T, Tr, CF>(
326 updates: VecCollection<'scope, T, (Row, T), Diff>,
327 trace: Arranged<'scope, Tr>,
328 prev_key: Vec<LirScalarExpr>,
329 prev_thinning: Vec<usize>,
330 comparison: CF,
331 closure: JoinClosure,
332 config_set: Rc<ConfigSet>,
333) -> (
334 VecCollection<'scope, T, (Row, T), Diff>,
335 VecCollection<'scope, T, DataflowErrorSer, Diff>,
336)
337where
338 T: RenderTimestamp,
339 Tr: TraceReader<KeyContainer: BatchContainer<Owned = Row>, Time = T, Diff = Diff>
340 + Clone
341 + 'static,
342 for<'a> Tr::Val<'a>: ExtendDatums,
343 CF: Fn(Tr::TimeGat<'_>, &T) -> bool + 'static,
344{
345 let use_half_join2 = ENABLE_HALF_JOIN2.get(&config_set);
346
347 let name = "DeltaJoinKeyPreparation";
348 type CB<C> = CapacityContainerBuilder<C>;
349 let (updates, errs) = updates.map_fallible::<CB<_>, CB<_>, _, _, _>(name, {
350 // Reuseable allocation for unpacking.
351 let mut datums = DatumVec::new();
352 move |(row, time)| {
353 let temp_storage = RowArena::new();
354 let datums_local = datums.borrow_with(&row);
355 let mut row_builder = SharedRow::get();
356 row_builder.packer().try_extend(
357 prev_key
358 .iter()
359 .map(|e| e.eval(&datums_local, &temp_storage)),
360 )?;
361 let key = row_builder.clone();
362 row_builder
363 .packer()
364 .extend(prev_thinning.iter().map(|&c| datums_local[c]));
365 let row_value = row_builder.clone();
366
367 Ok((key, row_value, time))
368 }
369 });
370 let datums = DatumVec::new();
371
372 if use_half_join2 {
373 build_halfjoin2(updates, trace, comparison, closure, datums, errs)
374 } else {
375 build_halfjoin1(updates, trace, comparison, closure, datums, errs)
376 }
377}
378
379/// `half_join2` implementation (less-quadratic, new default).
380fn build_halfjoin2<'scope, T, Tr, CF>(
381 updates: VecCollection<'scope, T, (Row, Row, T), Diff>,
382 trace: Arranged<'scope, Tr>,
383 comparison: CF,
384 closure: JoinClosure,
385 mut datums: DatumVec,
386 errs: VecCollection<'scope, T, DataflowErrorSer, Diff>,
387) -> (
388 VecCollection<'scope, T, (Row, T), Diff>,
389 VecCollection<'scope, T, DataflowErrorSer, Diff>,
390)
391where
392 T: RenderTimestamp,
393 Tr: TraceReader<KeyContainer: BatchContainer<Owned = Row>, Time = T, Diff = Diff>
394 + Clone
395 + 'static,
396 for<'a> Tr::Val<'a>: ExtendDatums,
397 CF: Fn(Tr::TimeGat<'_>, &T) -> bool + 'static,
398{
399 type CB<C> = CapacityContainerBuilder<C>;
400
401 if closure.could_error() {
402 let (oks, errs2) = differential_dogs3::operators::half_join2::half_join_internal_unsafe(
403 updates,
404 trace,
405 |time, antichain| {
406 antichain.insert(time.step_back());
407 },
408 comparison,
409 // TODO(mcsherry): investigate/establish trade-offs here; time based had problems,
410 // in that we seem to yield too much and do too little work when we do.
411 |_timer, count| count > 1_000_000,
412 // TODO(mcsherry): consider `RefOrMut` in `half_join` interface to allow re-use.
413 move |session: &mut CB<Vec<_>>, key, stream_row, lookup_row, initial, diff1, output| {
414 let mut row_builder = SharedRow::get();
415 let temp_storage = RowArena::new();
416
417 let mut datums_local = datums.borrow();
418 datums_local.extend(key.iter());
419 datums_local.extend(stream_row.iter());
420 lookup_row.extend_datums(&temp_storage, &mut datums_local, None);
421
422 let row = closure.apply(&mut datums_local, &temp_storage, &mut row_builder);
423
424 for (time, diff2) in output.drain(..) {
425 let row = row.as_ref().map(|row| row.cloned()).map_err(Clone::clone);
426 let diff = diff1.clone() * diff2.clone();
427 let data = ((row, time.clone()), initial.clone(), diff);
428 use timely::container::PushInto;
429 session.push_into(data);
430 }
431 },
432 )
433 .ok_err(|(data_time, init_time, diff)| {
434 // TODO(mcsherry): consider `ok_err()` for `Collection`.
435 match data_time {
436 (Ok(data), time) => Ok((data.map(|data| (data, time)), init_time, diff)),
437 (Err(err), _time) => Err((DataflowErrorSer::from(err), init_time, diff)),
438 }
439 });
440
441 (
442 oks.as_collection().flat_map(|x| x),
443 errs.concat(errs2.as_collection()),
444 )
445 } else {
446 let oks = differential_dogs3::operators::half_join2::half_join_internal_unsafe(
447 updates,
448 trace,
449 |time, antichain| {
450 antichain.insert(time.step_back());
451 },
452 comparison,
453 // TODO(mcsherry): investigate/establish trade-offs here; time based had problems,
454 // in that we seem to yield too much and do too little work when we do.
455 |_timer, count| count > 1_000_000,
456 // TODO(mcsherry): consider `RefOrMut` in `half_join` interface to allow re-use.
457 move |session: &mut CB<Vec<_>>, key, stream_row, lookup_row, initial, diff1, output| {
458 if output.is_empty() {
459 return;
460 }
461
462 let mut row_builder = SharedRow::get();
463 let temp_storage = RowArena::new();
464
465 let mut datums_local = datums.borrow();
466 datums_local.extend(key.iter());
467 datums_local.extend(stream_row.iter());
468 lookup_row.extend_datums(&temp_storage, &mut datums_local, None);
469
470 if let Some(row) = closure
471 .apply(&mut datums_local, &temp_storage, &mut row_builder)
472 .expect("Closure claimed to never error")
473 {
474 for (time, diff2) in output.drain(..) {
475 let diff = diff1.clone() * diff2.clone();
476 use timely::container::PushInto;
477 session.push_into(((row.clone(), time.clone()), initial.clone(), diff));
478 }
479 }
480 },
481 );
482
483 (oks.as_collection(), errs)
484 }
485}
486
487/// Original `half_join` implementation (fallback).
488fn build_halfjoin1<'scope, T, Tr, CF>(
489 updates: VecCollection<'scope, T, (Row, Row, T), Diff>,
490 trace: Arranged<'scope, Tr>,
491 comparison: CF,
492 closure: JoinClosure,
493 mut datums: DatumVec,
494 errs: VecCollection<'scope, T, DataflowErrorSer, Diff>,
495) -> (
496 VecCollection<'scope, T, (Row, T), Diff>,
497 VecCollection<'scope, T, DataflowErrorSer, Diff>,
498)
499where
500 T: RenderTimestamp,
501 Tr: TraceReader<KeyContainer: BatchContainer<Owned = Row>, Time = T, Diff = Diff>
502 + Clone
503 + 'static,
504 for<'a> Tr::Val<'a>: ExtendDatums,
505 CF: Fn(Tr::TimeGat<'_>, &T) -> bool + 'static,
506{
507 type CB<C> = CapacityContainerBuilder<C>;
508
509 if closure.could_error() {
510 let (oks, errs2) = differential_dogs3::operators::half_join::half_join_internal_unsafe(
511 updates,
512 trace,
513 |time, antichain| {
514 antichain.insert(time.step_back());
515 },
516 comparison,
517 |_timer, count| count > 1_000_000,
518 move |session: &mut Session<'_, '_, T, CB<Vec<_>>, _>,
519 key,
520 stream_row: &Row,
521 lookup_row,
522 initial,
523 diff1,
524 output| {
525 let mut row_builder = SharedRow::get();
526 let temp_storage = RowArena::new();
527
528 let mut datums_local = datums.borrow();
529 datums_local.extend(key.iter());
530 datums_local.extend(stream_row.iter());
531 lookup_row.extend_datums(&temp_storage, &mut datums_local, None);
532
533 let row = closure.apply(&mut datums_local, &temp_storage, &mut row_builder);
534
535 for (time, diff2) in output.drain(..) {
536 let row = row.as_ref().map(|row| row.cloned()).map_err(Clone::clone);
537 let diff = diff1.clone() * diff2.clone();
538 let data = ((row, time.clone()), initial.clone(), diff);
539 session.give(data);
540 }
541 },
542 )
543 .ok_err(|(data_time, init_time, diff)| match data_time {
544 (Ok(data), time) => Ok((data.map(|data| (data, time)), init_time, diff)),
545 (Err(err), _time) => Err((DataflowErrorSer::from(err), init_time, diff)),
546 });
547
548 (
549 oks.as_collection().flat_map(|x| x),
550 errs.concat(errs2.as_collection()),
551 )
552 } else {
553 let oks = differential_dogs3::operators::half_join::half_join_internal_unsafe(
554 updates,
555 trace,
556 |time, antichain| {
557 antichain.insert(time.step_back());
558 },
559 comparison,
560 |_timer, count| count > 1_000_000,
561 move |session: &mut Session<'_, '_, T, CB<Vec<_>>, _>,
562 key,
563 stream_row: &Row,
564 lookup_row,
565 initial,
566 diff1,
567 output| {
568 if output.is_empty() {
569 return;
570 }
571
572 let mut row_builder = SharedRow::get();
573 let temp_storage = RowArena::new();
574
575 let mut datums_local = datums.borrow();
576 datums_local.extend(key.iter());
577 datums_local.extend(stream_row.iter());
578 lookup_row.extend_datums(&temp_storage, &mut datums_local, None);
579
580 if let Some(row) = closure
581 .apply(&mut datums_local, &temp_storage, &mut row_builder)
582 .expect("Closure claimed to never error")
583 {
584 for (time, diff2) in output.drain(..) {
585 let diff = diff1.clone() * diff2.clone();
586 session.give(((row.clone(), time.clone()), initial.clone(), diff));
587 }
588 }
589 },
590 );
591
592 (oks.as_collection(), errs)
593 }
594}
595
596/// Builds the beginning of the update stream of a delta path.
597///
598/// At start-up time only the delta path for the first relation sees updates, since any updates fed to the
599/// other delta paths would be discarded anyway due to the tie-breaking logic that avoids double-counting
600/// updates happening at the same time on different relations.
601fn build_update_stream<'scope, T, Tr>(
602 trace: Arranged<'scope, Tr>,
603 as_of: Antichain<mz_repr::Timestamp>,
604 source_relation: usize,
605 initial_closure: JoinClosure,
606) -> (
607 VecCollection<'scope, T, Row, Diff>,
608 VecCollection<'scope, T, DataflowErrorSer, Diff>,
609)
610where
611 T: RenderTimestamp,
612 for<'a, 'b> &'a T: PartialEq<Tr::TimeGat<'b>>,
613 Tr: for<'a> TraceReader<Time = T, Diff = Diff> + Clone + 'static,
614 for<'a> Tr::Key<'a>: ExtendDatums,
615 for<'a> Tr::Val<'a>: ExtendDatums,
616{
617 let mut inner_as_of = Antichain::new();
618 for event_time in as_of.elements().iter() {
619 inner_as_of.insert(<T>::to_inner(event_time.clone()));
620 }
621
622 let (ok_stream, err_stream) =
623 trace
624 .stream
625 .unary_fallible(Pipeline, "UpdateStream", move |_, _| {
626 let mut datums = DatumVec::new();
627 Box::new(move |input, ok_output, err_output| {
628 // Buffer to accumulate contributing (time, diff) pairs for each (key, val).
629 let mut times_diffs = Vec::default();
630 input.for_each(|time, data| {
631 let mut row_builder = SharedRow::get();
632 let mut ok_session = ok_output.session(&time);
633 let mut err_session = err_output.session(&time);
634
635 for wrapper in data.iter() {
636 let batch = &wrapper;
637 let mut cursor = batch.cursor();
638 while let Some(key) = cursor.get_key(batch) {
639 while let Some(val) = cursor.get_val(batch) {
640 // Collect contributing (time, diff) pairs before invoking the closure.
641 cursor.map_times(batch, |time, diff| {
642 if source_relation == 0
643 || inner_as_of.elements().iter().all(|e| e != time)
644 {
645 // TODO: Consolidate as we push, defensively.
646 times_diffs
647 .push((Tr::owned_time(time), Tr::owned_diff(diff)));
648 }
649 });
650 differential_dataflow::consolidation::consolidate(
651 &mut times_diffs,
652 );
653 // The can not-uncommonly be empty, if the inbound updates cancel.
654 if !times_diffs.is_empty() {
655 let temp_storage = RowArena::new();
656
657 let mut datums_local = datums.borrow();
658 key.extend_datums(&temp_storage, &mut datums_local, None);
659 val.extend_datums(&temp_storage, &mut datums_local, None);
660
661 if !initial_closure.is_identity() {
662 match initial_closure
663 .apply(
664 &mut datums_local,
665 &temp_storage,
666 &mut row_builder,
667 )
668 .map(|row| row.cloned())
669 .transpose()
670 {
671 Some(Ok(row)) => {
672 for (time, diff) in times_diffs.drain(..) {
673 ok_session.give((row.clone(), time, diff))
674 }
675 }
676 Some(Err(err)) => {
677 for (time, diff) in times_diffs.drain(..) {
678 err_session.give((err.clone(), time, diff))
679 }
680 }
681 None => {}
682 }
683 } else {
684 let row = {
685 row_builder.packer().extend(&*datums_local);
686 row_builder.clone()
687 };
688 for (time, diff) in times_diffs.drain(..) {
689 ok_session.give((row.clone(), time, diff));
690 }
691 }
692 }
693 times_diffs.clear();
694
695 cursor.step_val(batch);
696 }
697 cursor.step_key(batch);
698 }
699 }
700 });
701 })
702 });
703
704 (
705 ok_stream.as_collection(),
706 err_stream.as_collection().map(DataflowErrorSer::from),
707 )
708}