differential_dataflow/operators/join.rs
1//! Match pairs of records based on a key.
2//!
3//! The various `join` implementations require that the units of each collection can be multiplied, and that
4//! the multiplication distributes over addition. That is, we will repeatedly evaluate (a + b) * c as (a * c)
5//! + (b * c), and if this is not equal to the former term, little is known about the actual output.
6use std::cmp::Ordering;
7use std::collections::VecDeque;
8
9use timely::{Container, ContainerBuilder};
10use timely::container::NoopBuilder;
11use timely::order::PartialOrder;
12use timely::progress::Timestamp;
13use timely::dataflow::Stream;
14use timely::dataflow::operators::generic::{Operator, OutputBuilderSession};
15use timely::dataflow::channels::pact::Pipeline;
16use timely::dataflow::operators::Capability;
17
18use crate::lattice::Lattice;
19use crate::operators::arrange::Arranged;
20use crate::trace::{BatchCursor, BatchDiff, BatchReader, BatchVal, Cursor, Navigable, TraceReader};
21use crate::trace::cursor::cursor_list;
22use crate::trace::implementations::containers::BatchContainer;
23use crate::operators::ValueHistory;
24
25/// A type that can manage the joining of lists of batches.
26///
27/// The trait is parameterized by the output container `C`, not by the builder that assembles it: a tactic
28/// yields finished containers, and how it produces them (pushing records into a [`ContainerBuilder`], or
29/// otherwise) is its own concern.
30pub trait JoinTactic<B0: BatchReader, B1: BatchReader<Time = B0::Time>, C> {
31 /// Prepare the join of two lists of batches into an iterator of output containers.
32 ///
33 /// The supplied `fresh` and `meet` indicate respectively which input is "novel", and should drive the
34 /// join, as well as a lower bound on that input's times, so that the other input can be loaded compacted.
35 fn prep(&mut self, input0: Vec<B0>, input1: Vec<B1>, fresh: Fresh, meet: B0::Time) -> Box<dyn Iterator<Item = C>>;
36}
37
38/// Which input contributed the freshly-arrived batch of a deferred join unit.
39///
40/// The fresh batch's times all lie at or beyond the capability, so its side is not advanced by the
41/// capability's meet; the opposing accumulated trace is. The marker also selects which queue a unit
42/// joins, so a burst on one input cannot starve the other.
43pub enum Fresh {
44 /// The first input (`B0`) contributed the fresh batch.
45 Input0,
46 /// The second input (`B1`) contributed the fresh batch.
47 Input1,
48}
49
50/// An equijoin of two traces, sharing a common key type.
51///
52/// This method exists to provide join functionality without opinions on the specific input types, keys and values,
53/// that should be presented. The two traces here can have arbitrary key and value types, which can be unsized and
54/// even potentially unrelated to the input collection data. Importantly, the key and value types could be generic
55/// associated types (GATs) of the traces, and we would seemingly struggle to frame these types as trait arguments.
56///
57/// The implementation produces a caller-specified container. Implementations can use [`AsCollection`] to wrap the
58/// output stream in a collection.
59///
60/// The "correctness" of this method depends heavily on the behavior of the supplied `result` function.
61///
62/// [`AsCollection`]: crate::collection::AsCollection
63pub fn join_traces<'scope, Tr1, Tr2, KC, L, CB>(arranged1: Arranged<'scope, Tr1>, arranged2: Arranged<'scope, Tr2>, result: L) -> Stream<'scope, Tr1::Time, CB::Container>
64where
65 Tr1: TraceReader<Batch: Navigable>+'static,
66 Tr2: TraceReader<Batch: Navigable, Time = Tr1::Time>+'static,
67 KC: BatchContainer,
68 BatchCursor<Tr1>: Cursor<Time = Tr1::Time, KeyContainer = KC>,
69 for<'a> BatchCursor<Tr1>: Cursor<Key<'a> = KC::ReadItem<'a>>,
70 for<'a> BatchCursor<Tr2>: Cursor<Key<'a> = KC::ReadItem<'a>, Time = Tr1::Time>,
71 L: FnMut(KC::ReadItem<'_>,BatchVal<'_, Tr1>,BatchVal<'_, Tr2>,Tr1::Time,&BatchDiff<Tr1>,&BatchDiff<Tr2>,&mut CB)+'static,
72 CB: ContainerBuilder<Container: Default> + 'static,
73{
74 join_with_tactic(arranged1, arranged2, cursors::CursorTactic::<Tr1::Batch, Tr2::Batch, _, CB>::new(result))
75}
76
77/// Drives an equijoin of two traces using a supplied [`JoinTactic`].
78///
79/// This is the general join operator: it does the dataflow plumbing (frontiers, capabilities, trace
80/// compaction) and routes the per-batch work through the tactic. It requires only `TraceReader` of its
81/// inputs, never `Navigable`: it extracts trace batches via `batches_through`, and building cursors over
82/// them (if that is how the join proceeds) is the tactic's concern.
83pub fn join_with_tactic<'scope, Tr1, Tr2, T, C>(arranged1: Arranged<'scope, Tr1>, arranged2: Arranged<'scope, Tr2>, mut tactic: T) -> Stream<'scope, Tr1::Time, C>
84where
85 Tr1: TraceReader+'static,
86 Tr2: TraceReader<Time = Tr1::Time>+'static,
87 T: JoinTactic<Tr1::Batch, Tr2::Batch, C>+'static,
88 C: Container + 'static,
89{
90 // Rename traces for symmetry from here on out.
91 let mut trace1 = arranged1.trace;
92 let mut trace2 = arranged2.trace;
93
94 let scope = arranged1.stream.scope();
95 arranged1.stream.binary_frontier(arranged2.stream, Pipeline, Pipeline, "Join", move |capability, info| {
96
97 // Acquire an activator to reschedule the operator when it has unfinished work.
98 use timely::scheduling::Activator;
99 let activations = scope.activations();
100 let activator = Activator::new(info.address, activations);
101
102 // Our initial invariants are that for each trace, physical compaction is less or equal the trace's upper bound.
103 // These invariants ensure that we can reference observed batch frontiers from `_start_upper` onward, as long as
104 // we maintain our physical compaction capabilities appropriately. These assertions are tested as we load up the
105 // initial work for the two traces, and before the operator is constructed.
106
107 // Acknowledged frontier for each input.
108 // These two are used exclusively to track batch boundaries on which we may want/need to call `cursor_through`.
109 // They will drive our physical compaction of each trace, and we want to maintain at all times that each is beyond
110 // the physical compaction frontier of their corresponding trace.
111 // Should we ever *drop* a trace, these are 1. much harder to maintain correctly, but 2. no longer used.
112 use timely::progress::frontier::Antichain;
113 let mut acknowledged1 = Antichain::from_elem(Tr1::Time::minimum());
114 let mut acknowledged2 = Antichain::from_elem(Tr1::Time::minimum());
115
116 // Deferred work, as `(capability, iterator)` pairs bucketed by which input carried the fresh
117 // batch (so a burst on one input cannot starve the other). The driver owns the capabilities and
118 // the fuel budget; each iterator, prepared by the tactic, yields the output containers to ship
119 // under its paired capability, and is dropped once it goes dry.
120 let mut todo0: VecDeque<(Capability<Tr1::Time>, Box<dyn Iterator<Item = C>>)> = VecDeque::new();
121 let mut todo1: VecDeque<(Capability<Tr1::Time>, Box<dyn Iterator<Item = C>>)> = VecDeque::new();
122
123 // We'll unload the initial batches here, to put ourselves in a less non-deterministic state to start.
124 trace1.map_batches(|batch1| {
125 acknowledged1.clone_from(batch1.upper());
126 // No `todo1` work here, because we haven't accepted anything into `batches2` yet.
127 // It is effectively "empty", because we choose to drain `trace1` before `trace2`.
128 // Once we start streaming batches in, we will need to respond to new batches from
129 // `input1` with logic that would have otherwise been here. Check out the next loop
130 // for the structure.
131 });
132 // At this point, `ack1` should exactly equal `trace1.read_upper()`, as they are both determined by
133 // iterating through batches and capturing the upper bound. This is a great moment to assert that
134 // `trace1`'s physical compaction frontier is before the frontier of completed times in `trace1`.
135 // TODO: in the case that this does not hold, instead "upgrade" the physical compaction frontier.
136 assert!(PartialOrder::less_equal(&trace1.get_physical_compaction(), &acknowledged1.borrow()));
137
138 // We capture batch2's batches first and establish work second to avoid taking a `RefCell` lock
139 // on both traces at the same time, as they could be the same trace and this would panic.
140 let mut batch2_list = Vec::new();
141 trace2.map_batches(|batch2| {
142 acknowledged2.clone_from(batch2.upper());
143 batch2_list.push(batch2.clone());
144 });
145 // At this point, `ack2` should exactly equal `trace2.read_upper()`, as they are both determined by
146 // iterating through batches and capturing the upper bound. This is a great moment to assert that
147 // `trace2`'s physical compaction frontier is before the frontier of completed times in `trace2`.
148 // TODO: in the case that this does not hold, instead "upgrade" the physical compaction frontier.
149 assert!(PartialOrder::less_equal(&trace2.get_physical_compaction(), &acknowledged2.borrow()));
150
151 // Load up deferred work joining each captured `trace2` batch against `trace1`.
152 for batch2 in batch2_list.into_iter() {
153 // It is safe to ask for `ack1` because we have confirmed it to be in advance of `distinguish_since`.
154 let trace1_storage = trace1.batches_through(acknowledged1.borrow()).unwrap();
155 // We could downgrade the capability here, but doing so is a bit complicated mathematically.
156 // TODO: downgrade the capability by searching out the one time in `batch2.lower()` and not
157 // in `batch2.upper()`. Only necessary for non-empty batches, as empty batches may not have
158 // that property.
159 let work = tactic.prep(trace1_storage, vec![batch2], Fresh::Input1, capability.time().clone());
160 todo1.push_back((capability.clone(), work));
161 }
162
163 // Droppable handles to shared trace data structures.
164 let mut trace1_option = Some(trace1);
165 let mut trace2_option = Some(trace2);
166
167 move |(input1, frontier1), (input2, frontier2), output| {
168
169 // 1. Consuming input.
170 //
171 // The join computation repeatedly accepts batches of updates from each of its inputs.
172 //
173 // For each accepted batch, it prepares a work-item to join the batch against previously "accepted"
174 // updates from its other input. It is important to track which updates have been accepted, because
175 // we use a shared trace and there may be updates present that are in advance of this accepted bound.
176 //
177 // Batches are accepted: 1. in bulk at start-up (above), 2. as we observe them in the input stream,
178 // and 3. if the trace can confirm a region of empty space directly following our accepted bound.
179 // This last case is a consequence of our inability to transmit empty batches, as they may be formed
180 // in the absence of timely dataflow capabilities.
181
182 // Drain input 1, prepare work.
183 input1.for_each(|capability, data| {
184 // This test *should* always pass, as we only drop a trace in response to the other input emptying.
185 if let Some(ref mut trace2) = trace2_option {
186 let capability = capability.retain(0);
187 for batch1 in data.drain(..) {
188 // Ignore any pre-loaded data.
189 if PartialOrder::less_equal(&acknowledged1, batch1.lower()) {
190 if !batch1.is_empty() {
191 // It is safe to ask for `ack2` as we validated that it was at least `get_physical_compaction()`
192 // at start-up, and have held back physical compaction ever since.
193 let trace2_storage = trace2.batches_through(acknowledged2.borrow()).unwrap();
194 let work = tactic.prep(vec![batch1.clone()], trace2_storage, Fresh::Input0, capability.time().clone());
195 todo0.push_back((capability.clone(), work));
196 }
197
198 // To update `acknowledged1` we might presume that `batch1.lower` should equal it, but we
199 // may have skipped over empty batches. Still, the batches are in-order, and we should be
200 // able to just assume the most recent `batch1.upper`
201 debug_assert!(PartialOrder::less_equal(&acknowledged1, batch1.upper()));
202 acknowledged1.clone_from(batch1.upper());
203 }
204 }
205 }
206 else { panic!("`trace2_option` dropped before `input1` emptied!"); }
207 });
208
209 // Drain input 2, prepare work.
210 input2.for_each(|capability, data| {
211 // This test *should* always pass, as we only drop a trace in response to the other input emptying.
212 if let Some(ref mut trace1) = trace1_option {
213 let capability = capability.retain(0);
214 for batch2 in data.drain(..) {
215 // Ignore any pre-loaded data.
216 if PartialOrder::less_equal(&acknowledged2, batch2.lower()) {
217 if !batch2.is_empty() {
218 // It is safe to ask for `ack1` as we validated that it was at least `get_physical_compaction()`
219 // at start-up, and have held back physical compaction ever since.
220 let trace1_storage = trace1.batches_through(acknowledged1.borrow()).unwrap();
221 let work = tactic.prep(trace1_storage, vec![batch2.clone()], Fresh::Input1, capability.time().clone());
222 todo1.push_back((capability.clone(), work));
223 }
224
225 // To update `acknowledged2` we might presume that `batch2.lower` should equal it, but we
226 // may have skipped over empty batches. Still, the batches are in-order, and we should be
227 // able to just assume the most recent `batch2.upper`
228 debug_assert!(PartialOrder::less_equal(&acknowledged2, batch2.upper()));
229 acknowledged2.clone_from(batch2.upper());
230 }
231 }
232 }
233 else { panic!("`trace1_option` dropped before `input2` emptied!"); }
234 });
235
236 // Advance acknowledged frontiers through any empty regions that we may not receive as batches.
237 if let Some(trace1) = trace1_option.as_mut() {
238 trace1.advance_upper(&mut acknowledged1);
239 }
240 if let Some(trace2) = trace2_option.as_mut() {
241 trace2.advance_upper(&mut acknowledged2);
242 }
243
244 // 2. Join computation.
245 //
246 // For each of the inputs, we do some amount of work (measured in terms of number
247 // of output records produced). This is meant to yield control to allow downstream
248 // operators to consume and reduce the output, but it it also means to provide some
249 // degree of responsiveness. There is a potential risk here that if we fall behind
250 // then the increasing queues hold back physical compaction of the underlying traces
251 // which results in unintentionally quadratic processing time (each batch of either
252 // input must scan all batches from the other input).
253
254 // Perform some amount of outstanding work by pulling the deferred iterators and shipping the
255 // containers they yield. Each direction drains against its own half of the budget, so a burst
256 // on one input cannot starve the other. We reschedule the operator whenever any work remains,
257 // which is observable directly: an iterator has yet to yield `None`. The budget is split from
258 // `2_000_000` to preserve the historical `1_000_000` of progress per input each activation.
259 // The driver only ships finished containers (`give_container`), never pushing records, so it
260 // pins the operator output to `NoopBuilder<C>` — the builder for exactly this "containers ready
261 // to go" case, which is a `ContainerBuilder` for any `C` without further bounds.
262 let output: &mut OutputBuilderSession<'_, Tr1::Time, NoopBuilder<C>> = output;
263 let mut drain = |queue: &mut VecDeque<(Capability<Tr1::Time>, Box<dyn Iterator<Item = C>>)>, mut fuel: isize| {
264 while fuel >= 0 {
265 let Some((capability, work)) = queue.front_mut() else { break };
266 match work.next() {
267 Some(mut container) => {
268 fuel -= container.record_count() as isize;
269 output.session_with_builder(&*capability).give_container(&mut container);
270 }
271 None => { queue.pop_front(); }
272 }
273 }
274 };
275 let fuel = 2_000_000;
276 drain(&mut todo0, fuel / 2);
277 drain(&mut todo1, fuel / 2);
278 if !todo0.is_empty() || !todo1.is_empty() {
279 activator.activate();
280 }
281
282 // 3. Trace maintenance.
283 //
284 // Importantly, we use `input.frontier()` here rather than `acknowledged` to track
285 // the progress of an input, because should we ever drop one of the traces we will
286 // lose the ability to extract information from anything other than the input.
287 // For example, if we dropped `trace2` we would not be able to use `advance_upper`
288 // to keep `acknowledged2` up to date wrt empty batches, and would hold back logical
289 // compaction of `trace1`.
290
291 // Maintain `trace1`. Drop if `input2` is empty, or advance based on future needs.
292 if let Some(trace1) = trace1_option.as_mut() {
293 if frontier2.is_empty() { trace1_option = None; }
294 else {
295 // Allow `trace1` to compact logically up to the frontier we may yet receive,
296 // in the opposing input (`input2`). All `input2` times will be beyond this
297 // frontier, and joined times only need to be accurate when advanced to it.
298 trace1.set_logical_compaction(frontier2.frontier());
299 // Allow `trace1` to compact physically up to the upper bound of batches we
300 // have received in its input (`input1`). We will not require a cursor that
301 // is not beyond this bound.
302 trace1.set_physical_compaction(acknowledged1.borrow());
303 }
304 }
305
306 // Maintain `trace2`. Drop if `input1` is empty, or advance based on future needs.
307 if let Some(trace2) = trace2_option.as_mut() {
308 if frontier1.is_empty() { trace2_option = None;}
309 else {
310 // Allow `trace2` to compact logically up to the frontier we may yet receive,
311 // in the opposing input (`input1`). All `input1` times will be beyond this
312 // frontier, and joined times only need to be accurate when advanced to it.
313 trace2.set_logical_compaction(frontier1.frontier());
314 // Allow `trace2` to compact physically up to the upper bound of batches we
315 // have received in its input (`input2`). We will not require a cursor that
316 // is not beyond this bound.
317 trace2.set_physical_compaction(acknowledged2.borrow());
318 }
319 }
320 }
321 })
322}
323
324/// Cursor-based join: the conventional [`JoinTactic`] implementation and its per-batch worker.
325mod cursors {
326
327 use std::cell::RefCell;
328 use std::rc::Rc;
329
330 use super::*;
331
332 /// The conventional cursor-based [`JoinTactic`].
333 ///
334 /// It builds a [`CursorList`] over each input batch list and plays the merge-join out at whatever rate
335 /// the driver's fuel allows. Each prepared unit joins a `B0`-side cursor against a `B1`-side cursor,
336 /// emitting `(val0, val1)` to `logic` and yielding the output containers `logic` fills. `logic` is
337 /// shared across all outstanding units (an `Rc<RefCell<_>>`), preserving the single mutable-state
338 /// semantics of one closure threaded through every match — each unit is a self-contained `'static`
339 /// iterator, so it cannot borrow the tactic.
340 ///
341 /// It is parameterized by the builder `CB` into which `logic` pushes output; the [`JoinTactic`] it
342 /// implements is over the container `CB` yields (`CB::Container`).
343 pub struct CursorTactic<B0, B1, L, CB>
344 where
345 B0: BatchReader + Navigable,
346 B1: BatchReader<Time = B0::Time> + Navigable,
347 B0::Cursor: Cursor<Time = B0::Time>,
348 B1::Cursor: for<'a> Cursor<Key<'a> = <B0::Cursor as Cursor>::Key<'a>, Time = B0::Time>,
349 {
350 logic: Rc<RefCell<L>>,
351 _marker: std::marker::PhantomData<(B0, B1, CB)>,
352 }
353
354 impl<B0, B1, L, CB> CursorTactic<B0, B1, L, CB>
355 where
356 B0: BatchReader + Navigable,
357 B1: BatchReader<Time = B0::Time> + Navigable,
358 B0::Cursor: Cursor<Time = B0::Time>,
359 B1::Cursor: for<'a> Cursor<Key<'a> = <B0::Cursor as Cursor>::Key<'a>, Time = B0::Time>,
360 {
361 /// Construct a tactic that applies `logic` to each matched `(key, val0, val1)`.
362 pub fn new(logic: L) -> Self {
363 CursorTactic { logic: Rc::new(RefCell::new(logic)), _marker: std::marker::PhantomData }
364 }
365 }
366
367 impl<B0, B1, L, CB> JoinTactic<B0, B1, CB::Container> for CursorTactic<B0, B1, L, CB>
368 where
369 B0: BatchReader + Navigable + 'static,
370 B1: BatchReader<Time = B0::Time> + Navigable + 'static,
371 B0::Cursor: Cursor<Time = B0::Time>,
372 B1::Cursor: for<'a> Cursor<Key<'a> = <B0::Cursor as Cursor>::Key<'a>, Time = B0::Time>,
373 CB: ContainerBuilder<Container: Default> + 'static,
374 L: for<'a> FnMut(<B0::Cursor as Cursor>::Key<'a>, <B0::Cursor as Cursor>::Val<'a>, <B1::Cursor as Cursor>::Val<'a>, B0::Time, &<B0::Cursor as Cursor>::Diff, &<B1::Cursor as Cursor>::Diff, &mut CB) + 'static,
375 {
376 fn prep(&mut self, input0: Vec<B0>, input1: Vec<B1>, fresh: Fresh, meet: B0::Time) -> Box<dyn Iterator<Item = CB::Container>> {
377 // The accumulated side's history is advanced by `meet` to consolidate it before the
378 // cross-product; the fresh side is left, as its times already lie at or beyond `meet`. `fresh`
379 // fixes which side is which. The advance is output-neutral either way (the fresh side's times are
380 // at or beyond `meet`, so the joined time is too), so it is purely a consolidation: it pays off
381 // when the accumulated side carries times below `meet`, and is a wasted scan when it does not. A
382 // more precise rule would skip the scan when the side is already entirely at or beyond `meet`,
383 // but detecting that needs both frontiers, not just `lower`: a batch's times lie at or beyond
384 // both its `lower` and its `since`, so the side is entirely beyond `meet` exactly when
385 // `meet <= lower` or `meet <= since`. A fresh batch is caught by `lower` (its `since` is
386 // `minimum`), a compacted trace by `since` (its `lower` is `minimum`); checking `lower` alone
387 // would wrongly advance a compacted trace whose times are all already at or beyond `meet`. We
388 // keep the simpler fresh-based choice and accept the occasional no-op scan.
389 let (cursor1, storage1) = cursor_list(input0);
390 let (cursor2, storage2) = cursor_list(input1);
391 let (advance1, advance2) = match fresh {
392 Fresh::Input0 => (false, true),
393 Fresh::Input1 => (true, false),
394 };
395 Box::new(DeferredIter {
396 cursor1,
397 storage1,
398 cursor2,
399 storage2,
400 meet,
401 advance1,
402 advance2,
403 logic: Rc::clone(&self.logic),
404 builder: CB::default(),
405 ready: VecDeque::new(),
406 done: false,
407 })
408 }
409 }
410
411 /// Deferred join computation, as an iterator of output containers.
412 ///
413 /// The structure wraps cursors which allow us to play out join computation at whatever rate we like.
414 /// This allows us to avoid producing and buffering massive amounts of data, without giving the timely
415 /// dataflow system a chance to run operators that can consume and aggregate the data. Each `next` plays
416 /// the merge-join forward until the builder yields a container (or the cursors run dry), matching the
417 /// former per-unit `work` loop but suspending at container boundaries rather than under a fuel budget:
418 /// the driver stops pulling once its budget is spent and resumes the same iterator next activation.
419 struct DeferredIter<T, C1, C2, L, CB>
420 where
421 T: Timestamp+Lattice,
422 C1: Cursor<Time=T>,
423 C2: for<'a> Cursor<Key<'a>=C1::Key<'a>, Time=T>,
424 CB: ContainerBuilder,
425 {
426 cursor1: C1,
427 storage1: C1::Storage,
428 cursor2: C2,
429 storage2: C2::Storage,
430 /// The capability's time, at which this unit's output ships; the lower envelope for consolidation.
431 meet: T,
432 /// Whether to advance each side's history by `meet` before consolidation.
433 advance1: bool,
434 advance2: bool,
435 /// The output closure, shared across all outstanding units.
436 logic: Rc<RefCell<L>>,
437 /// The builder `logic` fills; drained into `ready` as containers complete.
438 builder: CB,
439 /// Completed containers awaiting a `next` call.
440 ready: VecDeque<CB::Container>,
441 done: bool,
442 }
443
444 impl<T, C1, C2, L, CB> Iterator for DeferredIter<T, C1, C2, L, CB>
445 where
446 T: Timestamp+Lattice,
447 C1: Cursor<Time=T>,
448 C2: for<'a> Cursor<Key<'a>=C1::Key<'a>, Time=T>,
449 CB: ContainerBuilder<Container: Default>,
450 L: for<'a> FnMut(C1::Key<'a>, C1::Val<'a>, C2::Val<'a>, T, &C1::Diff, &C2::Diff, &mut CB),
451 {
452 type Item = CB::Container;
453
454 /// Play the merge-join forward until a container is ready, or the cursors run dry.
455 #[inline(never)]
456 fn next(&mut self) -> Option<CB::Container> {
457 // Serve any container completed on an earlier call first.
458 if let Some(container) = self.ready.pop_front() { return Some(container); }
459 if self.done { return None; }
460
461 // The accumulated side is advanced by `meet` to consolidate its history; the fresh side is left,
462 // as its times already lie at or beyond `meet`. The choice was fixed per side at construction,
463 // from which input carried the fresh batch.
464 let meet1 = if self.advance1 { Some(&self.meet) } else { None };
465 let meet2 = if self.advance2 { Some(&self.meet) } else { None };
466
467 let storage1 = &self.storage1;
468 let storage2 = &self.storage2;
469 let cursor1 = &mut self.cursor1;
470 let cursor2 = &mut self.cursor2;
471 let builder = &mut self.builder;
472 let ready = &mut self.ready;
473 let mut logic = self.logic.borrow_mut();
474 let logic = &mut *logic;
475
476 let mut thinker = JoinThinker::new();
477 let mut exhausted = false;
478
479 while ready.is_empty() {
480 match (cursor1.get_key(storage1), cursor2.get_key(storage2)) {
481 (Some(key1), Some(key2)) => match key1.cmp(&key2) {
482 Ordering::Less => cursor1.seek_key(storage1, key2),
483 Ordering::Greater => cursor2.seek_key(storage2, key1),
484 Ordering::Equal => {
485
486 thinker.history1.edits.load(cursor1, storage1, meet1);
487 thinker.history2.edits.load(cursor2, storage2, meet2);
488
489 thinker.think(|v1,v2,t,r1,r2| {
490 logic(key1, v1, v2, t, r1, r2, builder);
491 });
492
493 cursor1.step_key(storage1);
494 cursor2.step_key(storage2);
495
496 thinker.history1.clear();
497 thinker.history2.clear();
498
499 // Move any completed containers aside; we yield them one at a time.
500 while let Some(container) = builder.extract() {
501 // Avoiding the mem::take would require a non-iterator trait.
502 ready.push_back(std::mem::take(container));
503 }
504 }
505 },
506 // One side is exhausted; no further keys can match.
507 _ => { exhausted = true; break; }
508 }
509 }
510
511 if exhausted {
512 self.done = true;
513 // Flush the final partial container.
514 while let Some(container) = builder.finish() {
515 // Avoiding the mem::take would require a non-iterator trait.
516 ready.push_back(std::mem::take(container));
517 }
518 }
519
520 ready.pop_front()
521 }
522 }
523
524 struct JoinThinker<V1, V2, T, D1, D2> {
525 pub history1: ValueHistory<V1, T, D1>,
526 pub history2: ValueHistory<V2, T, D2>,
527 }
528
529 impl<V1, V2, T, D1, D2> JoinThinker<V1, V2, T, D1, D2>
530 where
531 V1: Copy + Ord,
532 V2: Copy + Ord,
533 T: Ord + Clone + Lattice,
534 D1: Clone + crate::difference::Semigroup,
535 D2: Clone + crate::difference::Semigroup,
536 {
537 fn new() -> Self {
538 JoinThinker {
539 history1: ValueHistory::new(),
540 history2: ValueHistory::new(),
541 }
542 }
543
544 fn think<F: FnMut(V1, V2, T, &D1, &D2)>(&mut self, mut results: F) {
545
546 // for reasonably sized edits, do the dead-simple thing.
547 if self.history1.edits.len() < 10 || self.history2.edits.len() < 10 {
548 self.history1.edits.map(|v1, t1, d1| {
549 self.history2.edits.map(|v2, t2, d2| {
550 results(v1, v2, t1.join(t2), d1, d2);
551 })
552 })
553 }
554 else {
555
556 let mut replay1 = self.history1.replay();
557 let mut replay2 = self.history2.replay();
558
559 // TODO: It seems like there is probably a good deal of redundant `advance_buffer_by`
560 // in here. If a time is ever repeated, for example, the call will be identical
561 // and accomplish nothing. If only a single record has been added, it may not
562 // be worth the time to collapse (advance, re-sort) the data when a linear scan
563 // is sufficient.
564
565 while !replay1.is_done() && !replay2.is_done() {
566
567 if replay1.time().unwrap().cmp(replay2.time().unwrap()) == ::std::cmp::Ordering::Less {
568 replay2.advance_buffer_by(replay1.meet().unwrap());
569 for &((val2, ref time2), ref diff2) in replay2.buffer().iter() {
570 let (val1, time1, diff1) = replay1.edit().unwrap();
571 results(val1, val2, time1.join(time2), diff1, diff2);
572 }
573 replay1.step();
574 }
575 else {
576 replay1.advance_buffer_by(replay2.meet().unwrap());
577 for &((val1, ref time1), ref diff1) in replay1.buffer().iter() {
578 let (val2, time2, diff2) = replay2.edit().unwrap();
579 results(val1, val2, time1.join(time2), diff1, diff2);
580 }
581 replay2.step();
582 }
583 }
584
585 while !replay1.is_done() {
586 replay2.advance_buffer_by(replay1.meet().unwrap());
587 for &((val2, ref time2), ref diff2) in replay2.buffer().iter() {
588 let (val1, time1, diff1) = replay1.edit().unwrap();
589 results(val1, val2, time1.join(time2), diff1, diff2);
590 }
591 replay1.step();
592 }
593 while !replay2.is_done() {
594 replay1.advance_buffer_by(replay2.meet().unwrap());
595 for &((val1, ref time1), ref diff1) in replay1.buffer().iter() {
596 let (val2, time2, diff2) = replay2.edit().unwrap();
597 results(val1, val2, time1.join(time2), diff1, diff2);
598 }
599 replay2.step();
600 }
601 }
602 }
603 }
604}