differential_dataflow/algorithms/
identifiers.rs

1//! Assign unique identifiers to records.
2
3use timely::dataflow::Scope;
4
5use crate::{Collection, ExchangeData, Hashable};
6use crate::lattice::Lattice;
7use crate::operators::*;
8use crate::difference::Abelian;
9
10/// Assign unique identifiers to elements of a collection.
11pub trait Identifiers<G: Scope, D: ExchangeData, R: ExchangeData+Abelian> {
12    /// Assign unique identifiers to elements of a collection.
13    ///
14    /// # Example
15    /// ```
16    /// use differential_dataflow::input::Input;
17    /// use differential_dataflow::algorithms::identifiers::Identifiers;
18    /// use differential_dataflow::operators::Threshold;
19    ///
20    /// ::timely::example(|scope| {
21    ///
22    ///     let identifiers =
23    ///     scope.new_collection_from(1 .. 10).1
24    ///          .identifiers()
25    ///          // assert no conflicts
26    ///          .map(|(data, id)| id)
27    ///          .threshold(|_id,cnt| if cnt > &1 { *cnt } else { 0 })
28    ///          .assert_empty();
29    /// });
30    /// ```
31    fn identifiers(&self) -> Collection<G, (D, u64), R>;
32}
33
34impl<G, D, R> Identifiers<G, D, R> for Collection<G, D, R>
35where
36    G: Scope<Timestamp: Lattice>,
37    D: ExchangeData + ::std::hash::Hash,
38    R: ExchangeData + Abelian,
39{
40    fn identifiers(&self) -> Collection<G, (D, u64), R> {
41
42        // The design here is that we iteratively develop a collection
43        // of pairs (round, record), where each pair is a proposal that
44        // the hash for record should be (round, record).hashed().
45        //
46        // Iteratively, any colliding pairs establish a winner (the one
47        // with the lower round, breaking ties by record), and indicate
48        // that the losers should increment their round and try again.
49        //
50        // Non-obviously, this happens via a `reduce` operator that yields
51        // additions and subtractions of losers, rather than reproducing
52        // the winners. This is done under the premise that losers are
53        // very rare, and maintaining winners in both the input and output
54        // of `reduce` is an unnecessary duplication.
55
56        use crate::collection::AsCollection;
57
58        let init = self.map(|record| (0, record));
59        timely::dataflow::operators::generic::operator::empty(&init.scope())
60            .as_collection()
61            .iterate(|diff|
62                init.enter(&diff.scope())
63                    .concat(diff)
64                    .map(|pair| (pair.hashed(), pair))
65                    .reduce(|_hash, input, output| {
66                        // keep round-positive records as changes.
67                        let ((round, record), count) = &input[0];
68                        if *round > 0 {
69                            let mut neg_count = count.clone();
70                            neg_count.negate();
71                            output.push(((0, record.clone()), neg_count));
72                            output.push(((*round, record.clone()), count.clone()));
73                        }
74                        // if any losers, increment their rounds.
75                        for ((round, record), count) in input[1..].iter() {
76                            let mut neg_count = count.clone();
77                            neg_count.negate();
78                            output.push(((0, record.clone()), neg_count));
79                            output.push(((*round+1, record.clone()), count.clone()));
80                        }
81                    })
82                    .map(|(_hash, pair)| pair)
83            )
84            .concat(&init)
85            .map(|pair| { let hash = pair.hashed(); (pair.1, hash) })
86    }
87}
88
89#[cfg(test)]
90mod tests {
91
92    #[test]
93    fn are_unique() {
94
95        // It is hard to test the above method, because we would want
96        // to exercise the case with hash collisions. Instead, we test
97        // a version with a crippled hash function to see that even if
98        // there are collisions, everyone gets a unique identifier.
99
100        use crate::input::Input;
101        use crate::operators::{Threshold, Reduce};
102        use crate::operators::iterate::Iterate;
103
104        ::timely::example(|scope| {
105
106            let input = scope.new_collection_from(1 .. 4).1;
107
108            use crate::collection::AsCollection;
109
110            let init = input.map(|record| (0, record));
111            timely::dataflow::operators::generic::operator::empty(&init.scope())
112                .as_collection()
113                .iterate(|diff|
114                    init.enter(&diff.scope())
115                        .concat(&diff)
116                        .map(|(round, num)| ((round + num) / 10, (round, num)))
117                        .reduce(|_hash, input, output| {
118                            println!("Input: {:?}", input);
119                            // keep round-positive records as changes.
120                            let ((round, record), count) = &input[0];
121                            if *round > 0 {
122                                output.push(((0, record.clone()), -*count));
123                                output.push(((*round, record.clone()), *count));
124                            }
125                            // if any losers, increment their rounds.
126                            for ((round, record), count) in input[1..].iter() {
127                                output.push(((0, record.clone()), -*count));
128                                output.push(((*round+1, record.clone()), *count));
129                            }
130                        })
131                        .inspect(|x| println!("{:?}", x))
132                        .map(|(_hash, pair)| pair)
133                )
134                .concat(&init)
135                .map(|(round, num)| { (num, (round + num) / 10) })
136                .map(|(_data, id)| id)
137                .threshold(|_id,cnt| if cnt > &1 { *cnt } else { 0 })
138                .assert_empty();
139        });
140    }
141}