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;
7
8use timely::{Accountable, ContainerBuilder};
9use timely::container::PushInto;
10use timely::order::PartialOrder;
11use timely::progress::Timestamp;
12use timely::dataflow::{Scope, Stream};
13use timely::dataflow::operators::generic::{Operator, OutputBuilderSession, Session};
14use timely::dataflow::channels::pact::Pipeline;
15use timely::dataflow::operators::Capability;
16
17use crate::lattice::Lattice;
18use crate::operators::arrange::Arranged;
19use crate::trace::{BatchReader, Cursor};
20use crate::operators::ValueHistory;
21
22use crate::trace::TraceReader;
23
24/// The session passed to join closures.
25pub type JoinSession<'a, 'b, T, CB, CT> = Session<'a, 'b, T, EffortBuilder<CB>, CT>;
26
27/// A container builder that tracks the length of outputs to estimate the effort of join closures.
28#[derive(Default, Debug)]
29pub struct EffortBuilder<CB>(pub std::cell::Cell<usize>, pub CB);
30
31impl<CB: ContainerBuilder> timely::container::ContainerBuilder for EffortBuilder<CB> {
32 type Container = CB::Container;
33
34 #[inline]
35 fn extract(&mut self) -> Option<&mut Self::Container> {
36 let extracted = self.1.extract();
37 self.0.replace(self.0.take() + extracted.as_ref().map_or(0, |e| e.record_count() as usize));
38 extracted
39 }
40
41 #[inline]
42 fn finish(&mut self) -> Option<&mut Self::Container> {
43 let finished = self.1.finish();
44 self.0.replace(self.0.take() + finished.as_ref().map_or(0, |e| e.record_count() as usize));
45 finished
46 }
47}
48
49impl<CB: PushInto<D>, D> PushInto<D> for EffortBuilder<CB> {
50 #[inline]
51 fn push_into(&mut self, item: D) {
52 self.1.push_into(item);
53 }
54}
55
56/// An equijoin of two traces, sharing a common key type.
57///
58/// This method exists to provide join functionality without opinions on the specific input types, keys and values,
59/// that should be presented. The two traces here can have arbitrary key and value types, which can be unsized and
60/// even potentially unrelated to the input collection data. Importantly, the key and value types could be generic
61/// associated types (GATs) of the traces, and we would seemingly struggle to frame these types as trait arguments.
62///
63/// The implementation produces a caller-specified container. Implementations can use [`AsCollection`] to wrap the
64/// output stream in a collection.
65///
66/// The "correctness" of this method depends heavily on the behavior of the supplied `result` function.
67///
68/// [`AsCollection`]: crate::collection::AsCollection
69pub fn join_traces<G, T1, T2, L, CB>(arranged1: Arranged<G,T1>, arranged2: Arranged<G,T2>, mut result: L) -> Stream<G, CB::Container>
70where
71 G: Scope<Timestamp=T1::Time>,
72 T1: TraceReader+Clone+'static,
73 T2: for<'a> TraceReader<Key<'a>=T1::Key<'a>, Time=T1::Time>+Clone+'static,
74 L: FnMut(T1::Key<'_>,T1::Val<'_>,T2::Val<'_>,&G::Timestamp,&T1::Diff,&T2::Diff,&mut JoinSession<T1::Time, CB, Capability<T1::Time>>)+'static,
75 CB: ContainerBuilder,
76{
77 // Rename traces for symmetry from here on out.
78 let mut trace1 = arranged1.trace.clone();
79 let mut trace2 = arranged2.trace.clone();
80
81 let scope = arranged1.stream.scope();
82 arranged1.stream.binary_frontier(arranged2.stream, Pipeline, Pipeline, "Join", move |capability, info| {
83
84 // Acquire an activator to reschedule the operator when it has unfinished work.
85 use timely::scheduling::Activator;
86 let activations = scope.activations().clone();
87 let activator = Activator::new(info.address, activations);
88
89 // Our initial invariants are that for each trace, physical compaction is less or equal the trace's upper bound.
90 // These invariants ensure that we can reference observed batch frontiers from `_start_upper` onward, as long as
91 // we maintain our physical compaction capabilities appropriately. These assertions are tested as we load up the
92 // initial work for the two traces, and before the operator is constructed.
93
94 // Acknowledged frontier for each input.
95 // These two are used exclusively to track batch boundaries on which we may want/need to call `cursor_through`.
96 // They will drive our physical compaction of each trace, and we want to maintain at all times that each is beyond
97 // the physical compaction frontier of their corresponding trace.
98 // Should we ever *drop* a trace, these are 1. much harder to maintain correctly, but 2. no longer used.
99 use timely::progress::frontier::Antichain;
100 let mut acknowledged1 = Antichain::from_elem(<G::Timestamp>::minimum());
101 let mut acknowledged2 = Antichain::from_elem(<G::Timestamp>::minimum());
102
103 // deferred work of batches from each input.
104 let mut todo1 = std::collections::VecDeque::new();
105 let mut todo2 = std::collections::VecDeque::new();
106
107 // We'll unload the initial batches here, to put ourselves in a less non-deterministic state to start.
108 trace1.map_batches(|batch1| {
109 acknowledged1.clone_from(batch1.upper());
110 // No `todo1` work here, because we haven't accepted anything into `batches2` yet.
111 // It is effectively "empty", because we choose to drain `trace1` before `trace2`.
112 // Once we start streaming batches in, we will need to respond to new batches from
113 // `input1` with logic that would have otherwise been here. Check out the next loop
114 // for the structure.
115 });
116 // At this point, `ack1` should exactly equal `trace1.read_upper()`, as they are both determined by
117 // iterating through batches and capturing the upper bound. This is a great moment to assert that
118 // `trace1`'s physical compaction frontier is before the frontier of completed times in `trace1`.
119 // TODO: in the case that this does not hold, instead "upgrade" the physical compaction frontier.
120 assert!(PartialOrder::less_equal(&trace1.get_physical_compaction(), &acknowledged1.borrow()));
121
122 // We capture batch2 cursors first and establish work second to avoid taking a `RefCell` lock
123 // on both traces at the same time, as they could be the same trace and this would panic.
124 let mut batch2_cursors = Vec::new();
125 trace2.map_batches(|batch2| {
126 acknowledged2.clone_from(batch2.upper());
127 batch2_cursors.push((batch2.cursor(), batch2.clone()));
128 });
129 // At this point, `ack2` should exactly equal `trace2.read_upper()`, as they are both determined by
130 // iterating through batches and capturing the upper bound. This is a great moment to assert that
131 // `trace2`'s physical compaction frontier is before the frontier of completed times in `trace2`.
132 // TODO: in the case that this does not hold, instead "upgrade" the physical compaction frontier.
133 assert!(PartialOrder::less_equal(&trace2.get_physical_compaction(), &acknowledged2.borrow()));
134
135 // Load up deferred work using trace2 cursors and batches captured just above.
136 for (batch2_cursor, batch2) in batch2_cursors.into_iter() {
137 // It is safe to ask for `ack1` because we have confirmed it to be in advance of `distinguish_since`.
138 let (trace1_cursor, trace1_storage) = trace1.cursor_through(acknowledged1.borrow()).unwrap();
139 // We could downgrade the capability here, but doing so is a bit complicated mathematically.
140 // TODO: downgrade the capability by searching out the one time in `batch2.lower()` and not
141 // in `batch2.upper()`. Only necessary for non-empty batches, as empty batches may not have
142 // that property.
143 todo2.push_back(Deferred::new(trace1_cursor, trace1_storage, batch2_cursor, batch2.clone(), capability.clone()));
144 }
145
146 // Droppable handles to shared trace data structures.
147 let mut trace1_option = Some(trace1);
148 let mut trace2_option = Some(trace2);
149
150 move |(input1, frontier1), (input2, frontier2), output| {
151
152 // 1. Consuming input.
153 //
154 // The join computation repeatedly accepts batches of updates from each of its inputs.
155 //
156 // For each accepted batch, it prepares a work-item to join the batch against previously "accepted"
157 // updates from its other input. It is important to track which updates have been accepted, because
158 // we use a shared trace and there may be updates present that are in advance of this accepted bound.
159 //
160 // Batches are accepted: 1. in bulk at start-up (above), 2. as we observe them in the input stream,
161 // and 3. if the trace can confirm a region of empty space directly following our accepted bound.
162 // This last case is a consequence of our inability to transmit empty batches, as they may be formed
163 // in the absence of timely dataflow capabilities.
164
165 // Drain input 1, prepare work.
166 input1.for_each(|capability, data| {
167 // This test *should* always pass, as we only drop a trace in response to the other input emptying.
168 if let Some(ref mut trace2) = trace2_option {
169 let capability = capability.retain(0);
170 for batch1 in data.drain(..) {
171 // Ignore any pre-loaded data.
172 if PartialOrder::less_equal(&acknowledged1, batch1.lower()) {
173 if !batch1.is_empty() {
174 // It is safe to ask for `ack2` as we validated that it was at least `get_physical_compaction()`
175 // at start-up, and have held back physical compaction ever since.
176 let (trace2_cursor, trace2_storage) = trace2.cursor_through(acknowledged2.borrow()).unwrap();
177 let batch1_cursor = batch1.cursor();
178 todo1.push_back(Deferred::new(trace2_cursor, trace2_storage, batch1_cursor, batch1.clone(), capability.clone()));
179 }
180
181 // To update `acknowledged1` we might presume that `batch1.lower` should equal it, but we
182 // may have skipped over empty batches. Still, the batches are in-order, and we should be
183 // able to just assume the most recent `batch1.upper`
184 debug_assert!(PartialOrder::less_equal(&acknowledged1, batch1.upper()));
185 acknowledged1.clone_from(batch1.upper());
186 }
187 }
188 }
189 else { panic!("`trace2_option` dropped before `input1` emptied!"); }
190 });
191
192 // Drain input 2, prepare work.
193 input2.for_each(|capability, data| {
194 // This test *should* always pass, as we only drop a trace in response to the other input emptying.
195 if let Some(ref mut trace1) = trace1_option {
196 let capability = capability.retain(0);
197 for batch2 in data.drain(..) {
198 // Ignore any pre-loaded data.
199 if PartialOrder::less_equal(&acknowledged2, batch2.lower()) {
200 if !batch2.is_empty() {
201 // It is safe to ask for `ack1` as we validated that it was at least `get_physical_compaction()`
202 // at start-up, and have held back physical compaction ever since.
203 let (trace1_cursor, trace1_storage) = trace1.cursor_through(acknowledged1.borrow()).unwrap();
204 let batch2_cursor = batch2.cursor();
205 todo2.push_back(Deferred::new(trace1_cursor, trace1_storage, batch2_cursor, batch2.clone(), capability.clone()));
206 }
207
208 // To update `acknowledged2` we might presume that `batch2.lower` should equal it, but we
209 // may have skipped over empty batches. Still, the batches are in-order, and we should be
210 // able to just assume the most recent `batch2.upper`
211 debug_assert!(PartialOrder::less_equal(&acknowledged2, batch2.upper()));
212 acknowledged2.clone_from(batch2.upper());
213 }
214 }
215 }
216 else { panic!("`trace1_option` dropped before `input2` emptied!"); }
217 });
218
219 // Advance acknowledged frontiers through any empty regions that we may not receive as batches.
220 if let Some(trace1) = trace1_option.as_mut() {
221 trace1.advance_upper(&mut acknowledged1);
222 }
223 if let Some(trace2) = trace2_option.as_mut() {
224 trace2.advance_upper(&mut acknowledged2);
225 }
226
227 // 2. Join computation.
228 //
229 // For each of the inputs, we do some amount of work (measured in terms of number
230 // of output records produced). This is meant to yield control to allow downstream
231 // operators to consume and reduce the output, but it it also means to provide some
232 // degree of responsiveness. There is a potential risk here that if we fall behind
233 // then the increasing queues hold back physical compaction of the underlying traces
234 // which results in unintentionally quadratic processing time (each batch of either
235 // input must scan all batches from the other input).
236
237 // Perform some amount of outstanding work.
238 let mut fuel = 1_000_000;
239 while !todo1.is_empty() && fuel > 0 {
240 todo1.front_mut().unwrap().work(
241 output,
242 |k,v2,v1,t,r2,r1,c| result(k,v1,v2,t,r1,r2,c),
243 &mut fuel
244 );
245 if !todo1.front().unwrap().work_remains() { todo1.pop_front(); }
246 }
247
248 // Perform some amount of outstanding work.
249 let mut fuel = 1_000_000;
250 while !todo2.is_empty() && fuel > 0 {
251 todo2.front_mut().unwrap().work(
252 output,
253 |k,v1,v2,t,r1,r2,c| result(k,v1,v2,t,r1,r2,c),
254 &mut fuel
255 );
256 if !todo2.front().unwrap().work_remains() { todo2.pop_front(); }
257 }
258
259 // Re-activate operator if work remains.
260 if !todo1.is_empty() || !todo2.is_empty() {
261 activator.activate();
262 }
263
264 // 3. Trace maintenance.
265 //
266 // Importantly, we use `input.frontier()` here rather than `acknowledged` to track
267 // the progress of an input, because should we ever drop one of the traces we will
268 // lose the ability to extract information from anything other than the input.
269 // For example, if we dropped `trace2` we would not be able to use `advance_upper`
270 // to keep `acknowledged2` up to date wrt empty batches, and would hold back logical
271 // compaction of `trace1`.
272
273 // Maintain `trace1`. Drop if `input2` is empty, or advance based on future needs.
274 if let Some(trace1) = trace1_option.as_mut() {
275 if frontier2.is_empty() { trace1_option = None; }
276 else {
277 // Allow `trace1` to compact logically up to the frontier we may yet receive,
278 // in the opposing input (`input2`). All `input2` times will be beyond this
279 // frontier, and joined times only need to be accurate when advanced to it.
280 trace1.set_logical_compaction(frontier2.frontier());
281 // Allow `trace1` to compact physically up to the upper bound of batches we
282 // have received in its input (`input1`). We will not require a cursor that
283 // is not beyond this bound.
284 trace1.set_physical_compaction(acknowledged1.borrow());
285 }
286 }
287
288 // Maintain `trace2`. Drop if `input1` is empty, or advance based on future needs.
289 if let Some(trace2) = trace2_option.as_mut() {
290 if frontier1.is_empty() { trace2_option = None;}
291 else {
292 // Allow `trace2` to compact logically up to the frontier we may yet receive,
293 // in the opposing input (`input1`). All `input1` times will be beyond this
294 // frontier, and joined times only need to be accurate when advanced to it.
295 trace2.set_logical_compaction(frontier1.frontier());
296 // Allow `trace2` to compact physically up to the upper bound of batches we
297 // have received in its input (`input2`). We will not require a cursor that
298 // is not beyond this bound.
299 trace2.set_physical_compaction(acknowledged2.borrow());
300 }
301 }
302 }
303 })
304}
305
306
307/// Deferred join computation.
308///
309/// The structure wraps cursors which allow us to play out join computation at whatever rate we like.
310/// This allows us to avoid producing and buffering massive amounts of data, without giving the timely
311/// dataflow system a chance to run operators that can consume and aggregate the data.
312struct Deferred<T, C1, C2>
313where
314 T: Timestamp+Lattice+Ord,
315 C1: Cursor<Time=T>,
316 C2: for<'a> Cursor<Key<'a>=C1::Key<'a>, Time=T>,
317{
318 trace: C1,
319 trace_storage: C1::Storage,
320 batch: C2,
321 batch_storage: C2::Storage,
322 capability: Capability<T>,
323 done: bool,
324}
325
326impl<T, C1, C2> Deferred<T, C1, C2>
327where
328 C1: Cursor<Time=T>,
329 C2: for<'a> Cursor<Key<'a>=C1::Key<'a>, Time=T>,
330 T: Timestamp+Lattice+Ord,
331{
332 fn new(trace: C1, trace_storage: C1::Storage, batch: C2, batch_storage: C2::Storage, capability: Capability<T>) -> Self {
333 Deferred {
334 trace,
335 trace_storage,
336 batch,
337 batch_storage,
338 capability,
339 done: false,
340 }
341 }
342
343 fn work_remains(&self) -> bool {
344 !self.done
345 }
346
347 /// Process keys until at least `fuel` output tuples produced, or the work is exhausted.
348 #[inline(never)]
349 fn work<L, CB: ContainerBuilder>(&mut self, output: &mut OutputBuilderSession<T, EffortBuilder<CB>>, mut logic: L, fuel: &mut usize)
350 where
351 L: for<'a> FnMut(C1::Key<'a>, C1::Val<'a>, C2::Val<'a>, &T, &C1::Diff, &C2::Diff, &mut JoinSession<T, CB, Capability<T>>),
352 {
353
354 let meet = self.capability.time();
355
356 let mut effort = 0;
357 let mut session = output.session_with_builder(&self.capability);
358
359 let trace_storage = &self.trace_storage;
360 let batch_storage = &self.batch_storage;
361
362 let trace = &mut self.trace;
363 let batch = &mut self.batch;
364
365 let mut thinker = JoinThinker::new();
366
367 while let (Some(batch_key), Some(trace_key), true) = (batch.get_key(batch_storage), trace.get_key(trace_storage), effort < *fuel) {
368
369 match trace_key.cmp(&batch_key) {
370 Ordering::Less => trace.seek_key(trace_storage, batch_key),
371 Ordering::Greater => batch.seek_key(batch_storage, trace_key),
372 Ordering::Equal => {
373
374 thinker.history1.edits.load(trace, trace_storage, |time| {
375 let mut time = C1::owned_time(time);
376 time.join_assign(meet);
377 time
378 });
379 thinker.history2.edits.load(batch, batch_storage, |time| C2::owned_time(time));
380
381 // populate `temp` with the results in the best way we know how.
382 thinker.think(|v1,v2,t,r1,r2| {
383 logic(batch_key, v1, v2, &t, r1, r2, &mut session);
384 });
385
386 // TODO: Effort isn't perfectly tracked as we might still have some data in the
387 // session at the moment it's dropped.
388 effort += session.builder().0.take();
389 batch.step_key(batch_storage);
390 trace.step_key(trace_storage);
391
392 thinker.history1.clear();
393 thinker.history2.clear();
394 }
395 }
396 }
397 self.done = !batch.key_valid(batch_storage) || !trace.key_valid(trace_storage);
398
399 if effort > *fuel { *fuel = 0; }
400 else { *fuel -= effort; }
401 }
402}
403
404struct JoinThinker<'a, C1, C2>
405where
406 C1: Cursor,
407 C2: Cursor<Time = C1::Time>,
408{
409 pub history1: ValueHistory<'a, C1>,
410 pub history2: ValueHistory<'a, C2>,
411}
412
413impl<'a, C1, C2> JoinThinker<'a, C1, C2>
414where
415 C1: Cursor,
416 C2: Cursor<Time = C1::Time>,
417{
418 fn new() -> Self {
419 JoinThinker {
420 history1: ValueHistory::new(),
421 history2: ValueHistory::new(),
422 }
423 }
424
425 fn think<F: FnMut(C1::Val<'a>,C2::Val<'a>,C1::Time,&C1::Diff,&C2::Diff)>(&mut self, mut results: F) {
426
427 // for reasonably sized edits, do the dead-simple thing.
428 if self.history1.edits.len() < 10 || self.history2.edits.len() < 10 {
429 self.history1.edits.map(|v1, t1, d1| {
430 self.history2.edits.map(|v2, t2, d2| {
431 results(v1, v2, t1.join(t2), d1, d2);
432 })
433 })
434 }
435 else {
436
437 let mut replay1 = self.history1.replay();
438 let mut replay2 = self.history2.replay();
439
440 // TODO: It seems like there is probably a good deal of redundant `advance_buffer_by`
441 // in here. If a time is ever repeated, for example, the call will be identical
442 // and accomplish nothing. If only a single record has been added, it may not
443 // be worth the time to collapse (advance, re-sort) the data when a linear scan
444 // is sufficient.
445
446 while !replay1.is_done() && !replay2.is_done() {
447
448 if replay1.time().unwrap().cmp(replay2.time().unwrap()) == ::std::cmp::Ordering::Less {
449 replay2.advance_buffer_by(replay1.meet().unwrap());
450 for &((val2, ref time2), ref diff2) in replay2.buffer().iter() {
451 let (val1, time1, diff1) = replay1.edit().unwrap();
452 results(val1, val2, time1.join(time2), diff1, diff2);
453 }
454 replay1.step();
455 }
456 else {
457 replay1.advance_buffer_by(replay2.meet().unwrap());
458 for &((val1, ref time1), ref diff1) in replay1.buffer().iter() {
459 let (val2, time2, diff2) = replay2.edit().unwrap();
460 results(val1, val2, time1.join(time2), diff1, diff2);
461 }
462 replay2.step();
463 }
464 }
465
466 while !replay1.is_done() {
467 replay2.advance_buffer_by(replay1.meet().unwrap());
468 for &((val2, ref time2), ref diff2) in replay2.buffer().iter() {
469 let (val1, time1, diff1) = replay1.edit().unwrap();
470 results(val1, val2, time1.join(time2), diff1, diff2);
471 }
472 replay1.step();
473 }
474 while !replay2.is_done() {
475 replay1.advance_buffer_by(replay2.meet().unwrap());
476 for &((val1, ref time1), ref diff1) in replay1.buffer().iter() {
477 let (val2, time2, diff2) = replay2.edit().unwrap();
478 results(val1, val2, time1.join(time2), diff1, diff2);
479 }
480 replay2.step();
481 }
482 }
483 }
484}