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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
use std::cmp::Ordering;
use std::collections::{BTreeMap, HashSet};
use std::convert::TryInto;
use std::iter;
use mz_expr::visit::Visit;
use mz_expr::{AggregateExpr, ColumnOrder, EvalError, MirRelationExpr, MirScalarExpr, TableFunc};
use mz_repr::{ColumnType, Datum, Diff, RelationType, Row, RowArena};
use crate::{TransformArgs, TransformError};
#[derive(Debug)]
pub struct FoldConstants {
pub limit: Option<usize>,
}
impl crate::Transform for FoldConstants {
#[tracing::instrument(
target = "optimizer"
level = "trace",
skip_all,
fields(path.segment = "fold_constants")
)]
fn transform(
&self,
relation: &mut MirRelationExpr,
_: TransformArgs,
) -> Result<(), TransformError> {
let mut type_stack = Vec::new();
let result = relation.try_visit_mut_post(&mut |e| -> Result<(), TransformError> {
let num_inputs = e.num_inputs();
let input_types = &type_stack[type_stack.len() - num_inputs..];
let mut relation_type = e.typ_with_input_types(input_types);
self.action(
e,
&mut relation_type,
input_types.iter().map(|typ| &typ.column_types),
)?;
type_stack.truncate(type_stack.len() - num_inputs);
type_stack.push(relation_type);
Ok(())
});
mz_repr::explain_new::trace_plan(&*relation);
result
}
}
impl FoldConstants {
pub fn action<'a, I>(
&self,
relation: &mut MirRelationExpr,
relation_type: &mut RelationType,
mut input_types: I,
) -> Result<(), TransformError>
where
I: Iterator<Item = &'a Vec<ColumnType>>,
{
match relation {
MirRelationExpr::Constant { .. } => { }
MirRelationExpr::Get { .. } => {}
MirRelationExpr::Let { .. } => { }
MirRelationExpr::Reduce {
input,
group_key,
aggregates,
monotonic: _,
expected_group_size: _,
} => {
let input_typ = input_types.next().unwrap();
for key in group_key.iter_mut() {
key.reduce(input_typ);
}
for aggregate in aggregates.iter_mut() {
aggregate.expr.reduce(input_typ);
}
if group_key.iter().any(|e| e.contains_unmaterializable())
|| aggregates
.iter()
.any(|a| a.expr.contains_unmaterializable())
{
return Ok(());
}
if let MirRelationExpr::Constant { rows, .. } = &**input {
let new_rows = match rows {
Ok(rows) => {
if let Some(rows) =
Self::fold_reduce_constant(group_key, aggregates, rows, self.limit)
{
rows
} else {
return Ok(());
}
}
Err(e) => Err(e.clone()),
};
*relation = MirRelationExpr::Constant {
rows: new_rows,
typ: relation_type.clone(),
};
}
}
MirRelationExpr::TopK {
input,
group_key,
order_key,
limit,
offset,
..
} => {
if let MirRelationExpr::Constant { rows, .. } = &mut **input {
if let Ok(rows) = rows {
Self::fold_topk_constant(group_key, order_key, limit, offset, rows);
}
*relation = input.take_dangerous();
}
}
MirRelationExpr::Negate { input } => {
if let MirRelationExpr::Constant { rows, .. } = &mut **input {
if let Ok(rows) = rows {
for (_row, diff) in rows {
*diff *= -1;
}
}
*relation = input.take_dangerous();
}
}
MirRelationExpr::Threshold { input } => {
if let MirRelationExpr::Constant { rows, .. } = &mut **input {
if let Ok(rows) = rows {
rows.retain(|(_, diff)| *diff > 0);
}
*relation = input.take_dangerous();
}
}
MirRelationExpr::Map { input, scalars } => {
let input_arity = input_types.next().unwrap().len();
for (index, scalar) in scalars.iter_mut().enumerate() {
scalar.reduce(&relation_type.column_types[..(input_arity + index)]);
}
if scalars.iter().any(|e| e.contains_unmaterializable()) {
return Ok(());
}
if let MirRelationExpr::Constant { rows, .. } = &**input {
let new_rows = match rows {
Ok(rows) => rows
.iter()
.cloned()
.map(|(input_row, diff)| {
let mut unpacked = input_row.unpack();
let temp_storage = RowArena::new();
for scalar in scalars.iter() {
unpacked.push(scalar.eval(&unpacked, &temp_storage)?)
}
Ok::<_, EvalError>((Row::pack_slice(&unpacked), diff))
})
.collect::<Result<_, _>>(),
Err(e) => Err(e.clone()),
};
*relation = MirRelationExpr::Constant {
rows: new_rows,
typ: relation_type.clone(),
};
}
}
MirRelationExpr::FlatMap { input, func, exprs } => {
let input_typ = input_types.next().unwrap();
for expr in exprs.iter_mut() {
expr.reduce(input_typ);
}
if exprs.iter().any(|e| e.contains_unmaterializable()) {
return Ok(());
}
if let MirRelationExpr::Constant { rows, .. } = &**input {
let new_rows = match rows {
Ok(rows) => Self::fold_flat_map_constant(func, exprs, rows, self.limit),
Err(e) => Err(e.clone()),
};
match new_rows {
Ok(None) => {}
Ok(Some(rows)) => {
*relation = MirRelationExpr::Constant {
rows: Ok(rows),
typ: relation_type.clone(),
};
}
Err(err) => {
*relation = MirRelationExpr::Constant {
rows: Err(err),
typ: relation_type.clone(),
};
}
};
}
}
MirRelationExpr::Filter { input, predicates } => {
let input_typ = input_types.next().unwrap();
for predicate in predicates.iter_mut() {
predicate.reduce(input_typ);
}
predicates.retain(|p| !p.is_literal_true());
if predicates.iter().any(|e| e.contains_unmaterializable()) {
return Ok(());
}
if predicates
.iter()
.any(|p| p.is_literal_false() || p.is_literal_null())
{
relation.take_safely();
} else if let MirRelationExpr::Constant { rows, .. } = &**input {
predicates.sort_by_key(|p| p.is_literal_err());
let new_rows = match rows {
Ok(rows) => Self::fold_filter_constant(predicates, rows),
Err(e) => Err(e.clone()),
};
*relation = MirRelationExpr::Constant {
rows: new_rows,
typ: relation_type.clone(),
};
}
}
MirRelationExpr::Project { input, outputs } => {
if let MirRelationExpr::Constant { rows, .. } = &**input {
let mut row_buf = Row::default();
let new_rows = match rows {
Ok(rows) => Ok(rows
.iter()
.map(|(input_row, diff)| {
let datums = input_row.unpack();
row_buf.packer().extend(outputs.iter().map(|i| &datums[*i]));
(row_buf.clone(), *diff)
})
.collect()),
Err(e) => Err(e.clone()),
};
*relation = MirRelationExpr::Constant {
rows: new_rows,
typ: relation_type.clone(),
};
}
}
MirRelationExpr::Join {
inputs,
equivalences,
..
} => {
if inputs.iter().any(|e| e.is_empty()) {
relation.take_safely();
} else if let Some(e) = inputs.iter().find_map(|i| match i {
MirRelationExpr::Constant { rows: Err(e), .. } => Some(e),
_ => None,
}) {
*relation = MirRelationExpr::Constant {
rows: Err(e.clone()),
typ: relation_type.clone(),
};
} else if inputs
.iter()
.all(|i| matches!(i, MirRelationExpr::Constant { rows: Ok(_), .. }))
{
if equivalences
.iter()
.any(|equiv| equiv.iter().any(|e| e.contains_unmaterializable()))
{
return Ok(());
}
let mut old_rows = vec![(Row::pack::<_, Datum>(None), 1)];
let mut row_buf = Row::default();
for input in inputs.iter() {
if let MirRelationExpr::Constant { rows: Ok(rows), .. } = input {
if let Some(limit) = self.limit {
if old_rows.len() * rows.len() > limit {
return Ok(());
}
}
let mut next_rows = Vec::new();
for (old_row, old_count) in old_rows {
for (new_row, new_count) in rows.iter() {
row_buf
.packer()
.extend(old_row.iter().chain(new_row.iter()));
next_rows.push((row_buf.clone(), old_count * *new_count));
}
}
old_rows = next_rows;
}
}
let mut datum_vec = mz_repr::DatumVec::new();
old_rows.retain(|(row, _count)| {
let datums = datum_vec.borrow_with(row);
let temp_storage = RowArena::new();
equivalences.iter().all(|equivalence| {
let mut values =
equivalence.iter().map(|e| e.eval(&datums, &temp_storage));
if let Some(value) = values.next() {
values.all(|v| v == value)
} else {
true
}
})
});
*relation = MirRelationExpr::Constant {
rows: Ok(old_rows),
typ: relation_type.clone(),
};
}
}
MirRelationExpr::Union { base, inputs } => {
if let Some(e) = iter::once(&mut **base)
.chain(&mut *inputs)
.find_map(|i| match i {
MirRelationExpr::Constant { rows: Err(e), .. } => Some(e),
_ => None,
})
{
*relation = MirRelationExpr::Constant {
rows: Err(e.clone()),
typ: relation_type.clone(),
};
} else {
let mut rows = vec![];
let mut new_inputs = vec![];
for input in iter::once(&mut **base).chain(&mut *inputs) {
match input.take_dangerous() {
MirRelationExpr::Constant {
rows: Ok(rs),
typ: _,
} => rows.extend(rs),
input => new_inputs.push(input),
}
}
if !rows.is_empty() {
new_inputs.push(MirRelationExpr::Constant {
rows: Ok(rows),
typ: relation_type.clone(),
});
}
*relation = MirRelationExpr::union_many(new_inputs, relation_type.clone());
}
}
MirRelationExpr::ArrangeBy { input, .. } => {
if let MirRelationExpr::Constant { .. } = &**input {
*relation = input.take_dangerous();
}
}
}
if let MirRelationExpr::Constant {
rows: Ok(rows),
typ,
} = relation
{
differential_dataflow::consolidation::consolidate(rows);
for col_type in typ.column_types.iter_mut() {
col_type.nullable = false;
}
for (row, _) in rows.iter_mut() {
for (index, datum) in row.iter().enumerate() {
if datum.is_null() {
typ.column_types[index].nullable = true;
}
}
}
*relation_type = typ.clone();
}
Ok(())
}
fn fold_reduce_constant(
group_key: &[MirScalarExpr],
aggregates: &[AggregateExpr],
rows: &[(Row, Diff)],
limit: Option<usize>,
) -> Option<Result<Vec<(Row, Diff)>, EvalError>> {
let mut groups = BTreeMap::new();
let temp_storage2 = RowArena::new();
let mut row_buf = Row::default();
let mut limit_remaining = limit.unwrap_or(usize::MAX);
for (row, diff) in rows {
if *diff <= 0 {
return Some(Err(EvalError::InvalidParameterValue(String::from(
"constant folding encountered reduce on collection \
with non-positive multiplicities",
))));
}
if limit_remaining < *diff as usize {
return None;
}
limit_remaining -= *diff as usize;
let datums = row.unpack();
let temp_storage = RowArena::new();
let key = match group_key
.iter()
.map(|e| e.eval(&datums, &temp_storage2))
.collect::<Result<Vec<_>, _>>()
{
Ok(key) => key,
Err(e) => return Some(Err(e)),
};
let val = match aggregates
.iter()
.map(|agg| {
row_buf
.packer()
.extend([agg.expr.eval(&datums, &temp_storage)?]);
Ok::<_, EvalError>(row_buf.clone())
})
.collect::<Result<Vec<_>, _>>()
{
Ok(val) => val,
Err(e) => return Some(Err(e)),
};
let entry = groups.entry(key).or_insert_with(Vec::new);
for _ in 0..*diff {
entry.push(val.clone());
}
}
let new_rows = groups
.into_iter()
.map({
let mut row_buf = Row::default();
move |(key, vals)| {
let temp_storage = RowArena::new();
row_buf.packer().extend(key.into_iter().chain(
aggregates.iter().enumerate().map(|(i, agg)| {
if agg.distinct {
agg.func.eval(
vals.iter()
.map(|val| val[i].unpack_first())
.collect::<HashSet<_>>()
.into_iter(),
&temp_storage,
)
} else {
agg.func.eval(
vals.iter().map(|val| val[i].unpack_first()),
&temp_storage,
)
}
}),
));
(row_buf.clone(), 1)
}
})
.collect();
Some(Ok(new_rows))
}
fn fold_topk_constant<'a>(
group_key: &[usize],
order_key: &[ColumnOrder],
limit: &Option<usize>,
offset: &usize,
rows: &'a mut [(Row, Diff)],
) {
let mut lhs_datum_vec = mz_repr::DatumVec::new();
let mut rhs_datum_vec = mz_repr::DatumVec::new();
let mut cmp_order_key = |lhs: &(Row, Diff), rhs: &(Row, Diff)| {
let lhs_datums = &lhs_datum_vec.borrow_with(&lhs.0);
let rhs_datums = &rhs_datum_vec.borrow_with(&rhs.0);
mz_expr::compare_columns(order_key, lhs_datums, rhs_datums, || lhs.cmp(rhs))
};
let mut cmp_group_key = {
let group_key = group_key
.iter()
.map(|column| ColumnOrder {
column: *column,
desc: false,
nulls_last: false,
})
.collect::<Vec<ColumnOrder>>();
let mut lhs_datum_vec = mz_repr::DatumVec::new();
let mut rhs_datum_vec = mz_repr::DatumVec::new();
move |lhs: &(Row, Diff), rhs: &(Row, Diff)| {
let lhs_datums = &lhs_datum_vec.borrow_with(&lhs.0);
let rhs_datums = &rhs_datum_vec.borrow_with(&rhs.0);
mz_expr::compare_columns(&group_key, lhs_datums, rhs_datums, || Ordering::Equal)
}
};
rows.sort_by(&mut cmp_order_key);
if !group_key.is_empty() {
rows.sort_by(&mut cmp_group_key);
};
let mut same_group_key =
|lhs: &(Row, Diff), rhs: &(Row, Diff)| cmp_group_key(lhs, rhs) == Ordering::Equal;
let mut cursor = 0;
while cursor < rows.len() {
let mut offset_rem: Diff = offset.clone().try_into().unwrap();
let mut limit_rem: Option<Diff> = limit.clone().map(|x| x.try_into().unwrap());
let mut finger = cursor;
while finger < rows.len() && same_group_key(&rows[cursor], &rows[finger]) {
if rows[finger].1 < 0 {
rows[finger].1 = 0;
} else {
let rows_to_ignore = std::cmp::min(offset_rem, rows[finger].1);
rows[finger].1 -= rows_to_ignore;
offset_rem -= rows_to_ignore;
if let Some(limit_rem) = &mut limit_rem {
let rows_to_retain = std::cmp::min(*limit_rem, rows[finger].1);
rows[finger].1 = rows_to_retain;
*limit_rem -= rows_to_retain;
}
}
finger += 1;
}
cursor = finger;
}
}
fn fold_flat_map_constant(
func: &TableFunc,
exprs: &[MirScalarExpr],
rows: &[(Row, Diff)],
limit: Option<usize>,
) -> Result<Option<Vec<(Row, Diff)>>, EvalError> {
let limit = limit.unwrap_or(usize::MAX);
let mut new_rows = Vec::new();
let mut row_buf = Row::default();
let mut datum_vec = mz_repr::DatumVec::new();
for (input_row, diff) in rows {
let datums = datum_vec.borrow_with(input_row);
let temp_storage = RowArena::new();
let datums = exprs
.iter()
.map(|expr| expr.eval(&datums, &temp_storage))
.collect::<Result<Vec<_>, _>>()?;
let mut output_rows = func.eval(&datums, &temp_storage)?.fuse();
for (output_row, diff2) in (&mut output_rows).take(limit - new_rows.len()) {
row_buf
.packer()
.extend(input_row.clone().into_iter().chain(output_row.into_iter()));
new_rows.push((row_buf.clone(), diff2 * *diff))
}
if output_rows.next() != None {
return Ok(None);
}
}
Ok(Some(new_rows))
}
fn fold_filter_constant(
predicates: &[MirScalarExpr],
rows: &[(Row, Diff)],
) -> Result<Vec<(Row, Diff)>, EvalError> {
let mut new_rows = Vec::new();
let mut datum_vec = mz_repr::DatumVec::new();
'outer: for (row, diff) in rows {
let datums = datum_vec.borrow_with(row);
let temp_storage = RowArena::new();
for p in &*predicates {
if p.eval(&datums, &temp_storage)? != Datum::True {
continue 'outer;
}
}
new_rows.push((row.clone(), *diff))
}
Ok(new_rows)
}
}