qrlew 0.3.2

Sarus Qrlew Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! # Methods to transform `Relation`s into differentially private ones
//!
//! This is experimental and little tested yet.
//!

pub mod mechanisms;
pub mod protect_grouping_keys;

use itertools::Itertools;

use crate::{
    builder::With,
    data_type::DataTyped,
    expr::{self, aggregate, AggregateColumn, Expr},
    protection::{self, PEPRelation},
    relation::{field::Field, transforms, Map, Reduce, Relation, Variant as _},
    DataType, Ready,
};
use std::collections::{HashMap, HashSet};
use std::ops::Deref;
use std::{cmp, error, fmt, result};

#[derive(Debug, PartialEq)]
pub enum Error {
    InvalidRelation(String),
    UnsafeGroups(String),
    Other(String),
}

impl Error {
    pub fn invalid_relation(relation: impl fmt::Display) -> Error {
        Error::InvalidRelation(format!("{relation} is invalid"))
    }
    pub fn unsafe_groups(groups: impl fmt::Display) -> Error {
        Error::UnsafeGroups(format!("{groups} should be public"))
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::InvalidRelation(relation) => writeln!(f, "{relation} invalid."),
            Error::UnsafeGroups(groups) => writeln!(f, "{groups} should be public."),
            Error::Other(err) => writeln!(f, "{}", err),
        }
    }
}

impl From<expr::Error> for Error {
    fn from(err: expr::Error) -> Self {
        Error::Other(err.to_string())
    }
}
impl From<transforms::Error> for Error {
    fn from(err: transforms::Error) -> Self {
        Error::Other(err.to_string())
    }
}
impl From<protection::Error> for Error {
    fn from(err: protection::Error) -> Self {
        Error::Other(err.to_string())
    }
}

impl error::Error for Error {}
pub type Result<T> = result::Result<T, Error>;

/// A DP Relation
#[derive(Clone, Debug)]
pub struct DPRelation(pub Relation);

impl From<DPRelation> for Relation {
    fn from(value: DPRelation) -> Self {
        value.0
    }
}

impl Deref for DPRelation {
    type Target = Relation;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Field {
    pub fn clipping_value(self, multiplicity: i64) -> f64 {
        match self.data_type() {
            DataType::Float(f) => {
                let min = f.min().unwrap().abs();
                let max = f.max().unwrap().abs();
                (min + max + (min - max).abs()) / 2. * multiplicity as f64
            }
            DataType::Integer(i) => {
                let min = i.min().unwrap().abs();
                let max = i.max().unwrap().abs();
                (cmp::max(min, max) * multiplicity) as f64
            }
            _ => todo!(),
        }
    }
}

impl PEPRelation {
    // /// Compile a protected Relation into DP
    // pub fn dp_compile_sums(self, epsilon: f64, delta: f64) -> Result<DPRelation> {// Return a DP relation
    //     let protected_entity_id = self.protected_entity_id().to_string();
    //     let protected_entity_weight = self.protected_entity_weight().to_string();
    //     if let PEPRelation(Relation::Reduce(reduce)) = self {
    //         reduce.dp_compile_sums(&protected_entity_id, &protected_entity_weight, epsilon, delta)
    //     } else {
    //         Err(Error::invalid_relation(self.0))
    //     }
    // }

