differential_dataflow/operators/
reduce.rs

1//! Applies a reduction function on records grouped by key.
2//!
3//! The `reduce` operator acts on `(key, val)` data.
4//! Records with the same key are grouped together, and a user-supplied reduction function is applied
5//! to the key and the list of values.
6//! The function is expected to populate a list of output values.
7
8use timely::container::PushInto;
9use crate::hashable::Hashable;
10use crate::{Data, ExchangeData, Collection};
11use crate::difference::{Semigroup, Abelian};
12
13use timely::order::PartialOrder;
14use timely::progress::frontier::Antichain;
15use timely::progress::Timestamp;
16use timely::dataflow::*;
17use timely::dataflow::operators::Operator;
18use timely::dataflow::channels::pact::Pipeline;
19use timely::dataflow::operators::Capability;
20
21use crate::operators::arrange::{Arranged, ArrangeByKey, ArrangeBySelf, TraceAgent};
22use crate::lattice::Lattice;
23use crate::trace::{BatchReader, Cursor, Trace, Builder, ExertionLogic, Description};
24use crate::trace::cursor::CursorList;
25use crate::trace::implementations::{KeySpine, KeyBuilder, ValSpine, ValBuilder};
26use crate::trace::implementations::containers::BatchContainer;
27use crate::trace::implementations::merge_batcher::container::MergerChunk;
28use crate::trace::TraceReader;
29
30/// Extension trait for the `reduce` differential dataflow method.
31pub trait Reduce<G: Scope<Timestamp: Lattice+Ord>, K: Data, V: Data, R: Semigroup> {
32    /// Applies a reduction function on records grouped by key.
33    ///
34    /// Input data must be structured as `(key, val)` pairs.
35    /// The user-supplied reduction function takes as arguments
36    ///
37    /// 1. a reference to the key,
38    /// 2. a reference to the slice of values and their accumulated updates,
39    /// 3. a mutuable reference to a vector to populate with output values and accumulated updates.
40    ///
41    /// The user logic is only invoked for non-empty input collections, and it is safe to assume that the
42    /// slice of input values is non-empty. The values are presented in sorted order, as defined by their
43    /// `Ord` implementations.
44    ///
45    /// # Examples
46    ///
47    /// ```
48    /// use differential_dataflow::input::Input;
49    /// use differential_dataflow::operators::Reduce;
50    ///
51    /// ::timely::example(|scope| {
52    ///     // report the smallest value for each group
53    ///     scope.new_collection_from(1 .. 10).1
54    ///          .map(|x| (x / 3, x))
55    ///          .reduce(|_key, input, output| {
56    ///              output.push((*input[0].0, 1))
57    ///          });
58    /// });
59    /// ```
60    fn reduce<L, V2: Data, R2: Ord+Abelian+'static>(&self, logic: L) -> Collection<G, (K, V2), R2>
61    where L: FnMut(&K, &[(&V, R)], &mut Vec<(V2, R2)>)+'static {
62        self.reduce_named("Reduce", logic)
63    }
64
65    /// As `reduce` with the ability to name the operator.
66    fn reduce_named<L, V2: Data, R2: Ord+Abelian+'static>(&self, name: &str, logic: L) -> Collection<G, (K, V2), R2>
67    where L: FnMut(&K, &[(&V, R)], &mut Vec<(V2, R2)>)+'static;
68}
69
70impl<G, K, V, R> Reduce<G, K, V, R> for Collection<G, (K, V), R>
71    where
72        G: Scope<Timestamp: Lattice+Ord>,
73        K: ExchangeData+Hashable,
74        V: ExchangeData,
75        R: ExchangeData+Semigroup,
76 {
77    fn reduce_named<L, V2: Data, R2: Ord+Abelian+'static>(&self, name: &str, logic: L) -> Collection<G, (K, V2), R2>
78        where L: FnMut(&K, &[(&V, R)], &mut Vec<(V2, R2)>)+'static {
79        self.arrange_by_key_named(&format!("Arrange: {}", name))
80            .reduce_named(name, logic)
81    }
82}
83
84impl<G, K: Data, V: Data, T1, R: Ord+Semigroup+'static> Reduce<G, K, V, R> for Arranged<G, T1>
85where
86    G: Scope<Timestamp=T1::Time>,
87    T1: for<'a> TraceReader<Key<'a>=&'a K, KeyOwn = K, Val<'a>=&'a V, Diff=R>+Clone+'static,
88{
89    fn reduce_named<L, V2: Data, R2: Ord+Abelian+'static>(&self, name: &str, logic: L) -> Collection<G, (K, V2), R2>
90        where L: FnMut(&K, &[(&V, R)], &mut Vec<(V2, R2)>)+'static {
91        self.reduce_abelian::<_,ValBuilder<_,_,_,_>,ValSpine<K,V2,_,_>>(name, logic)
92            .as_collection(|k,v| (k.clone(), v.clone()))
93    }
94}
95
96/// Extension trait for the `threshold` and `distinct` differential dataflow methods.
97pub trait Threshold<G: Scope<Timestamp: Lattice+Ord>, K: Data, R1: Semigroup> {
98    /// Transforms the multiplicity of records.
99    ///
100    /// The `threshold` function is obliged to map `R1::zero` to `R2::zero`, or at
101    /// least the computation may behave as if it does. Otherwise, the transformation
102    /// can be nearly arbitrary: the code does not assume any properties of `threshold`.
103    ///
104    /// # Examples
105    ///
106    /// ```
107    /// use differential_dataflow::input::Input;
108    /// use differential_dataflow::operators::Threshold;
109    ///
110    /// ::timely::example(|scope| {
111    ///     // report at most one of each key.
112    ///     scope.new_collection_from(1 .. 10).1
113    ///          .map(|x| x / 3)
114    ///          .threshold(|_,c| c % 2);
115    /// });
116    /// ```
117    fn threshold<R2: Ord+Abelian+'static, F: FnMut(&K, &R1)->R2+'static>(&self, thresh: F) -> Collection<G, K, R2> {
118        self.threshold_named("Threshold", thresh)
119    }
120
121    /// A `threshold` with the ability to name the operator.
122    fn threshold_named<R2: Ord+Abelian+'static, F: FnMut(&K, &R1)->R2+'static>(&self, name: &str, thresh: F) -> Collection<G, K, R2>;
123
124    /// Reduces the collection to one occurrence of each distinct element.
125    ///
126    /// # Examples
127    ///
128    /// ```
129    /// use differential_dataflow::input::Input;
130    /// use differential_dataflow::operators::Threshold;
131    ///
132    /// ::timely::example(|scope| {
133    ///     // report at most one of each key.
134    ///     scope.new_collection_from(1 .. 10).1
135    ///          .map(|x| x / 3)
136    ///          .distinct();
137    /// });
138    /// ```
139    fn distinct(&self) -> Collection<G, K, isize> {
140        self.distinct_core()
141    }
142
143    /// Distinct for general integer differences.
144    ///
145    /// This method allows `distinct` to produce collections whose difference
146    /// type is something other than an `isize` integer, for example perhaps an
147    /// `i32`.
148    fn distinct_core<R2: Ord+Abelian+'static+From<i8>>(&self) -> Collection<G, K, R2> {
149        self.threshold_named("Distinct", |_,_| R2::from(1i8))
150    }
151}
152
153impl<G: Scope<Timestamp: Lattice+Ord>, K: ExchangeData+Hashable, R1: ExchangeData+Semigroup> Threshold<G, K, R1> for Collection<G, K, R1> {
154    fn threshold_named<R2: Ord+Abelian+'static, F: FnMut(&K,&R1)->R2+'static>(&self, name: &str, thresh: F) -> Collection<G, K, R2> {
155        self.arrange_by_self_named(&format!("Arrange: {}", name))
156            .threshold_named(name, thresh)
157    }
158}
159
160impl<G, K: Data, T1, R1: Semigroup> Threshold<G, K, R1> for Arranged<G, T1>
161where
162    G: Scope<Timestamp=T1::Time>,
163    T1: for<'a> TraceReader<Key<'a>=&'a K, KeyOwn = K, Val<'a>=&'a (), Diff=R1>+Clone+'static,
164{
165    fn threshold_named<R2: Ord+Abelian+'static, F: FnMut(&K,&R1)->R2+'static>(&self, name: &str, mut thresh: F) -> Collection<G, K, R2> {
166        self.reduce_abelian::<_,KeyBuilder<K,G::Timestamp,R2>,KeySpine<K,G::Timestamp,R2>>(name, move |k,s,t| t.push(((), thresh(k, &s[0].1))))
167            .as_collection(|k,_| k.clone())
168    }
169}
170
171/// Extension trait for the `count` differential dataflow method.
172pub trait Count<G: Scope<Timestamp: Lattice+Ord>, K: Data, R: Semigroup> {
173    /// Counts the number of occurrences of each element.
174    ///
175    /// # Examples
176    ///
177    /// ```
178    /// use differential_dataflow::input::Input;
179    /// use differential_dataflow::operators::Count;
180    ///
181    /// ::timely::example(|scope| {
182    ///     // report the number of occurrences of each key
183    ///     scope.new_collection_from(1 .. 10).1
184    ///          .map(|x| x / 3)
185    ///          .count();
186    /// });
187    /// ```
188    fn count(&self) -> Collection<G, (K, R), isize> {
189        self.count_core()
190    }
191
192    /// Count for general integer differences.
193    ///
194    /// This method allows `count` to produce collections whose difference
195    /// type is something other than an `isize` integer, for example perhaps an
196    /// `i32`.
197    fn count_core<R2: Ord + Abelian + From<i8> + 'static>(&self) -> Collection<G, (K, R), R2>;
198}
199
200impl<G: Scope<Timestamp: Lattice+Ord>, K: ExchangeData+Hashable, R: ExchangeData+Semigroup> Count<G, K, R> for Collection<G, K, R> {
201    fn count_core<R2: Ord + Abelian + From<i8> + 'static>(&self) -> Collection<G, (K, R), R2> {
202        self.arrange_by_self_named("Arrange: Count")
203            .count_core()
204    }
205}
206
207impl<G, K: Data, T1, R: Data+Semigroup> Count<G, K, R> for Arranged<G, T1>
208where
209    G: Scope<Timestamp=T1::Time>,
210    T1: for<'a> TraceReader<Key<'a>=&'a K, KeyOwn = K, Val<'a>=&'a (), Diff=R>+Clone+'static,
211{
212    fn count_core<R2: Ord + Abelian + From<i8> + 'static>(&self) -> Collection<G, (K, R), R2> {
213        self.reduce_abelian::<_,ValBuilder<K,R,G::Timestamp,R2>,ValSpine<K,R,G::Timestamp,R2>>("Count", |_k,s,t| t.push((s[0].1.clone(), R2::from(1i8))))
214            .as_collection(|k,c| (k.clone(), c.clone()))
215    }
216}
217
218/// Extension trait for the `reduce_core` differential dataflow method.
219pub trait ReduceCore<G: Scope<Timestamp: Lattice+Ord>, K: ToOwned + ?Sized, V: Data, R: Semigroup> {
220    /// Applies `reduce` to arranged data, and returns an arrangement of output data.
221    ///
222    /// This method is used by the more ergonomic `reduce`, `distinct`, and `count` methods, although
223    /// it can be very useful if one needs to manually attach and re-use existing arranged collections.
224    ///
225    /// # Examples
226    ///
227    /// ```
228    /// use differential_dataflow::input::Input;
229    /// use differential_dataflow::operators::reduce::ReduceCore;
230    /// use differential_dataflow::trace::Trace;
231    /// use differential_dataflow::trace::implementations::{ValBuilder, ValSpine};
232    ///
233    /// ::timely::example(|scope| {
234    ///
235    ///     let trace =
236    ///     scope.new_collection_from(1 .. 10u32).1
237    ///          .map(|x| (x, x))
238    ///          .reduce_abelian::<_,ValBuilder<_,_,_,_>,ValSpine<_,_,_,_>>(
239    ///             "Example",
240    ///              move |_key, src, dst| dst.push((*src[0].0, 1))
241    ///          )
242    ///          .trace;
243    /// });
244    /// ```
245    fn reduce_abelian<L, Bu, T2>(&self, name: &str, mut logic: L) -> Arranged<G, TraceAgent<T2>>
246        where
247            T2: for<'a> Trace<
248                Key<'a>= &'a K,
249                KeyOwn = K,
250                ValOwn = V,
251                Time=G::Timestamp,
252                Diff: Abelian,
253            >+'static,
254            Bu: Builder<Time=T2::Time, Input = Vec<((K::Owned, V), T2::Time, T2::Diff)>, Output = T2::Batch>,
255            L: FnMut(&K, &[(&V, R)], &mut Vec<(V, T2::Diff)>)+'static,
256        {
257            self.reduce_core::<_,Bu,T2>(name, move |key, input, output, change| {
258                if !input.is_empty() {
259                    logic(key, input, change);
260                }
261                change.extend(output.drain(..).map(|(x,mut d)| { d.negate(); (x, d) }));
262                crate::consolidation::consolidate(change);
263            })
264        }
265
266    /// Solves for output updates when presented with inputs and would-be outputs.
267    ///
268    /// Unlike `reduce_arranged`, this method may be called with an empty `input`,
269    /// and it may not be safe to index into the first element.
270    /// At least one of the two collections will be non-empty.
271    fn reduce_core<L, Bu, T2>(&self, name: &str, logic: L) -> Arranged<G, TraceAgent<T2>>
272        where
273            T2: for<'a> Trace<
274                Key<'a>=&'a K,
275                KeyOwn = K,
276                ValOwn = V,
277                Time=G::Timestamp,
278            >+'static,
279            Bu: Builder<Time=T2::Time, Input = Vec<((K::Owned, V), T2::Time, T2::Diff)>, Output = T2::Batch>,
280            L: FnMut(&K, &[(&V, R)], &mut Vec<(V,T2::Diff)>, &mut Vec<(V, T2::Diff)>)+'static,
281            ;
282}
283
284impl<G, K, V, R> ReduceCore<G, K, V, R> for Collection<G, (K, V), R>
285where
286    G: Scope,
287    G::Timestamp: Lattice+Ord,
288    K: ExchangeData+Hashable,
289    V: ExchangeData,
290    R: ExchangeData+Semigroup,
291{
292    fn reduce_core<L, Bu, T2>(&self, name: &str, logic: L) -> Arranged<G, TraceAgent<T2>>
293        where
294            V: Data,
295            T2: for<'a> Trace<
296                Key<'a>=&'a K,
297                KeyOwn = K,
298                ValOwn = V,
299                Time=G::Timestamp,
300            >+'static,
301            Bu: Builder<Time=T2::Time, Input = Vec<((K, V), T2::Time, T2::Diff)>, Output = T2::Batch>,
302            L: FnMut(&K, &[(&V, R)], &mut Vec<(V,T2::Diff)>, &mut Vec<(V, T2::Diff)>)+'static,
303    {
304        self.arrange_by_key_named(&format!("Arrange: {}", name))
305            .reduce_core::<_,Bu,_>(name, logic)
306    }
307}
308
309/// A key-wise reduction of values in an input trace.
310///
311/// This method exists to provide reduce functionality without opinions about qualifying trace types.
312pub fn reduce_trace<G, T1, Bu, T2, L>(trace: &Arranged<G, T1>, name: &str, mut logic: L) -> Arranged<G, TraceAgent<T2>>
313where
314    G: Scope<Timestamp=T1::Time>,
315    T1: TraceReader<KeyOwn: Ord> + Clone + 'static,
316    T2: for<'a> Trace<Key<'a>=T1::Key<'a>, KeyOwn=T1::KeyOwn, ValOwn: Data, Time=T1::Time> + 'static,
317    Bu: Builder<Time=T2::Time, Output = T2::Batch, Input: MergerChunk + PushInto<((T1::KeyOwn, T2::ValOwn), T2::Time, T2::Diff)>>,
318    L: FnMut(T1::Key<'_>, &[(T1::Val<'_>, T1::Diff)], &mut Vec<(T2::ValOwn,T2::Diff)>, &mut Vec<(T2::ValOwn, T2::Diff)>)+'static,
319{
320    let mut result_trace = None;
321
322    // fabricate a data-parallel operator using the `unary_notify` pattern.
323    let stream = {
324
325        let result_trace = &mut result_trace;
326        trace.stream.unary_frontier(Pipeline, name, move |_capability, operator_info| {
327
328            // Acquire a logger for arrange events.
329            let logger = trace.stream.scope().logger_for::<crate::logging::DifferentialEventBuilder>("differential/arrange").map(Into::into);
330
331            let activator = Some(trace.stream.scope().activator_for(operator_info.address.clone()));
332            let mut empty = T2::new(operator_info.clone(), logger.clone(), activator);
333            // If there is default exert logic set, install it.
334            if let Some(exert_logic) = trace.stream.scope().config().get::<ExertionLogic>("differential/default_exert_logic").cloned() {
335                empty.set_exert_logic(exert_logic);
336            }
337
338
339            let mut source_trace = trace.trace.clone();
340
341            let (mut output_reader, mut output_writer) = TraceAgent::new(empty, operator_info, logger);
342
343            // let mut output_trace = TraceRc::make_from(agent).0;
344            *result_trace = Some(output_reader.clone());
345
346            // let mut thinker1 = history_replay_prior::HistoryReplayer::<V, V2, G::Timestamp, R, R2>::new();
347            // let mut thinker = history_replay::HistoryReplayer::<V, V2, G::Timestamp, R, R2>::new();
348            let mut new_interesting_times = Vec::<G::Timestamp>::new();
349
350            // Our implementation maintains a list of outstanding `(key, time)` synthetic interesting times,
351            // as well as capabilities for these times (or their lower envelope, at least).
352            let mut interesting = Vec::<(T1::KeyOwn, G::Timestamp)>::new();
353            let mut capabilities = Vec::<Capability<G::Timestamp>>::new();
354
355            // buffers and logic for computing per-key interesting times "efficiently".
356            let mut interesting_times = Vec::<G::Timestamp>::new();
357
358            // Upper and lower frontiers for the pending input and output batches to process.
359            let mut upper_limit = Antichain::from_elem(<G::Timestamp as timely::progress::Timestamp>::minimum());
360            let mut lower_limit = Antichain::from_elem(<G::Timestamp as timely::progress::Timestamp>::minimum());
361
362            // Output batches may need to be built piecemeal, and these temp storage help there.
363            let mut output_upper = Antichain::from_elem(<G::Timestamp as timely::progress::Timestamp>::minimum());
364            let mut output_lower = Antichain::from_elem(<G::Timestamp as timely::progress::Timestamp>::minimum());
365
366            let id = trace.stream.scope().index();
367
368            move |input, output| {
369
370                // The `reduce` operator receives fully formed batches, which each serve as an indication
371                // that the frontier has advanced to the upper bound of their description.
372                //
373                // Although we could act on each individually, several may have been sent, and it makes
374                // sense to accumulate them first to coordinate their re-evaluation. We will need to pay
375                // attention to which times need to be collected under which capability, so that we can
376                // assemble output batches correctly. We will maintain several builders concurrently, and
377                // place output updates into the appropriate builder.
378                //
379                // It turns out we must use notificators, as we cannot await empty batches from arrange to
380                // indicate progress, as the arrange may not hold the capability to send such. Instead, we
381                // must watch for progress here (and the upper bound of received batches) to tell us how
382                // far we can process work.
383                //
384                // We really want to retire all batches we receive, so we want a frontier which reflects
385                // both information from batches as well as progress information. I think this means that
386                // we keep times that are greater than or equal to a time in the other frontier, deduplicated.
387
388                let mut batch_cursors = Vec::new();
389                let mut batch_storage = Vec::new();
390
391                // Downgrade previous upper limit to be current lower limit.
392                lower_limit.clear();
393                lower_limit.extend(upper_limit.borrow().iter().cloned());
394
395                // Drain the input stream of batches, validating the contiguity of the batch descriptions and
396                // capturing a cursor for each of the batches as well as ensuring we hold a capability for the
397                // times in the batch.
398                input.for_each(|capability, batches| {
399
400                    for batch in batches.drain(..) {
401                        upper_limit.clone_from(batch.upper());
402                        batch_cursors.push(batch.cursor());
403                        batch_storage.push(batch);
404                    }
405
406                    // Ensure that `capabilities` covers the capability of the batch.
407                    capabilities.retain(|cap| !capability.time().less_than(cap.time()));
408                    if !capabilities.iter().any(|cap| cap.time().less_equal(capability.time())) {
409                        capabilities.push(capability.retain());
410                    }
411                });
412
413                // Pull in any subsequent empty batches we believe to exist.
414                source_trace.advance_upper(&mut upper_limit);
415
416                // Only if our upper limit has advanced should we do work.
417                if upper_limit != lower_limit {
418
419                    // If we have no capabilities, then we (i) should not produce any outputs and (ii) could not send
420                    // any produced outputs even if they were (incorrectly) produced. We cannot even send empty batches
421                    // to indicate forward progress, and must hope that downstream operators look at progress frontiers
422                    // as well as batch descriptions.
423                    //
424                    // We can (and should) advance source and output traces if `upper_limit` indicates this is possible.
425                    if capabilities.iter().any(|c| !upper_limit.less_equal(c.time())) {
426
427                        // `interesting` contains "warnings" about keys and times that may need to be re-considered.
428                        // We first extract those times from this list that lie in the interval we will process.
429                        sort_dedup(&mut interesting);
430                        // `exposed` contains interesting (key, time)s now below `upper_limit`
431                        let mut exposed_keys = T1::KeyContainer::with_capacity(0);
432                        let mut exposed_time = T1::TimeContainer::with_capacity(0);
433                        // Keep pairs greater or equal to `upper_limit`, and "expose" other pairs.
434                        interesting.retain(|(key, time)| {
435                            if upper_limit.less_equal(time) { true } else {
436                                exposed_keys.push_own(key);
437                                exposed_time.push_own(time);
438                                false
439                            }
440                        });
441
442                        // Prepare an output buffer and builder for each capability.
443                        //
444                        // We buffer and build separately, as outputs are produced grouped by time, whereas the
445                        // builder wants to see outputs grouped by value. While the per-key computation could
446                        // do the re-sorting itself, buffering per-key outputs lets us double check the results
447                        // against other implementations for accuracy.
448                        //
449                        // TODO: It would be better if all updates went into one batch, but timely dataflow prevents
450                        //       this as long as it requires that there is only one capability for each message.
451                        let mut buffers = Vec::<(G::Timestamp, Vec<(T2::ValOwn, G::Timestamp, T2::Diff)>)>::new();
452                        let mut builders = Vec::new();
453                        for cap in capabilities.iter() {
454                            buffers.push((cap.time().clone(), Vec::new()));
455                            builders.push(Bu::new());
456                        }
457
458                        let mut buffer = Bu::Input::default();
459
460                        // cursors for navigating input and output traces.
461                        let (mut source_cursor, source_storage): (T1::Cursor, _) = source_trace.cursor_through(lower_limit.borrow()).expect("failed to acquire source cursor");
462                        let source_storage = &source_storage;
463                        let (mut output_cursor, output_storage): (T2::Cursor, _) = output_reader.cursor_through(lower_limit.borrow()).expect("failed to acquire output cursor");
464                        let output_storage = &output_storage;
465                        let (mut batch_cursor, batch_storage) = (CursorList::new(batch_cursors, &batch_storage), batch_storage);
466                        let batch_storage = &batch_storage;
467
468                        let mut thinker = history_replay::HistoryReplayer::new();
469
470                        // We now march through the keys we must work on, drawing from `batch_cursors` and `exposed`.
471                        //
472                        // We only keep valid cursors (those with more data) in `batch_cursors`, and so its length
473                        // indicates whether more data remain. We move through `exposed` using (index) `exposed_position`.
474                        // There could perhaps be a less provocative variable name.
475                        let mut exposed_position = 0;
476                        while batch_cursor.key_valid(batch_storage) || exposed_position < exposed_keys.len() {
477
478                            // Determine the next key we will work on; could be synthetic, could be from a batch.
479                            let key1 = exposed_keys.get(exposed_position);
480                            let key2 = batch_cursor.get_key(batch_storage);
481                            let key = match (key1, key2) {
482                                (Some(key1), Some(key2)) => ::std::cmp::min(key1, key2),
483                                (Some(key1), None)       => key1,
484                                (None, Some(key2))       => key2,
485                                (None, None)             => unreachable!(),
486                            };
487
488                            // `interesting_times` contains those times between `lower_issued` and `upper_limit`
489                            // that we need to re-consider. We now populate it, but perhaps this should be left
490                            // to the per-key computation, which may be able to avoid examining the times of some
491                            // values (for example, in the case of min/max/topk).
492                            interesting_times.clear();
493
494                            // Populate `interesting_times` with synthetic interesting times (below `upper_limit`) for this key.
495                            while exposed_keys.get(exposed_position) == Some(key) {
496                                interesting_times.push(T1::owned_time(exposed_time.index(exposed_position)));
497                                exposed_position += 1;
498                            }
499
500                            // tidy up times, removing redundancy.
501                            sort_dedup(&mut interesting_times);
502
503                            // do the per-key computation.
504                            let _counters = thinker.compute(
505                                key,
506                                (&mut source_cursor, source_storage),
507                                (&mut output_cursor, output_storage),
508                                (&mut batch_cursor, batch_storage),
509                                &mut interesting_times,
510                                &mut logic,
511                                &upper_limit,
512                                &mut buffers[..],
513                                &mut new_interesting_times,
514                            );
515
516                            if batch_cursor.get_key(batch_storage) == Some(key) {
517                                batch_cursor.step_key(batch_storage);
518                            }
519
520                            // Record future warnings about interesting times (and assert they should be "future").
521                            for time in new_interesting_times.drain(..) {
522                                debug_assert!(upper_limit.less_equal(&time));
523                                interesting.push((T1::owned_key(key), time));
524                            }
525
526                            // Sort each buffer by value and move into the corresponding builder.
527                            // TODO: This makes assumptions about at least one of (i) the stability of `sort_by`,
528                            //       (ii) that the buffers are time-ordered, and (iii) that the builders accept
529                            //       arbitrarily ordered times.
530                            for index in 0 .. buffers.len() {
531                                buffers[index].1.sort_by(|x,y| x.0.cmp(&y.0));
532                                for (val, time, diff) in buffers[index].1.drain(..) {
533                                    buffer.push_into(((T1::owned_key(key), val), time, diff));
534                                    builders[index].push(&mut buffer);
535                                    buffer.clear();
536                                }
537                            }
538                        }
539
540                        // We start sealing output batches from the lower limit (previous upper limit).
541                        // In principle, we could update `lower_limit` itself, and it should arrive at
542                        // `upper_limit` by the end of the process.
543                        output_lower.clear();
544                        output_lower.extend(lower_limit.borrow().iter().cloned());
545
546                        // build and ship each batch (because only one capability per message).
547                        for (index, builder) in builders.drain(..).enumerate() {
548
549                            // Form the upper limit of the next batch, which includes all times greater
550                            // than the input batch, or the capabilities from i + 1 onward.
551                            output_upper.clear();
552                            output_upper.extend(upper_limit.borrow().iter().cloned());
553                            for capability in &capabilities[index + 1 ..] {
554                                output_upper.insert(capability.time().clone());
555                            }
556
557                            if output_upper.borrow() != output_lower.borrow() {
558
559                                let description = Description::new(output_lower.clone(), output_upper.clone(), Antichain::from_elem(G::Timestamp::minimum()));
560                                let batch = builder.done(description);
561
562                                // ship batch to the output, and commit to the output trace.
563                                output.session(&capabilities[index]).give(batch.clone());
564                                output_writer.insert(batch, Some(capabilities[index].time().clone()));
565
566                                output_lower.clear();
567                                output_lower.extend(output_upper.borrow().iter().cloned());
568                            }
569                        }
570
571                        // This should be true, as the final iteration introduces no capabilities, and
572                        // uses exactly `upper_limit` to determine the upper bound. Good to check though.
573                        assert!(output_upper.borrow() == upper_limit.borrow());
574
575                        // Determine the frontier of our interesting times.
576                        let mut frontier = Antichain::<G::Timestamp>::new();
577                        for (_, time) in &interesting {
578                            frontier.insert_ref(time);
579                        }
580
581                        // Update `capabilities` to reflect interesting pairs described by `frontier`.
582                        let mut new_capabilities = Vec::new();
583                        for time in frontier.borrow().iter() {
584                            if let Some(cap) = capabilities.iter().find(|c| c.time().less_equal(time)) {
585                                new_capabilities.push(cap.delayed(time));
586                            }
587                            else {
588                                println!("{}:\tfailed to find capability less than new frontier time:", id);
589                                println!("{}:\t  time: {:?}", id, time);
590                                println!("{}:\t  caps: {:?}", id, capabilities);
591                                println!("{}:\t  uppr: {:?}", id, upper_limit);
592                            }
593                        }
594                        capabilities = new_capabilities;
595
596                        // ensure that observed progress is reflected in the output.
597                        output_writer.seal(upper_limit.clone());
598                    }
599                    else {
600                        output_writer.seal(upper_limit.clone());
601                    }
602
603                    // We only anticipate future times in advance of `upper_limit`.
604                    source_trace.set_logical_compaction(upper_limit.borrow());
605                    output_reader.set_logical_compaction(upper_limit.borrow());
606
607                    // We will only slice the data between future batches.
608                    source_trace.set_physical_compaction(upper_limit.borrow());
609                    output_reader.set_physical_compaction(upper_limit.borrow());
610                }
611
612                // Exert trace maintenance if we have been so requested.
613                output_writer.exert();
614            }
615        }
616    )
617    };
618
619    Arranged { stream, trace: result_trace.unwrap() }
620}
621
622
623#[inline(never)]
624fn sort_dedup<T: Ord>(list: &mut Vec<T>) {
625    list.dedup();
626    list.sort();
627    list.dedup();
628}
629
630trait PerKeyCompute<'a, C1, C2, C3, V>
631where
632    C1: Cursor,
633    C2: for<'b> Cursor<Key<'a> = C1::Key<'a>, ValOwn = V, Time = C1::Time>,
634    C3: Cursor<Key<'a> = C1::Key<'a>, Val<'a> = C1::Val<'a>, Time = C1::Time, Diff = C1::Diff>,
635    V: Clone + Ord,
636{
637    fn new() -> Self;
638    fn compute<L>(
639        &mut self,
640        key: C1::Key<'a>,
641        source_cursor: (&mut C1, &'a C1::Storage),
642        output_cursor: (&mut C2, &'a C2::Storage),
643        batch_cursor: (&mut C3, &'a C3::Storage),
644        times: &mut Vec<C1::Time>,
645        logic: &mut L,
646        upper_limit: &Antichain<C1::Time>,
647        outputs: &mut [(C2::Time, Vec<(V, C2::Time, C2::Diff)>)],
648        new_interesting: &mut Vec<C1::Time>) -> (usize, usize)
649    where
650        L: FnMut(
651            C1::Key<'a>,
652            &[(C1::Val<'a>, C1::Diff)],
653            &mut Vec<(V, C2::Diff)>,
654            &mut Vec<(V, C2::Diff)>,
655        );
656}
657
658
659/// Implementation based on replaying historical and new updates together.
660mod history_replay {
661
662    use timely::progress::Antichain;
663    use timely::PartialOrder;
664
665    use crate::lattice::Lattice;
666    use crate::trace::Cursor;
667    use crate::operators::ValueHistory;
668
669    use super::{PerKeyCompute, sort_dedup};
670
671    /// The `HistoryReplayer` is a compute strategy based on moving through existing inputs, interesting times, etc in
672    /// time order, maintaining consolidated representations of updates with respect to future interesting times.
673    pub struct HistoryReplayer<'a, C1, C2, C3, V>
674    where
675        C1: Cursor,
676        C2: Cursor<Key<'a> = C1::Key<'a>, Time = C1::Time>,
677        C3: Cursor<Key<'a> = C1::Key<'a>, Val<'a> = C1::Val<'a>, Time = C1::Time, Diff = C1::Diff>,
678        V: Clone + Ord,
679    {
680        input_history: ValueHistory<'a, C1>,
681        output_history: ValueHistory<'a, C2>,
682        batch_history: ValueHistory<'a, C3>,
683        input_buffer: Vec<(C1::Val<'a>, C1::Diff)>,
684        output_buffer: Vec<(V, C2::Diff)>,
685        update_buffer: Vec<(V, C2::Diff)>,
686        output_produced: Vec<((V, C2::Time), C2::Diff)>,
687        synth_times: Vec<C1::Time>,
688        meets: Vec<C1::Time>,
689        times_current: Vec<C1::Time>,
690        temporary: Vec<C1::Time>,
691    }
692
693    impl<'a, C1, C2, C3, V> PerKeyCompute<'a, C1, C2, C3, V> for HistoryReplayer<'a, C1, C2, C3, V>
694    where
695        C1: Cursor,
696        C2: for<'b> Cursor<Key<'a> = C1::Key<'a>, ValOwn = V, Time = C1::Time>,
697        C3: Cursor<Key<'a> = C1::Key<'a>, Val<'a> = C1::Val<'a>, Time = C1::Time, Diff = C1::Diff>,
698        V: Clone + Ord,
699    {
700        fn new() -> Self {
701            HistoryReplayer {
702                input_history: ValueHistory::new(),
703                output_history: ValueHistory::new(),
704                batch_history: ValueHistory::new(),
705                input_buffer: Vec::new(),
706                output_buffer: Vec::new(),
707                update_buffer: Vec::new(),
708                output_produced: Vec::new(),
709                synth_times: Vec::new(),
710                meets: Vec::new(),
711                times_current: Vec::new(),
712                temporary: Vec::new(),
713            }
714        }
715        #[inline(never)]
716        fn compute<L>(
717            &mut self,
718            key: C1::Key<'a>,
719            (source_cursor, source_storage): (&mut C1, &'a C1::Storage),
720            (output_cursor, output_storage): (&mut C2, &'a C2::Storage),
721            (batch_cursor, batch_storage): (&mut C3, &'a C3::Storage),
722            times: &mut Vec<C1::Time>,
723            logic: &mut L,
724            upper_limit: &Antichain<C1::Time>,
725            outputs: &mut [(C2::Time, Vec<(V, C2::Time, C2::Diff)>)],
726            new_interesting: &mut Vec<C1::Time>) -> (usize, usize)
727        where
728            L: FnMut(
729                C1::Key<'a>,
730                &[(C1::Val<'a>, C1::Diff)],
731                &mut Vec<(V, C2::Diff)>,
732                &mut Vec<(V, C2::Diff)>,
733            )
734        {
735
736            // The work we need to perform is at times defined principally by the contents of `batch_cursor`
737            // and `times`, respectively "new work we just received" and "old times we were warned about".
738            //
739            // Our first step is to identify these times, so that we can use them to restrict the amount of
740            // information we need to recover from `input` and `output`; as all times of interest will have
741            // some time from `batch_cursor` or `times`, we can compute their meet and advance all other
742            // loaded times by performing the lattice `join` with this value.
743
744            // Load the batch contents.
745            let mut batch_replay = self.batch_history.replay_key(batch_cursor, batch_storage, key, |time| C3::owned_time(time));
746
747            // We determine the meet of times we must reconsider (those from `batch` and `times`). This meet
748            // can be used to advance other historical times, which may consolidate their representation. As
749            // a first step, we determine the meets of each *suffix* of `times`, which we will use as we play
750            // history forward.
751
752            self.meets.clear();
753            self.meets.extend(times.iter().cloned());
754            for index in (1 .. self.meets.len()).rev() {
755                self.meets[index-1] = self.meets[index-1].meet(&self.meets[index]);
756            }
757
758            // Determine the meet of times in `batch` and `times`.
759            let mut meet = None;
760            update_meet(&mut meet, self.meets.get(0));
761            update_meet(&mut meet, batch_replay.meet());
762            // if let Some(time) = self.meets.get(0) {
763            //     meet = match meet {
764            //         None => Some(self.meets[0].clone()),
765            //         Some(x) => Some(x.meet(&self.meets[0])),
766            //     };
767            // }
768            // if let Some(time) = batch_replay.meet() {
769            //     meet = match meet {
770            //         None => Some(time.clone()),
771            //         Some(x) => Some(x.meet(&time)),
772            //     };
773            // }
774
775            // Having determined the meet, we can load the input and output histories, where we
776            // advance all times by joining them with `meet`. The resulting times are more compact
777            // and guaranteed to accumulate identically for times greater or equal to `meet`.
778
779            // Load the input and output histories.
780            let mut input_replay = if let Some(meet) = meet.as_ref() {
781                self.input_history.replay_key(source_cursor, source_storage, key, |time| {
782                    let mut time = C1::owned_time(time);
783                    time.join_assign(meet);
784                    time
785                })
786            }
787            else {
788                self.input_history.replay_key(source_cursor, source_storage, key, |time| C1::owned_time(time))
789            };
790            let mut output_replay = if let Some(meet) = meet.as_ref() {
791                self.output_history.replay_key(output_cursor, output_storage, key, |time| {
792                    let mut time = C2::owned_time(time);
793                    time.join_assign(meet);
794                    time
795                })
796            }
797            else {
798                self.output_history.replay_key(output_cursor, output_storage, key, |time| C2::owned_time(time))
799            };
800
801            self.synth_times.clear();
802            self.times_current.clear();
803            self.output_produced.clear();
804
805            // The frontier of times we may still consider.
806            // Derived from frontiers of our update histories, supplied times, and synthetic times.
807
808            let mut times_slice = &times[..];
809            let mut meets_slice = &self.meets[..];
810
811            let mut compute_counter = 0;
812            let mut output_counter = 0;
813
814            // We have candidate times from `batch` and `times`, as well as times identified by either
815            // `input` or `output`. Finally, we may have synthetic times produced as the join of times
816            // we consider in the course of evaluation. As long as any of these times exist, we need to
817            // keep examining times.
818            while let Some(next_time) = [   batch_replay.time(),
819                                            times_slice.first(),
820                                            input_replay.time(),
821                                            output_replay.time(),
822                                            self.synth_times.last(),
823                                        ].iter().cloned().flatten().min().cloned() {
824
825                // Advance input and output history replayers. This marks applicable updates as active.
826                input_replay.step_while_time_is(&next_time);
827                output_replay.step_while_time_is(&next_time);
828
829                // One of our goals is to determine if `next_time` is "interesting", meaning whether we
830                // have any evidence that we should re-evaluate the user logic at this time. For a time
831                // to be "interesting" it would need to be the join of times that include either a time
832                // from `batch`, `times`, or `synth`. Neither `input` nor `output` times are sufficient.
833
834                // Advance batch history, and capture whether an update exists at `next_time`.
835                let mut interesting = batch_replay.step_while_time_is(&next_time);
836                if interesting {
837                    if let Some(meet) = meet.as_ref() {
838                        batch_replay.advance_buffer_by(meet);
839                    }
840                }
841
842                // advance both `synth_times` and `times_slice`, marking this time interesting if in either.
843                while self.synth_times.last() == Some(&next_time) {
844                    // We don't know enough about `next_time` to avoid putting it in to `times_current`.
845                    // TODO: If we knew that the time derived from a canceled batch update, we could remove the time.
846                    self.times_current.push(self.synth_times.pop().expect("failed to pop from synth_times")); // <-- TODO: this could be a min-heap.
847                    interesting = true;
848                }
849                while times_slice.first() == Some(&next_time) {
850                    // We know nothing about why we were warned about `next_time`, and must include it to scare future times.
851                    self.times_current.push(times_slice[0].clone());
852                    times_slice = &times_slice[1..];
853                    meets_slice = &meets_slice[1..];
854                    interesting = true;
855                }
856
857                // Times could also be interesting if an interesting time is less than them, as they would join
858                // and become the time itself. They may not equal the current time because whatever frontier we
859                // are tracking may not have advanced far enough.
860                // TODO: `batch_history` may or may not be super compact at this point, and so this check might
861                //       yield false positives if not sufficiently compact. Maybe we should into this and see.
862                interesting = interesting || batch_replay.buffer().iter().any(|&((_, ref t),_)| t.less_equal(&next_time));
863                interesting = interesting || self.times_current.iter().any(|t| t.less_equal(&next_time));
864
865                // We should only process times that are not in advance of `upper_limit`.
866                //
867                // We have no particular guarantee that known times will not be in advance of `upper_limit`.
868                // We may have the guarantee that synthetic times will not be, as we test against the limit
869                // before we add the time to `synth_times`.
870                if !upper_limit.less_equal(&next_time) {
871
872                    // We should re-evaluate the computation if this is an interesting time.
873                    // If the time is uninteresting (and our logic is sound) it is not possible for there to be
874                    // output produced. This sounds like a good test to have for debug builds!
875                    if interesting {
876
877                        compute_counter += 1;
878
879                        // Assemble the input collection at `next_time`. (`self.input_buffer` cleared just after use).
880                        debug_assert!(self.input_buffer.is_empty());
881                        meet.as_ref().map(|meet| input_replay.advance_buffer_by(meet));
882                        for &((value, ref time), ref diff) in input_replay.buffer().iter() {
883                            if time.less_equal(&next_time) {
884                                self.input_buffer.push((value, diff.clone()));
885                            }
886                            else {
887                                self.temporary.push(next_time.join(time));
888                            }
889                        }
890                        for &((value, ref time), ref diff) in batch_replay.buffer().iter() {
891                            if time.less_equal(&next_time) {
892                                self.input_buffer.push((value, diff.clone()));
893                            }
894                            else {
895                                self.temporary.push(next_time.join(time));
896                            }
897                        }
898                        crate::consolidation::consolidate(&mut self.input_buffer);
899
900                        meet.as_ref().map(|meet| output_replay.advance_buffer_by(meet));
901                        for &((value, ref time), ref diff) in output_replay.buffer().iter() {
902                            if time.less_equal(&next_time) {
903                                self.output_buffer.push((C2::owned_val(value), diff.clone()));
904                            }
905                            else {
906                                self.temporary.push(next_time.join(time));
907                            }
908                        }
909                        for &((ref value, ref time), ref diff) in self.output_produced.iter() {
910                            if time.less_equal(&next_time) {
911                                self.output_buffer.push(((*value).to_owned(), diff.clone()));
912                            }
913                            else {
914                                self.temporary.push(next_time.join(time));
915                            }
916                        }
917                        crate::consolidation::consolidate(&mut self.output_buffer);
918
919                        // Apply user logic if non-empty input and see what happens!
920                        if !self.input_buffer.is_empty() || !self.output_buffer.is_empty() {
921                            logic(key, &self.input_buffer[..], &mut self.output_buffer, &mut self.update_buffer);
922                            self.input_buffer.clear();
923                            self.output_buffer.clear();
924                        }
925
926                        // output_replay.advance_buffer_by(&meet);
927                        // for &((ref value, ref time), diff) in output_replay.buffer().iter() {
928                        //     if time.less_equal(&next_time) {
929                        //         self.output_buffer.push(((*value).clone(), -diff));
930                        //     }
931                        //     else {
932                        //         self.temporary.push(next_time.join(time));
933                        //     }
934                        // }
935                        // for &((ref value, ref time), diff) in self.output_produced.iter() {
936                        //     if time.less_equal(&next_time) {
937                        //         self.output_buffer.push(((*value).clone(), -diff));
938                        //     }
939                        //     else {
940                        //         self.temporary.push(next_time.join(&time));
941                        //     }
942                        // }
943
944                        // Having subtracted output updates from user output, consolidate the results to determine
945                        // if there is anything worth reporting. Note: this also orders the results by value, so
946                        // that could make the above merging plan even easier.
947                        crate::consolidation::consolidate(&mut self.update_buffer);
948
949                        // Stash produced updates into both capability-indexed buffers and `output_produced`.
950                        // The two locations are important, in that we will compact `output_produced` as we move
951                        // through times, but we cannot compact the output buffers because we need their actual
952                        // times.
953                        if !self.update_buffer.is_empty() {
954
955                            output_counter += 1;
956
957                            // We *should* be able to find a capability for `next_time`. Any thing else would
958                            // indicate a logical error somewhere along the way; either we release a capability
959                            // we should have kept, or we have computed the output incorrectly (or both!)
960                            let idx = outputs.iter().rev().position(|(time, _)| time.less_equal(&next_time));
961                            let idx = outputs.len() - idx.expect("failed to find index") - 1;
962                            for (val, diff) in self.update_buffer.drain(..) {
963                                self.output_produced.push(((val.clone(), next_time.clone()), diff.clone()));
964                                outputs[idx].1.push((val, next_time.clone(), diff));
965                            }
966
967                            // Advance times in `self.output_produced` and consolidate the representation.
968                            // NOTE: We only do this when we add records; it could be that there are situations
969                            //       where we want to consolidate even without changes (because an initially
970                            //       large collection can now be collapsed).
971                            if let Some(meet) = meet.as_ref() {
972                                for entry in &mut self.output_produced {
973                                    (entry.0).1 = (entry.0).1.join(meet);
974                                }
975                            }
976                            crate::consolidation::consolidate(&mut self.output_produced);
977                        }
978                    }
979
980                    // Determine synthetic interesting times.
981                    //
982                    // Synthetic interesting times are produced differently for interesting and uninteresting
983                    // times. An uninteresting time must join with an interesting time to become interesting,
984                    // which means joins with `self.batch_history` and  `self.times_current`. I think we can
985                    // skip `self.synth_times` as we haven't gotten to them yet, but we will and they will be
986                    // joined against everything.
987
988                    // Any time, even uninteresting times, must be joined with the current accumulation of
989                    // batch times as well as the current accumulation of `times_current`.
990                    for &((_, ref time), _) in batch_replay.buffer().iter() {
991                        if !time.less_equal(&next_time) {
992                            self.temporary.push(time.join(&next_time));
993                        }
994                    }
995                    for time in self.times_current.iter() {
996                        if !time.less_equal(&next_time) {
997                            self.temporary.push(time.join(&next_time));
998                        }
999                    }
1000
1001                    sort_dedup(&mut self.temporary);
1002
1003                    // Introduce synthetic times, and re-organize if we add any.
1004                    let synth_len = self.synth_times.len();
1005                    for time in self.temporary.drain(..) {
1006                        // We can either service `join` now, or must delay for the future.
1007                        if upper_limit.less_equal(&time) {
1008                            debug_assert!(outputs.iter().any(|(t,_)| t.less_equal(&time)));
1009                            new_interesting.push(time);
1010                        }
1011                        else {
1012                            self.synth_times.push(time);
1013                        }
1014                    }
1015                    if self.synth_times.len() > synth_len {
1016                        self.synth_times.sort_by(|x,y| y.cmp(x));
1017                        self.synth_times.dedup();
1018                    }
1019                }
1020                else if interesting {
1021                    // We cannot process `next_time` now, and must delay it.
1022                    //
1023                    // I think we are probably only here because of an uninteresting time declared interesting,
1024                    // as initial interesting times are filtered to be in interval, and synthetic times are also
1025                    // filtered before introducing them to `self.synth_times`.
1026                    new_interesting.push(next_time.clone());
1027                    debug_assert!(outputs.iter().any(|(t,_)| t.less_equal(&next_time)))
1028                }
1029
1030
1031                // Update `meet` to track the meet of each source of times.
1032                meet = None;//T::maximum();
1033                update_meet(&mut meet, batch_replay.meet());
1034                update_meet(&mut meet, input_replay.meet());
1035                update_meet(&mut meet, output_replay.meet());
1036                for time in self.synth_times.iter() { update_meet(&mut meet, Some(time)); }
1037                // if let Some(time) = batch_replay.meet() { meet = meet.meet(time); }
1038                // if let Some(time) = input_replay.meet() { meet = meet.meet(time); }
1039                // if let Some(time) = output_replay.meet() { meet = meet.meet(time); }
1040                // for time in self.synth_times.iter() { meet = meet.meet(time); }
1041                update_meet(&mut meet, meets_slice.first());
1042                // if let Some(time) = meets_slice.first() { meet = meet.meet(time); }
1043
1044                // Update `times_current` by the frontier.
1045                if let Some(meet) = meet.as_ref() {
1046                    for time in self.times_current.iter_mut() {
1047                        *time = time.join(meet);
1048                    }
1049                }
1050
1051                sort_dedup(&mut self.times_current);
1052            }
1053
1054            // Normalize the representation of `new_interesting`, deduplicating and ordering.
1055            sort_dedup(new_interesting);
1056
1057            (compute_counter, output_counter)
1058        }
1059    }
1060
1061    /// Updates an optional meet by an optional time.
1062    fn update_meet<T: Lattice+Clone>(meet: &mut Option<T>, other: Option<&T>) {
1063        if let Some(time) = other {
1064            if let Some(meet) = meet.as_mut() {
1065                *meet = meet.meet(time);
1066            }
1067            if meet.is_none() {
1068                *meet = Some(time.clone());
1069            }
1070        }
1071    }
1072}