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