-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
utils.rs
459 lines (405 loc) · 15.5 KB
/
utils.rs
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
use polars_core::prelude::*;
use super::keys::*;
use crate::prelude::*;
fn combine_by_and(left: Node, right: Node, arena: &mut Arena<AExpr>) -> Node {
arena.add(AExpr::BinaryExpr {
left,
op: Operator::And,
right,
})
}
/// Don't overwrite predicates but combine them.
pub(super) fn insert_and_combine_predicate(
acc_predicates: &mut PlHashMap<Arc<str>, ExprIR>,
predicate: &ExprIR,
arena: &mut Arena<AExpr>,
) {
let name = predicate_to_key(predicate.node(), arena);
acc_predicates
.entry(name)
.and_modify(|existing_predicate| {
let node = combine_by_and(predicate.node(), existing_predicate.node(), arena);
existing_predicate.set_node(node)
})
.or_insert_with(|| predicate.clone());
}
pub(super) fn temporary_unique_key(acc_predicates: &PlHashMap<Arc<str>, ExprIR>) -> String {
let mut out_key = '\u{1D17A}'.to_string();
let mut existing_keys = acc_predicates.keys();
while acc_predicates.contains_key(&*out_key) {
out_key.push_str(existing_keys.next().unwrap());
}
out_key
}
pub(super) fn combine_predicates<I>(iter: I, arena: &mut Arena<AExpr>) -> ExprIR
where
I: Iterator<Item = ExprIR>,
{
let mut single_pred = None;
for e in iter {
single_pred = match single_pred {
None => Some(e.node()),
Some(left) => Some(arena.add(AExpr::BinaryExpr {
left,
op: Operator::And,
right: e.node(),
})),
};
}
single_pred
.map(|node| ExprIR::from_node(node, arena))
.expect("an empty iterator was passed")
}
pub(super) fn predicate_at_scan(
acc_predicates: PlHashMap<Arc<str>, ExprIR>,
predicate: Option<ExprIR>,
expr_arena: &mut Arena<AExpr>,
) -> Option<ExprIR> {
if !acc_predicates.is_empty() {
let mut new_predicate = combine_predicates(acc_predicates.into_values(), expr_arena);
if let Some(pred) = predicate {
new_predicate.set_node(combine_by_and(
new_predicate.node(),
pred.node(),
expr_arena,
));
}
Some(new_predicate)
} else {
None
}
}
fn shifts_elements(node: Node, expr_arena: &Arena<AExpr>) -> bool {
let matches = |e: &AExpr| {
matches!(
e,
AExpr::Function {
function: FunctionExpr::Shift | FunctionExpr::ShiftAndFill,
..
}
)
};
has_aexpr(node, expr_arena, matches)
}
pub(super) fn predicate_is_sort_boundary(node: Node, expr_arena: &Arena<AExpr>) -> bool {
let matches = |e: &AExpr| match e {
AExpr::Window { function, .. } => shifts_elements(*function, expr_arena),
AExpr::Function { options, .. } | AExpr::AnonymousFunction { options, .. } => {
// this check for functions that are
// group sensitive and doesn't auto-explode (e.g. is a reduction/aggregation
// like sum, min, etc).
// function that match this are `cum_sum`, `shift`, `sort`, etc.
options.is_groups_sensitive() && !options.returns_scalar
},
_ => false,
};
has_aexpr(node, expr_arena, matches)
}
/// Evaluates a condition on the column name inputs of every predicate, where if
/// the condition evaluates to true on any column name the predicate is
/// transferred to local.
pub(super) fn transfer_to_local_by_name<F>(
expr_arena: &Arena<AExpr>,
acc_predicates: &mut PlHashMap<Arc<str>, ExprIR>,
mut condition: F,
) -> Vec<ExprIR>
where
F: FnMut(Arc<str>) -> bool,
{
let mut remove_keys = Vec::with_capacity(acc_predicates.len());
for (key, predicate) in &*acc_predicates {
let root_names = aexpr_to_leaf_names(predicate.node(), expr_arena);
for name in root_names {
if condition(name) {
remove_keys.push(key.clone());
break;
}
}
}
let mut local_predicates = Vec::with_capacity(remove_keys.len());
for key in remove_keys {
if let Some(pred) = acc_predicates.remove(&*key) {
local_predicates.push(pred)
}
}
local_predicates
}
fn check_and_extend_predicate_pd_nodes(
stack: &mut Vec<Node>,
ae: &AExpr,
expr_arena: &Arena<AExpr>,
) -> bool {
if match ae {
// These literals do not come from the RHS of an is_in, meaning that
// they are projected as either columns or predicates, both of which
// rely on the height of the dataframe at this level and thus need
// to block pushdown.
AExpr::Literal(lit) => !lit.projects_as_scalar(),
ae => ae.groups_sensitive(),
} {
false
} else {
match ae {
#[cfg(feature = "is_in")]
AExpr::Function {
function: FunctionExpr::Boolean(BooleanFunction::IsIn),
input,
..
} => {
// Handles a special case where the expr contains a series, but it is being
// used as part the RHS of an `is_in`, so it can be pushed down as it is not
// being projected.
let mut transferred_local_nodes = false;
if let Some(rhs) = input.get(1) {
let rhs = rhs.node();
if matches!(expr_arena.get(rhs), AExpr::Literal { .. }) {
let mut local_nodes = Vec::<Node>::with_capacity(4);
ae.nodes(&mut local_nodes);
stack.extend(local_nodes.into_iter().filter(|node| *node != rhs));
transferred_local_nodes = true;
}
};
if !transferred_local_nodes {
ae.nodes(stack);
}
},
ae => {
ae.nodes(stack);
},
};
true
}
}
/// An expression blocks predicates from being pushed past it if its results for
/// the subset where the predicate evaluates as true becomes different compared
/// to if it was performed before the predicate was applied. This is in general
/// any expression that produces outputs based on groups of values
/// (i.e. groups-wise) rather than individual values (i.e. element-wise).
///
/// Examples of expressions whose results would change, and thus block push-down:
/// - any aggregation - sum, mean, first, last, min, max etc.
/// - sorting - as the sort keys would change between filters
pub(super) fn aexpr_blocks_predicate_pushdown(node: Node, expr_arena: &Arena<AExpr>) -> bool {
let mut stack = Vec::<Node>::with_capacity(4);
stack.push(node);
// Cannot use `has_aexpr` because we need to ignore any literals in the RHS
// of an `is_in` operation.
while let Some(node) = stack.pop() {
let ae = expr_arena.get(node);
if !check_and_extend_predicate_pd_nodes(&mut stack, ae, expr_arena) {
return true;
}
}
false
}
/// * `col(A).alias(B).alias(C) => (C, A)`
/// * `col(A) => (A, A)`
/// * `col(A).sum().alias(B) => None`
fn get_maybe_aliased_projection_to_input_name_map(
e: &ExprIR,
expr_arena: &Arena<AExpr>,
) -> Option<(Arc<str>, Arc<str>)> {
let ae = expr_arena.get(e.node());
match e.get_alias() {
Some(alias) => match ae {
AExpr::Column(c_name) => Some((alias.clone(), c_name.clone())),
_ => None,
},
_ => match ae {
AExpr::Column(c_name) => Some((c_name.clone(), c_name.clone())),
_ => None,
},
}
}
pub enum PushdownEligibility {
Full,
// Partial can happen when there are window exprs.
Partial { to_local: Vec<Arc<str>> },
NoPushdown,
}
#[allow(clippy::type_complexity)]
pub fn pushdown_eligibility(
projection_nodes: &[ExprIR],
acc_predicates: &PlHashMap<Arc<str>, ExprIR>,
expr_arena: &mut Arena<AExpr>,
) -> PolarsResult<(PushdownEligibility, PlHashMap<Arc<str>, Arc<str>>)> {
let mut ae_nodes_stack = Vec::<Node>::with_capacity(4);
let mut alias_to_col_map =
optimizer::init_hashmap::<Arc<str>, Arc<str>>(Some(projection_nodes.len()));
let mut col_to_alias_map = alias_to_col_map.clone();
let mut modified_projection_columns =
PlHashSet::<Arc<str>>::with_capacity(projection_nodes.len());
let mut has_window = false;
let mut common_window_inputs = PlHashSet::<Arc<str>>::new();
// Important: Names inserted into any data structure by this function are
// all non-aliased.
// This function returns false if pushdown cannot be performed.
let process_projection_or_predicate =
|ae_nodes_stack: &mut Vec<Node>,
has_window: &mut bool,
common_window_inputs: &mut PlHashSet<Arc<str>>| {
debug_assert_eq!(ae_nodes_stack.len(), 1);
while let Some(node) = ae_nodes_stack.pop() {
let ae = expr_arena.get(node);
match ae {
AExpr::Window {
partition_by,
#[cfg(feature = "dynamic_group_by")]
options,
// The function is not checked for groups-sensitivity because
// it is applied over the windows.
..
} => {
#[cfg(feature = "dynamic_group_by")]
if matches!(options, WindowType::Rolling(..)) {
return false;
};
let mut partition_by_names =
PlHashSet::<Arc<str>>::with_capacity(partition_by.len());
for node in partition_by.iter() {
// Only accept col()
if let AExpr::Column(name) = expr_arena.get(*node) {
partition_by_names.insert(name.clone());
} else {
// Nested windows can also qualify for push down.
// e.g.:
// * expr1 = min().over(A)
// * expr2 = sum().over(A, expr1)
// Both exprs window over A, so predicates referring
// to A can still be pushed.
ae_nodes_stack.push(*node);
}
}
if !*has_window {
for name in partition_by_names.into_iter() {
common_window_inputs.insert(name);
}
*has_window = true;
} else {
common_window_inputs.retain(|k| partition_by_names.contains(k))
}
// Cannot push into disjoint windows:
// e.g.:
// * sum().over(A)
// * sum().over(B)
if common_window_inputs.is_empty() {
return false;
}
},
_ => {
if !check_and_extend_predicate_pd_nodes(ae_nodes_stack, ae, expr_arena) {
return false;
}
},
}
}
true
};
for e in projection_nodes.iter() {
if let Some((alias, column_name)) =
get_maybe_aliased_projection_to_input_name_map(e, expr_arena)
{
if alias != column_name {
alias_to_col_map.insert(alias.clone(), column_name.clone());
col_to_alias_map.insert(column_name, alias);
}
continue;
}
modified_projection_columns.insert(e.output_name_arc().clone());
debug_assert!(ae_nodes_stack.is_empty());
ae_nodes_stack.push(e.node());
if !process_projection_or_predicate(
&mut ae_nodes_stack,
&mut has_window,
&mut common_window_inputs,
) {
return Ok((PushdownEligibility::NoPushdown, alias_to_col_map));
}
}
if has_window && !col_to_alias_map.is_empty() {
// Rename to aliased names.
let mut new = PlHashSet::<Arc<str>>::with_capacity(2 * common_window_inputs.len());
for key in common_window_inputs.into_iter() {
if let Some(aliased) = col_to_alias_map.get(&key) {
new.insert(aliased.clone());
}
// Ensure predicate does not refer to a different column that
// got aliased to the same name as the window column. E.g.:
// .with_columns(col(A).alias(C), sum=sum().over(C))
// .filter(col(C) == ..)
if !alias_to_col_map.contains_key(&key) {
new.insert(key);
}
}
if new.is_empty() {
return Ok((PushdownEligibility::NoPushdown, alias_to_col_map));
}
common_window_inputs = new;
}
for e in acc_predicates.values() {
debug_assert!(ae_nodes_stack.is_empty());
ae_nodes_stack.push(e.node());
if !process_projection_or_predicate(
&mut ae_nodes_stack,
&mut has_window,
&mut common_window_inputs,
) {
return Ok((PushdownEligibility::NoPushdown, alias_to_col_map));
}
}
// Should have returned early.
debug_assert!(!common_window_inputs.is_empty() || !has_window);
if !has_window && projection_nodes.is_empty() {
return Ok((PushdownEligibility::Full, alias_to_col_map));
}
// Note: has_window is constant.
let can_use_column = |col: &Arc<str>| {
if has_window {
common_window_inputs.contains(col)
} else {
!modified_projection_columns.contains(col)
}
};
let to_local = acc_predicates
.iter()
.filter_map(|(key, e)| {
debug_assert!(ae_nodes_stack.is_empty());
ae_nodes_stack.push(e.node());
let mut can_pushdown = true;
while let Some(node) = ae_nodes_stack.pop() {
let ae = expr_arena.get(node);
can_pushdown &= if let AExpr::Column(name) = ae {
can_use_column(name)
} else {
// May still contain window expressions that need to be blocked.
check_and_extend_predicate_pd_nodes(&mut ae_nodes_stack, ae, expr_arena)
};
if !can_pushdown {
break;
};
}
ae_nodes_stack.clear();
if !can_pushdown {
Some(key.clone())
} else {
None
}
})
.collect::<Vec<_>>();
match to_local.len() {
0 => Ok((PushdownEligibility::Full, alias_to_col_map)),
len if len == acc_predicates.len() => {
Ok((PushdownEligibility::NoPushdown, alias_to_col_map))
},
_ => Ok((PushdownEligibility::Partial { to_local }, alias_to_col_map)),
}
}
/// Used in places that previously handled blocking exprs before refactoring.
/// Can probably be eventually removed if it isn't catching anything.
#[inline(always)]
pub(super) fn debug_assert_aexpr_allows_predicate_pushdown(node: Node, expr_arena: &Arena<AExpr>) {
debug_assert!(
!aexpr_blocks_predicate_pushdown(node, expr_arena),
"Predicate pushdown: Did not expect blocking exprs at this point, please open an issue."
);
}