    /// Compile a protected Relation into DP
    pub fn dp_compile(self, epsilon: f64, delta: f64) -> Result<DPRelation> {
        // Return a DP relation
        let protected_entity_id = self.protected_entity_id().to_string();
        let protected_entity_weight = self.protected_entity_weight().to_string();
        match Relation::from(self) {
            Relation::Map(map) => {
                let dp_input: Relation = PEPRelation::try_from(map.input().clone())?
                    .dp_compile(epsilon, delta)?
                    .into();
                Ok(DPRelation(
                    Map::builder()
                        .filter_fields_with(map, |f| {
                            f != protected_entity_id.as_str()
                                && f != protected_entity_weight.as_str()
                        })
                        .input(dp_input)
                        .build(),
                ))
            }
            Relation::Reduce(reduce) => reduce.dp_compile(
                &protected_entity_id,
                &protected_entity_weight,
                epsilon,
                delta,
            ),
            relation => Err(Error::invalid_relation(relation)),
        }
    }
}

/* Reduce
 */
impl Reduce {
    /// DP compile the sums
    fn dp_compile_sums(
        self,
        protected_entity_id: &str,
        protected_entity_weight: &str,
        epsilon: f64,
        delta: f64,
    ) -> Result<DPRelation> {
        // Collect groups
        let mut input_entities: Option<&str> = None;
        let mut input_groups: HashSet<&str> = self.group_by_names().into_iter().collect();
        let mut input_values_bound: Vec<(&str, f64)> = vec![];
        let mut names: HashMap<&str, &str> = HashMap::new();
        // Collect names, sums and bounds
        for (name, aggregate) in self.named_aggregates() {
            // Get value name
            let input_name = aggregate.column_name()?;
            names.insert(input_name, name);
            if name == protected_entity_id {
                // remove pe group
                input_groups.remove(&input_name);
                input_entities = Some(input_name);
            } else if aggregate.aggregate() == &aggregate::Aggregate::Sum
                && name != protected_entity_weight
            {
                // add aggregate
                let input_data_type = self.input().schema()[input_name].data_type();
                let absolute_bound = input_data_type.absolute_upper_bound().unwrap_or(1.0);
                input_values_bound.push((input_name, absolute_bound));
            }
        }
        // Check that groups are public
        if !input_groups
            .iter()
            .all(|e| self.input().schema()[*e].all_values())
        {
            return Err(Error::unsafe_groups(
                input_groups
                    .iter()
                    .map(|e| self.input().schema()[*e].data_type())
                    .join(", "),
            ));
        };

        // Clip the relation
        let clipped_relation = self.input().clone().l2_clipped_sums(
            input_entities.unwrap(),
            input_groups.into_iter().collect(),
            input_values_bound.iter().cloned().collect(),
        );
        let noise_multiplier = 1.; // TODO set this properly
        let dp_clipped_relation = clipped_relation.add_gaussian_noise(
            input_values_bound
                .into_iter()
                .map(|(name, bound)| (name, noise_multiplier * bound))
                .collect(),
        );
        let renamed_dp_clipped_relation =
            dp_clipped_relation.rename_fields(|n, e| names.get(n).unwrap_or(&n).to_string());
        Ok(DPRelation(renamed_dp_clipped_relation))
    }

    /// Rewrite aggregations as sums and compile sums
    pub fn dp_compile(
        self,
        protected_entity_id: &str,
        protected_entity_weight: &str,
        epsilon: f64,
        delta: f64,
    ) -> Result<DPRelation> {
        let mut output = Map::builder();
        let mut sums = Reduce::builder();
        // Add aggregate colums
        for (name, aggregate) in self.named_aggregates().into_iter() {
            match aggregate.aggregate() {
                aggregate::Aggregate::First => {
                    sums = sums.with((
                        aggregate.column_name()?,
                        AggregateColumn::col(aggregate.column_name()?),
                    ));
                    if name != protected_entity_id {
                        output = output.with((name, Expr::col(aggregate.column_name()?)));
                    }
                }
                aggregate::Aggregate::Mean => {
                    let sum_col = &format!("_SUM_{}", aggregate.column_name()?);
                    let count_col = &format!("_COUNT_{}", aggregate.column_name()?);
                    sums = sums
                        .with((count_col, Expr::sum(Expr::val(1.))))
                        .with((sum_col, Expr::sum(Expr::col(aggregate.column_name()?))));
                    output = output.with((
                        name,
                        Expr::divide(
                            Expr::col(sum_col),
                            Expr::greatest(Expr::val(1.), Expr::col(count_col)),
                        ),
                    ))
                }
                aggregate::Aggregate::Count => {
                    let count_col = &format!("_COUNT_{}", aggregate.column_name()?);
                    sums = sums.with((count_col, Expr::sum(Expr::val(1.))));
                    output = output.with((name, Expr::col(count_col)));
                }
                aggregate::Aggregate::Sum
                    if aggregate.column_name()? != protected_entity_weight =>
                {
                    let sum_col = &format!("_SUM_{}", aggregate.column_name()?);
                    sums = sums.with((sum_col, Expr::sum(Expr::col(aggregate.column_name()?))));
                    output = output.with((name, Expr::col(sum_col)));
                }
                aggregate::Aggregate::Std => todo!(),
                aggregate::Aggregate::Var => todo!(),
                _ => (),
            }
        }
        sums = sums.group_by_iter(self.group_by().iter().cloned());
        let sums: Reduce = sums.input(self.input().clone()).build();
        let dp_sums: Relation = sums
            .dp_compile_sums(protected_entity_id, protected_entity_weight, epsilon, delta)?
            .into();
        Ok(DPRelation(output.input(dp_sums).build()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        ast,
        builder::{Ready, With},
        display::Dot,
        io::{postgresql, Database},
        relation::Variant as _,
        sql::parse,
        Relation,
    };
    use colored::Colorize;
    use itertools::Itertools;

    #[test]
    fn test_table_with_noise() {
        let mut database = postgresql::test_database();
        let relations = database.relations();
        // CReate a relation to add noise to
        let relation = Relation::try_from(
            parse("SELECT sum(price) FROM item_table GROUP BY order_id")
                .unwrap()
                .with(&relations),
        )
        .unwrap();
        println!("Schema = {}", relation.schema());
        relation.display_dot().unwrap();
        // Add noise directly
        for row in database
            .query("SELECT random(), sum(price) FROM item_table GROUP BY order_id")
            .unwrap()
        {
            println!("Row = {row}");
        }
    }

    #[test]
    fn test_dp_compile() {
        let mut database = postgresql::test_database();
        let relations = database.relations();

        let query = parse(
            "SELECT price
        FROM item_table WHERE order_id IN (1,2,3,4,5,6,7,8,9,10)",
        )
        .unwrap();
        let relation = Relation::try_from(query.with(&relations)).unwrap();
        relation.display_dot().unwrap();

        let query = parse(
            "SELECT sum(price) AS sum_price,
        count(price) AS count_price,
        avg(price) AS mean_price
        FROM item_table WHERE order_id IN (1,2,3,4,5,6,7,8,9,10) GROUP BY order_id",
        )
        .unwrap();
        let relation = Relation::try_from(query.with(&relations)).unwrap();
        relation.display_dot().unwrap();

        let pep_relation = relation.force_protect_from_field_paths(
            &relations,
            vec![
                (
                    "item_table",
                    vec![
                        ("order_id", "order_table", "id"),
                        ("user_id", "user_table", "id"),
                    ],
                    "name",
                ),
                ("order_table", vec![("user_id", "user_table", "id")], "name"),
                ("user_table", vec![], "name"),
            ],
        );
        pep_relation.display_dot().unwrap();

        let epsilon = 1.;
        let delta = 1e-3;
        let dp_relation = pep_relation.dp_compile(epsilon, delta).unwrap();
        dp_relation.display_dot().unwrap();
        let dp_query = ast::Query::from(dp_relation.deref());
        for row in database.query(&dp_query.to_string()).unwrap() {
            println!("{row}");
        }
    }

    #[test]
    fn test_dp_compile_simple() {
        let mut database = postgresql::test_database();
        let relations = database.relations();

        // GROUPING col in the SELECT clause
        let str_query = "SELECT z, sum(x) AS sum_x FROM table_2 GROUP BY z";
        let query = parse(str_query).unwrap();
        let relation = Relation::try_from(query.with(&relations)).unwrap();

        let pep_relation =
            relation.force_protect_from_field_paths(&relations, vec![("table_2", vec![], "y")]);

        let dp_relation = pep_relation.dp_compile(1., 1e-3).unwrap();
        dp_relation.display_dot().unwrap();

        assert_eq!(
            dp_relation.data_type()["z"],
            DataType::text_values(["Foo".into(), "Bar".into()])
        );
        assert!(matches!(
            dp_relation.data_type()["sum_x"],
            DataType::Float(_)
        ));
        assert_eq!(dp_relation.schema().len(), 2);
        let dp_query = ast::Query::from(dp_relation.deref());
        database.query(&dp_query.to_string()).unwrap();

        // GROUPING col NOT in the SELECT clause
        let str_query = "SELECT sum(x) AS sum_x FROM table_2 GROUP BY z";
        let query = parse(str_query).unwrap();
        let relation = Relation::try_from(query.with(&relations)).unwrap();

        let pep_relation =
            relation.force_protect_from_field_paths(&relations, vec![("table_2", vec![], "y")]);

        let dp_relation = pep_relation.dp_compile(1., 1e-3).unwrap();
        dp_relation.display_dot().unwrap();

        assert_eq!(dp_relation.schema().len(), 1);
        assert!(matches!(
            dp_relation.data_type()["sum_x"],
            DataType::Float(_)
        ));
        let dp_query = ast::Query::from(dp_relation.deref());
        database.query(&dp_query.to_string()).unwrap();
    }
}