This repository was archived by the owner on May 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathRelAlgExecutor.cpp
More file actions
1942 lines (1790 loc) · 79 KB
/
Copy pathRelAlgExecutor.cpp
File metadata and controls
1942 lines (1790 loc) · 79 KB
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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2017 MapD Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "RelAlgExecutor.h"
#include "DataMgr/DataMgr.h"
#include "IR/TypeUtils.h"
#include "QueryBuilder/QueryBuilder.h"
#include "QueryEngine/CalciteDeserializerUtils.h"
#include "QueryEngine/CardinalityEstimator.h"
#include "QueryEngine/ColumnFetcher.h"
#include "QueryEngine/EquiJoinCondition.h"
#include "QueryEngine/ErrorHandling.h"
#include "QueryEngine/ExpressionRewrite.h"
#include "QueryEngine/ExtensionFunctionsBinding.h"
#include "QueryEngine/ExternalExecutor.h"
#include "QueryEngine/FromTableReordering.h"
#include "QueryEngine/MemoryLayoutBuilder.h"
#include "QueryEngine/QueryPhysicalInputsCollector.h"
#include "QueryEngine/QueryPlanDagExtractor.h"
#include "QueryEngine/RangeTableIndexVisitor.h"
#include "QueryEngine/RelAlgDagBuilder.h"
#include "QueryEngine/RelAlgTranslator.h"
#include "QueryEngine/RelAlgVisitor.h"
#include "QueryEngine/ResultSetBuilder.h"
#include "QueryEngine/ResultSetSort.h"
#include "QueryEngine/UnnestedVarsCollector.h"
#include "QueryEngine/WindowContext.h"
#include "QueryEngine/WorkUnitBuilder.h"
#include "QueryOptimizer/CanonicalizeQuery.h"
#include "ResultSet/ColRangeInfo.h"
#include "ResultSet/HyperLogLog.h"
#include "ResultSetRegistry/ResultSetRegistry.h"
#include "SchemaMgr/SchemaMgr.h"
#include "SessionInfo.h"
#include "Shared/MathUtils.h"
#include "Shared/funcannotations.h"
#include "Shared/measure.h"
#include "Shared/misc.h"
#include <boost/algorithm/cxx11/any_of.hpp>
#include <boost/make_unique.hpp>
#include <boost/range/adaptor/reversed.hpp>
#include <algorithm>
#include <functional>
#include <numeric>
using namespace std::string_literals;
size_t g_estimator_failure_max_groupby_size{256000000};
bool g_columnar_large_projections{true};
size_t g_columnar_large_projections_threshold{1000000};
EXTERN extern bool g_enable_table_functions;
namespace {
bool is_projection(const RelAlgExecutionUnit& ra_exe_unit) {
return ra_exe_unit.groupby_exprs.size() == 1 && !ra_exe_unit.groupby_exprs.front();
}
bool should_output_columnar(const RelAlgExecutionUnit& ra_exe_unit) {
if (!is_projection(ra_exe_unit)) {
return false;
}
if (!ra_exe_unit.sort_info.order_entries.empty()) {
// disable output columnar when we have top-sort node query
return false;
}
for (const auto& target_expr : ra_exe_unit.target_exprs) {
// We don't currently support varlen columnar projections, so
// return false if we find one
if (target_expr->type()->isString() || target_expr->type()->isArray()) {
return false;
}
}
return ra_exe_unit.scan_limit >= g_columnar_large_projections_threshold;
}
bool is_extracted_dag_valid(ExtractedPlanDag& dag) {
return !dag.contain_not_supported_rel_node &&
dag.extracted_dag.compare(EMPTY_QUERY_PLAN) != 0;
}
} // namespace
RelAlgExecutor::RelAlgExecutor(Executor* executor, SchemaProviderPtr schema_provider)
: executor_(executor)
, schema_provider_(schema_provider)
, data_provider_(executor->getDataMgr()->getDataProvider())
, config_(executor_->getConfig())
, now_(0)
, queue_time_ms_(0) {
rs_registry_ = hdk::ResultSetRegistry::getOrCreate(executor->getDataMgr(),
executor->getConfigPtr());
}
RelAlgExecutor::RelAlgExecutor(Executor* executor,
SchemaProviderPtr schema_provider,
std::unique_ptr<hdk::ir::QueryDag> query_dag)
: executor_(executor)
, query_dag_(std::move(query_dag))
, schema_provider_(schema_provider)
, data_provider_(executor->getDataMgr()->getDataProvider())
, config_(executor_->getConfig())
, now_(0)
, queue_time_ms_(0) {
rs_registry_ = hdk::ResultSetRegistry::getOrCreate(executor->getDataMgr(),
executor->getConfigPtr());
// Add ResultSetRegistry to the schema provider by wrapping the current provider
// and the registry in SchemaMgr.
// TODO: In the future we expect pre-initialized registry and passed schema provider
// to cover it.
auto db_ids = schema_provider->listDatabases();
if (std::find(db_ids.begin(), db_ids.end(), hdk::ResultSetRegistry::DB_ID) ==
db_ids.end()) {
schema_provider_ =
mergeProviders(std::vector<SchemaProviderPtr>({schema_provider, rs_registry_}));
}
hdk::ir::canonicalizeQuery(*query_dag_);
}
RelAlgExecutor::~RelAlgExecutor() {
// We don't need temporary tables anymore. On desctruction we are going to lose
// all tokens and have ResultSets removed from the ResultSetRegistry. But some
// zero-copy Buffers might still live DataMgr and hold ResultSets alive. Here
// we clear these chunk to avoid unnecessary cached data. Remove in the reverse
// order because later results can re-use and pin earlier ones. Some buffers
// may still remain pinned by the final query result though.
std::set<int, std::greater<int>> tmp_table_ids;
for (auto& pr : temporary_tables_) {
tmp_table_ids.insert(pr.second->tableId());
}
auto data_mgr = executor_->getDataMgr();
ChunkKey prefix = {hdk::ResultSetRegistry::DB_ID, 0};
for (auto table_id : tmp_table_ids) {
prefix[1] = table_id;
data_mgr->deleteChunksWithPrefix(prefix, MemoryLevel::CPU_LEVEL);
}
}
ExecutionResult RelAlgExecutor::executeRelAlgQuery(const CompilationOptions& co,
const ExecutionOptions& eo,
const bool just_explain_plan) {
CHECK(query_dag_);
auto timer = DEBUG_TIMER(__func__);
INJECT_TIMER(executeRelAlgQuery);
auto run_query = [&](const CompilationOptions& co_in) {
auto execution_result = executeRelAlgQueryNoRetry(co_in, eo, just_explain_plan);
constexpr bool vlog_result_set_summary{false};
if constexpr (vlog_result_set_summary) {
for (size_t i = 0; i < execution_result.getToken()->resultSetCount(); ++i) {
VLOG(1) << execution_result.getToken()->resultSet(i)->summaryToString();
}
}
if (post_execution_callback_) {
VLOG(1) << "Running post execution callback.";
(*post_execution_callback_)();
}
return execution_result;
};
try {
return run_query(co);
} catch (const QueryMustRunOnCpu&) {
if (!config_.exec.heterogeneous.allow_cpu_retry) {
throw;
}
}
LOG(INFO) << "Query unable to run in GPU mode, retrying on CPU";
auto co_cpu = CompilationOptions::makeCpuOnly(co);
return run_query(co_cpu);
}
std::string treeToString(const hdk::ir::Node* node,
bool stop_on_executed = true,
std::string prefix = "|") {
std::stringstream ss;
ss << prefix << node->toString() << std::endl;
if (!stop_on_executed || !node->getResult()) {
for (size_t i = 0; i < node->inputCount(); ++i) {
ss << treeToString(node->getInput(i), stop_on_executed, prefix + "----");
}
}
return ss.str();
}
void printTree(const hdk::ir::Node* node,
bool stop_on_executed = true,
std::string prefix = "|") {
std::cout << treeToString(node, stop_on_executed, prefix);
}
ExecutionResult RelAlgExecutor::executeRelAlgQueryNoRetry(const CompilationOptions& co,
const ExecutionOptions& eo,
const bool just_explain_plan) {
INJECT_TIMER(executeRelAlgQueryNoRetry);
auto timer = DEBUG_TIMER(__func__);
auto timer_setup = DEBUG_TIMER("Query pre-execution steps");
query_dag_->resetQueryExecutionState();
const auto ra = query_dag_->getRootNode();
// capture the lock acquistion time
auto clock_begin = timer_start();
if (config_.exec.watchdog.enable_dynamic) {
executor_->resetInterrupt();
}
int64_t queue_time_ms = timer_stop(clock_begin);
ScopeGuard row_set_holder = [this] { cleanupPostExecution(); };
const auto col_descs = get_physical_inputs(ra);
const auto phys_table_ids = get_physical_table_inputs(ra);
executor_->setSchemaProvider(schema_provider_);
executor_->setupCaching(data_provider_, col_descs, phys_table_ids);
ScopeGuard restore_metainfo_cache = [this] { executor_->clearMetaInfoCache(); };
hdk::QueryExecutionSequence query_seq(ra, executor_->getConfigPtr());
if (just_explain_plan) {
std::stringstream ss;
std::vector<const hdk::ir::Node*> nodes;
for (size_t i = 0; i < query_seq.size(); i++) {
nodes.emplace_back(query_seq.step(i));
}
size_t ctr = nodes.size();
size_t tab_ctr = 0;
for (auto& body : boost::adaptors::reverse(nodes)) {
const auto index = ctr--;
const auto tabs = std::string(tab_ctr++, '\t');
CHECK(body);
ss << tabs << std::to_string(index) << " : " << body->toString() << "\n";
if (auto sort = dynamic_cast<const hdk::ir::Sort*>(body)) {
ss << tabs << " : " << sort->getInput(0)->toString() << "\n";
}
}
const auto& subqueries = getSubqueries();
if (!subqueries.empty()) {
ss << "Subqueries: "
<< "\n";
for (const auto& subquery : subqueries) {
const auto ra = subquery->node();
ss << "\t" << ra->toString() << "\n";
}
}
auto rs = std::make_shared<ResultSet>(ss.str());
return registerResultSetTable({rs}, {}, true);
}
if (eo.find_push_down_candidates) {
// this extra logic is mainly due to current limitations on multi-step queries
// and/or subqueries.
return executeRelAlgQueryWithFilterPushDown(query_seq, co, eo, queue_time_ms);
}
timer_setup.stop();
// Dispatch the subqueries first
for (auto& subquery : getSubqueries()) {
auto subquery_ra = subquery->node();
CHECK(subquery_ra);
if (subquery_ra->hasContextData()) {
continue;
}
RelAlgExecutor ra_executor(executor_, schema_provider_);
hdk::QueryExecutionSequence subquery_seq(subquery_ra, executor_->getConfigPtr());
ra_executor.execute(subquery_seq, co, eo, 0);
}
auto shared_res = execute(query_seq, co, eo, queue_time_ms);
return std::move(*shared_res);
}
AggregatedColRange RelAlgExecutor::computeColRangesCache() {
AggregatedColRange agg_col_range_cache;
const auto col_descs = get_physical_inputs(getRootNode());
return executor_->computeColRangesCache(col_descs);
}
StringDictionaryGenerations RelAlgExecutor::computeStringDictionaryGenerations() {
const auto col_descs = get_physical_inputs(getRootNode());
return executor_->computeStringDictionaryGenerations(col_descs);
}
TableGenerations RelAlgExecutor::computeTableGenerations() {
const auto phys_table_ids = get_physical_table_inputs(getRootNode());
return executor_->computeTableGenerations(phys_table_ids);
}
Executor* RelAlgExecutor::getExecutor() const {
return executor_;
}
void RelAlgExecutor::cleanupPostExecution() {
CHECK(executor_);
executor_->row_set_mem_owner_ = nullptr;
}
std::pair<std::vector<unsigned>, std::unordered_map<unsigned, JoinQualsPerNestingLevel>>
RelAlgExecutor::getJoinInfo(const hdk::ir::Node* root_node) {
auto sort_node = dynamic_cast<const hdk::ir::Sort*>(root_node);
if (sort_node) {
// we assume that test query that needs join info does not contain any sort node
return {};
}
auto work_unit = createWorkUnit(root_node, {}, ExecutionOptions::fromConfig(Config()));
return {{}, getLeftDeepJoinTreesInfo()};
}
namespace {
inline void check_sort_node_source_constraint(const hdk::ir::Sort* sort) {
CHECK_EQ(size_t(1), sort->inputCount());
const auto source = sort->getInput(0);
if (dynamic_cast<const hdk::ir::Sort*>(source)) {
throw std::runtime_error("Sort node not supported as input to another sort");
}
}
/**
* Check if multifrag result of input would be OK for node execution.
*/
inline bool supportsMultifragInput(const hdk::ir::Node* node,
const hdk::ir::Node* input) {
if (node->is<hdk::ir::Sort>()) {
node = node->getInput(0);
}
if (!node->hasInput(input)) {
return true;
}
if (node->is<hdk::ir::Project>() &&
node->as<hdk::ir::Project>()->hasWindowFunctionExpr()) {
return false;
}
if (node->is<hdk::ir::LogicalUnion>()) {
return false;
}
return true;
}
} // namespace
void RelAlgExecutor::prepareLeafExecution(
const AggregatedColRange& agg_col_range,
const StringDictionaryGenerations& string_dictionary_generations,
const TableGenerations& table_generations) {
// capture the lock acquistion time
auto clock_begin = timer_start();
if (config_.exec.watchdog.enable_dynamic) {
executor_->resetInterrupt();
}
queue_time_ms_ = timer_stop(clock_begin);
executor_->row_set_mem_owner_ = std::make_shared<RowSetMemoryOwner>(
data_provider_, Executor::getArenaBlockSize(), cpu_threads());
executor_->string_dictionary_generations_ = string_dictionary_generations;
executor_->table_generations_ = table_generations;
executor_->agg_col_range_cache_ = agg_col_range;
}
std::shared_ptr<const ExecutionResult> RelAlgExecutor::execute(
const hdk::QueryExecutionSequence& seq,
const CompilationOptions& co,
const ExecutionOptions& eo,
const int64_t queue_time_ms,
const bool with_existing_temp_tables) {
INJECT_TIMER(execute);
auto timer = DEBUG_TIMER(__func__);
if (!with_existing_temp_tables) {
decltype(temporary_tables_)().swap(temporary_tables_);
}
decltype(target_exprs_owned_)().swap(target_exprs_owned_);
decltype(left_deep_join_info_)().swap(left_deep_join_info_);
executor_->setSchemaProvider(schema_provider_);
executor_->temporary_tables_ = &temporary_tables_;
time(&now_);
CHECK(seq.size());
auto get_descriptor_count = [&seq, &eo]() -> size_t {
if (eo.just_explain) {
if (dynamic_cast<const hdk::ir::LogicalValues*>(seq.step(0))) {
// run the logical values descriptor to generate the result set, then the next
// descriptor to generate the explain
CHECK_GE(seq.size(), size_t(2));
return 2;
} else {
return 1;
}
} else {
return seq.size();
}
};
const auto exec_desc_count = get_descriptor_count();
// this join info needs to be maintained throughout an entire query runtime
for (size_t i = 0; i < exec_desc_count; i++) {
VLOG(1) << "Executing query step " << i;
// When we execute the last step, we expect the result to consist of a single
// ResultSet unless said otherwise by the config. Also, check if following steps
// can consume multifrag input.
auto multifrag_result =
eo.multifrag_result &&
(i != (exec_desc_count - 1) || config_.exec.enable_multifrag_execution_result);
if (multifrag_result) {
for (size_t j = i + 1; j < exec_desc_count; j++) {
if (!supportsMultifragInput(seq.step(j), seq.step(i))) {
multifrag_result = false;
break;
}
}
}
auto fixed_eo = eo.with_multifrag_result(multifrag_result);
try {
executeStep(seq.step(i), co, fixed_eo, queue_time_ms);
} catch (const QueryMustRunOnCpu&) {
CHECK(config_.exec.heterogeneous.enable_heterogeneous_execution ||
co.device_type == ExecutorDeviceType::GPU);
if (!config_.exec.heterogeneous.allow_query_step_cpu_retry) {
throw;
}
LOG(INFO) << "Retrying current query step " << i << " on CPU";
const auto co_cpu = CompilationOptions::makeCpuOnly(co);
executeStep(seq.step(i), co_cpu, fixed_eo, queue_time_ms);
} catch (const NativeExecutionError&) {
if (!config_.exec.enable_interop) {
throw;
}
auto eo_extern = eo;
eo_extern.executor_type = ::ExecutorType::Extern;
executeStep(seq.step(i), co, eo_extern, queue_time_ms);
} catch (const RequestPartitionedAggregation& e) {
executeStepWithPartitionedAggregation(
seq.step(i), co, eo, e.estimatedBufferSize(), queue_time_ms);
}
}
return seq.step(exec_desc_count - 1)->getResult();
}
void RelAlgExecutor::handleNop(RaExecutionDesc& ed) {
// just set the result of the previous node as the result of no op
auto body = ed.getBody();
CHECK(dynamic_cast<const hdk::ir::Aggregate*>(body));
CHECK_EQ(size_t(1), body->inputCount());
const auto input = body->getInput(0);
body->setOutputMetainfo(input->getOutputMetainfo());
const auto it = temporary_tables_.find(-input->getId());
CHECK(it != temporary_tables_.end());
ed.setResult({it->second, input->getOutputMetainfo()});
// set up temp table as it could be used by the outer query or next step
addTemporaryTable(-body->getId(), it->second);
}
namespace {
const hdk::ir::Node* get_data_sink(const hdk::ir::Node* ra_node) {
if (auto join = dynamic_cast<const hdk::ir::Join*>(ra_node)) {
CHECK_EQ(size_t(2), join->inputCount());
return join;
}
if (!dynamic_cast<const hdk::ir::LogicalUnion*>(ra_node)) {
CHECK_EQ(size_t(1), ra_node->inputCount());
}
auto only_src = ra_node->getInput(0);
const bool is_join = dynamic_cast<const hdk::ir::Join*>(only_src);
return is_join ? only_src : ra_node;
}
std::unordered_map<const hdk::ir::Node*, int> get_input_nest_levels(
const hdk::ir::Node* ra_node,
const std::vector<size_t>& input_permutation) {
const auto data_sink_node = get_data_sink(ra_node);
std::unordered_map<const hdk::ir::Node*, int> input_to_nest_level;
for (size_t input_idx = 0; input_idx < data_sink_node->inputCount(); ++input_idx) {
const auto input_node_idx =
input_permutation.empty() ? input_idx : input_permutation[input_idx];
const auto input_ra = data_sink_node->getInput(input_node_idx);
// Having a non-zero mapped value (input_idx) results in the query being
// interpretted as a JOIN within CodeGenerator::codegenColVar() due to rte_idx
// being set to the mapped value (input_idx) which originates here. This would be
// incorrect for UNION.
size_t const idx =
dynamic_cast<const hdk::ir::LogicalUnion*>(ra_node) ? 0 : input_idx;
const auto it_ok = input_to_nest_level.emplace(input_ra, idx);
CHECK(it_ok.second);
LOG_IF(INFO, !input_permutation.empty())
<< "Assigned input " << input_ra->toString() << " to nest level " << input_idx;
}
return input_to_nest_level;
}
hdk::ir::ExprPtr set_transient_dict_maybe(hdk::ir::ExprPtr expr) {
try {
return set_transient_dict(fold_expr(expr.get()));
} catch (const OverflowOrUnderflow& e) {
throw e;
} catch (const std::exception& e) {
LOG(WARNING) << "Caught exception trying to set transient dictionary source: "
<< e.what();
return expr;
}
}
hdk::ir::ExprPtr cast_dict_to_none(const hdk::ir::ExprPtr& input) {
auto input_type = input->type();
if (input_type->isExtDictionary()) {
return input->cast(input_type->ctx().text(input_type->nullable()));
}
return input;
}
bool is_count_distinct(const hdk::ir::Expr* expr) {
const auto agg_expr = dynamic_cast<const hdk::ir::AggExpr*>(expr);
return agg_expr && agg_expr->isDistinct();
}
bool is_agg(const hdk::ir::Expr* expr) {
const auto agg_expr = dynamic_cast<const hdk::ir::AggExpr*>(expr);
if (agg_expr && agg_expr->containsAgg()) {
auto agg_type = agg_expr->aggType();
if (agg_type == hdk::ir::AggType::kMin || agg_type == hdk::ir::AggType::kMax ||
agg_type == hdk::ir::AggType::kSum || agg_type == hdk::ir::AggType::kAvg) {
return true;
}
}
return false;
}
const hdk::ir::Type* canonicalTypeForExpr(const hdk::ir::Expr& expr) {
if (is_count_distinct(&expr)) {
return expr.type()->ctx().int64();
}
auto res = expr.type()->canonicalize();
if (is_agg(&expr)) {
res = res->withNullable(true);
}
return res;
}
std::vector<hdk::ir::TargetMetaInfo> get_targets_meta(
const hdk::ir::Node* node,
const std::vector<const hdk::ir::Expr*>& target_exprs) {
std::vector<hdk::ir::TargetMetaInfo> targets_meta;
CHECK_EQ(node->size(), target_exprs.size());
for (size_t i = 0; i < node->size(); ++i) {
CHECK(target_exprs[i]);
// TODO(alex): remove the count distinct type fixup.
targets_meta.emplace_back(node->getFieldName(i),
canonicalTypeForExpr(*target_exprs[i]));
}
return targets_meta;
}
bool is_agg_step(const hdk::ir::Node* node) {
if (node->getResult() || node->is<hdk::ir::Scan>()) {
return false;
}
if (node->is<hdk::ir::Aggregate>()) {
return true;
}
if (auto shuffle = node->as<hdk::ir::Shuffle>()) {
return shuffle->isCount();
}
for (size_t i = 0; i < node->inputCount(); ++i) {
if (is_agg_step(node->getInput(i))) {
return true;
}
}
return false;
}
class NonGroupbyInputColIndicesCollector
: public hdk::ir::ExprCollector<std::set<unsigned>,
NonGroupbyInputColIndicesCollector> {
public:
NonGroupbyInputColIndicesCollector(const hdk::ir::Aggregate* agg) : agg_(agg){};
static std::set<unsigned> collect(const hdk::ir::Aggregate* agg) {
return BaseClass::collect(agg->getAggs(), agg);
}
protected:
void visitColumnRef(const hdk::ir::ColumnRef* col_ref) override {
if (col_ref->index() >= agg_->getGroupByCount()) {
result_.insert(col_ref->index());
}
}
const hdk::ir::Aggregate* agg_;
};
void buildUsedAggColumns(const hdk::ir::Aggregate* agg,
hdk::ir::ExprPtrVector& out_exprs,
std::vector<std::string>& out_fields,
std::unordered_map<unsigned, unsigned>& out_mapping) {
auto input = agg->getInput(0);
for (size_t i = 0; i < agg->getGroupByCount(); ++i) {
out_exprs.push_back(hdk::ir::getNodeColumnRef(input, static_cast<unsigned>(i)));
out_fields.push_back(input->getFieldName(i));
}
auto data_cols = NonGroupbyInputColIndicesCollector::collect(agg);
for (auto& idx : data_cols) {
out_mapping[idx] = static_cast<unsigned>(out_exprs.size());
out_exprs.push_back(hdk::ir::getNodeColumnRef(input, idx));
out_fields.push_back(input->getFieldName(idx));
}
}
// Check of node should be executed before shuffle can be applied to it.
// Shuffle goes in two passes and, due to lack of appropriate cost model,
// we prefer shuffle's input to be materialized. Exception is when it is
// a simple projection.
// TODO: enable more cases when cheap operation can be merged into shuffle.
bool shouldMaterializeShuffleInput(const hdk::ir::Node* node) {
if (node->getResult() || node->is<hdk::ir::Scan>()) {
return false;
}
auto proj = node->as<hdk::ir::Project>();
if (!proj) {
return true;
}
return !proj->isSimple() || shouldMaterializeShuffleInput(proj->getInput(0));
}
} // namespace
hdk::ir::ExprPtr set_transient_dict(const hdk::ir::ExprPtr expr) {
auto type = expr->type();
if (!type->isString()) {
return expr;
}
auto transient_dict_type = type->ctx().extDict(type, TRANSIENT_DICT_ID);
return expr->cast(transient_dict_type);
}
hdk::ir::ExprPtr translate(const hdk::ir::Expr* expr,
const RelAlgTranslator& translator,
::ExecutorType executor_type) {
auto res = translator.normalize(expr);
res = rewrite_array_elements(res.get());
res = rewrite_expr(res.get());
if (executor_type == ExecutorType::Native) {
// This is actually added to get full match of translated legacy
// rex expressions and new Exprs. It's done only for testing purposes
// and shouldn't have any effect on functionality and performance.
// TODO: remove when rex are not used anymore
if (auto* agg = dynamic_cast<const hdk::ir::AggExpr*>(res.get())) {
if (agg->arg()) {
auto new_arg = set_transient_dict_maybe(agg->argShared());
if (new_arg != agg->argShared()) {
res = hdk::ir::makeExpr<hdk::ir::AggExpr>(agg->type(),
agg->aggType(),
new_arg,
agg->isDistinct(),
agg->arg1Shared(),
agg->interpolation());
}
}
} else {
res = set_transient_dict_maybe(res);
}
} else {
res = cast_dict_to_none(fold_expr(res.get()));
}
return res;
}
void RelAlgExecutor::executeStepWithPartitionedAggregation(const hdk::ir::Node* step_root,
const CompilationOptions& co,
const ExecutionOptions& eo,
size_t estimated_buffer_size,
const int64_t queue_time_ms) {
auto sort = step_root->as<hdk::ir::Sort>();
auto agg = sort ? sort->getInput(0)->as<hdk::ir::Aggregate>()
: step_root->as<hdk::ir::Aggregate>();
CHECK(agg);
// Materialize data to shuffle if required.
auto agg_input = agg->getInput(0);
auto agg_input_shared = const_cast<hdk::ir::Aggregate*>(agg)->getAndOwnInput(0);
std::shared_ptr<hdk::ir::Project> proj;
std::unordered_map<unsigned, unsigned> input_map;
if (shouldMaterializeShuffleInput(agg_input)) {
// Make additional projection to possibly filter out unused columns (e.g. in
// case of join).
hdk::ir::ExprPtrVector exprs;
std::vector<std::string> fields;
buildUsedAggColumns(agg, exprs, fields, input_map);
proj = std::make_shared<hdk::ir::Project>(
std::move(exprs), std::move(fields), agg_input_shared);
VLOG(1) << "Materializing data for partitioning.";
executeStep(proj.get(), co, eo, queue_time_ms);
}
// Now that data to shuffle is materialized, we can start shuffling. As the first
// step, we compute the desired number of resulting partitions and compute their sizes.
// By default, we want to have enough partitions to load all cores but not to slow
// down partitioning too much by too many output streams.
size_t min_partitions = config_.exec.group_by.min_partitions
? config_.exec.group_by.min_partitions
: cpu_threads() * 2;
size_t max_partitions = std::max(config_.exec.group_by.max_partitions, min_partitions);
// For now, we require number of partitions to be power of 2 to avoid division
// operation in partitioning code.
min_partitions = shared::roundUpToPow2(min_partitions);
max_partitions = shared::roundUpToPow2(max_partitions);
size_t partitions = min_partitions;
// Increase number of partitions until we achieve target output buffer size or
// hit the partitioning limit.
while (partitions < max_partitions &&
estimated_buffer_size / partitions >
config_.exec.group_by.partitioning_buffer_target_size) {
partitions = partitions * 2;
}
VLOG(1) << "Selected to use " << partitions << " partitions. Used range is ["
<< min_partitions << ", " << max_partitions << "]. Estimated buffer size is "
<< estimated_buffer_size;
hdk::ir::ShuffleFunction shuffle_fn{hdk::ir::ShuffleFunction::kHash, partitions};
VLOG(1) << "Selected shuffle function is " << shuffle_fn;
hdk::ir::NodePtr shuffle_input = proj ? proj : agg_input_shared;
hdk::ir::ExprPtrVector shuffle_keys;
for (unsigned i = 0; i < static_cast<unsigned>(agg->getGroupByCount()); ++i) {
shuffle_keys.push_back(getNodeColumnRef(shuffle_input.get(), i));
}
hdk::ir::NodePtr count_shuffle_node = std::make_shared<hdk::ir::Shuffle>(
shuffle_keys,
hdk::ir::makeExpr<hdk::ir::AggExpr>(hdk::ir::Context::defaultCtx().int64(false),
hdk::ir::AggType::kCount,
nullptr,
false,
nullptr),
"part_size",
shuffle_fn,
shuffle_input);
VLOG(1) << "Execute COUNT(*) for data shuffle.";
{
auto timer = DEBUG_TIMER("Partitions histogram computation");
executeStep(
count_shuffle_node.get(), co, eo.with_columnar_output(true), queue_time_ms);
}
// With partition sizes now known, start actual data shuffling.
hdk::ir::ExprPtrVector shuffle_input_cols;
std::vector<std::string> fields;
if (proj) {
shuffle_input_cols = hdk::ir::getNodeColumnRefs(proj.get());
fields = proj->getFields();
} else {
hdk::ir::ExprPtrVector exprs;
buildUsedAggColumns(agg, shuffle_input_cols, fields, input_map);
}
hdk::ir::ExprPtrVector shuffle_exprs;
auto offsets_ref = hdk::ir::getNodeColumnRef(count_shuffle_node.get(), 0);
hdk::ir::NodePtr shuffle_node = std::make_shared<hdk::ir::Shuffle>(
std::move(shuffle_keys),
std::move(shuffle_input_cols),
std::move(fields),
shuffle_fn,
std::vector<hdk::ir::NodePtr>({shuffle_input, count_shuffle_node}));
VLOG(1) << "Execute data shuffle.";
auto shuffle_eo = eo;
shuffle_eo.output_columnar_hint = true;
shuffle_eo.preserve_order = false;
auto shuffle_co = co;
shuffle_co.allow_lazy_fetch = false;
{
auto timer = DEBUG_TIMER("Data shuffling");
executeStep(shuffle_node.get(), shuffle_co, shuffle_eo, queue_time_ms);
}
// Now we can remove projection and its result to free memory.
if (proj) {
temporary_tables_.erase(-proj->getId());
proj.reset();
}
// Currently, we merge shuffle node with simple projections only. Therefore, we can
// assign original table stats to shuffling results to avoid metadata computation.
maybeCopyTableStatsFromInput(shuffle_node.get());
// Create new aggregation node and execute it.
auto part_agg = std::make_shared<hdk::ir::Aggregate>(
agg->getGroupByCount(), agg->getAggs(), agg->getFields(), agg_input_shared);
part_agg->replaceInput(agg_input_shared, shuffle_node, input_map);
part_agg->setPartitioned(true);
// Use max partition size for a new entry count guess.
auto count_res_token = temporary_tables_.at(-count_shuffle_node->getId());
const uint64_t* size_buf = reinterpret_cast<const uint64_t*>(
count_res_token->resultSet(count_res_token->resultSetCount() - 1)
->getStorage()
->getUnderlyingBuffer());
auto max_partition_size = *std::max_element(size_buf, size_buf + partitions);
part_agg->setBufferEntryCountHint(max_partition_size * 2);
VLOG(1) << "Using buffer entry count hint for partitioned aggregation: "
<< part_agg->bufferEntryCountHint();
hdk::ir::NodePtr new_root = part_agg;
if (sort) {
new_root = sort->deepCopy();
new_root->replaceInput(new_root->getAndOwnInput(0), part_agg);
}
VLOG(1) << "Execute partitioned aggregation.";
{
auto timer = DEBUG_TIMER("Partitioned aggregation");
executeStep(new_root.get(), co, eo, queue_time_ms);
}
// Register result as a temporary table for the original node.
addTemporaryTable(-step_root->getId(), new_root->getResult()->getToken());
step_root->setResult(new_root->getResult());
// Remove temporary tables we don't need anymore.
temporary_tables_.erase(-count_shuffle_node->getId());
temporary_tables_.erase(-shuffle_node->getId());
temporary_tables_.erase(-part_agg->getId());
temporary_tables_.erase(-new_root->getId());
}
void RelAlgExecutor::maybeCopyTableStatsFromInput(const hdk::ir::Node* node) {
std::vector<int> col_mapping;
col_mapping.reserve(node->size());
// Stats copy is supported for shuffle and simple projections only.
if (node->is<hdk::ir::Project>()) {
auto proj = node->as<hdk::ir::Project>();
if (!proj->isSimple()) {
VLOG(1) << "Cannot copy table stats for non-simple projection.";
return;
}
for (auto& expr : proj->getExprs()) {
col_mapping.push_back(expr->as<hdk::ir::ColumnRef>()->index());
}
} else if (node->is<hdk::ir::Shuffle>()) {
for (auto& expr : node->as<hdk::ir::Shuffle>()->exprs()) {
CHECK(expr->is<hdk::ir::ColumnRef>());
col_mapping.push_back(expr->as<hdk::ir::ColumnRef>()->index());
}
} else {
VLOG(1) << "Cannot copy table stats for node " << node->toString();
return;
}
// We can traverse through a chain of simple projections to the original data source.
auto data_source = node->getInput(0);
while (!data_source->getResult() && !data_source->is<hdk::ir::Scan>()) {
auto proj = data_source->as<hdk::ir::Project>();
if (!proj || !proj->isSimple()) {
VLOG(1) << "Cannot copy table stats due to non-simple projection. "
<< node->toString();
return;
}
for (size_t i = 0; i < col_mapping.size(); ++i) {
auto idx = static_cast<size_t>(col_mapping[i]);
CHECK_LT(idx, proj->size());
col_mapping[i] = proj->getExpr(idx)->as<hdk::ir::ColumnRef>()->index();
}
data_source = data_source->getInput(0);
}
auto input_token =
data_source->getResult() ? data_source->getResult()->getToken().get() : nullptr;
auto input_scan = data_source->getResult() ? nullptr : data_source->as<hdk::ir::Scan>();
int input_db_id = input_token ? input_token->dbId() : input_scan->getDatabaseId();
int input_table_id = input_token ? input_token->tableId() : input_scan->getTableId();
auto input_meta = data_provider_->getTableMetadata(input_db_id, input_table_id);
if (input_meta.hasComputedTableStats()) {
auto& orig_stats = input_meta.getTableStats();
auto target_token = node->getResult()->getToken();
TableStats stats;
for (size_t i = 0; i < col_mapping.size(); ++i) {
auto target_col_id = target_token->columnId(i);
auto input_col_id = input_token
? input_token->columnId(col_mapping[i])
: input_scan->getColumnInfo(col_mapping[i])->column_id;
CHECK(orig_stats.count(input_col_id))
<< "Cannot find stats for column " << input_col_id
<< ". data_source=" << data_source->toString();
stats.emplace(target_col_id, orig_stats.at(input_col_id));
}
target_token->setTableStats(std::move(stats));
VLOG(1) << "Copy table stats from " << input_db_id << ":" << input_table_id << " to "
<< target_token->dbId() << ":" << target_token->tableId();
} else {
VLOG(1) << "Cannot copy table stats because original table stats are unavailable.";
}
}
void RelAlgExecutor::executeStep(const hdk::ir::Node* step_root,
const CompilationOptions& co,
const ExecutionOptions& eo,
const int64_t queue_time_ms) {
VLOG(1) << "Executing query step:\n" << treeToString(step_root, true);
ExecutionResult res;
try {
// TODO: move allow_speculative_sort to ExecutionOptions?
res = executeStep(step_root, co, eo, queue_time_ms, true);
} catch (const SpeculativeTopNFailed& e) {
VLOG(1) << "Retrying step with disabled speculative TopN.";
res = executeStep(step_root, co, eo, queue_time_ms, false);
}
auto shared_res = std::make_shared<ExecutionResult>(std::move(res));
step_root->setResult(shared_res);
// Logical values are always executed and ignore just_explain flag.
if (!eo.just_explain || step_root->is<hdk::ir::LogicalValues>()) {
addTemporaryTable(-step_root->getId(), shared_res->getToken());
}
}
ExecutionResult RelAlgExecutor::executeStep(const hdk::ir::Node* step_root,
const CompilationOptions& co,
const ExecutionOptions& eo,
const int64_t queue_time_ms,
bool allow_speculative_sort) {
auto timer = DEBUG_TIMER(__func__);
WindowProjectNodeContext::reset(executor_);
// Currently, table functions and UNION ALL nodes are not merged
// with other nodes. We don't use WorkUnitBuilder for them.
if (auto logical_values = step_root->as<hdk::ir::LogicalValues>()) {
return executeLogicalValues(logical_values, eo);
}
WorkUnit work_unit = createWorkUnit(step_root, co, eo, allow_speculative_sort);
auto sort = step_root->as<hdk::ir::Sort>();
ExecutionOptions eo_with_limit =
eo.with_just_validate(eo.just_validate || (sort && sort->isEmptyResult()));
// Use additional result fragments sort for UNION ALL case.
// Detect it via a check for two outer tables in the input
// descriptors vector.
if (work_unit.exe_unit.input_descs.size() >= 2 &&
work_unit.exe_unit.input_descs[0].getNestLevel() ==
work_unit.exe_unit.input_descs[1].getNestLevel()) {
eo_with_limit = eo_with_limit.with_preserve_order(true);
}
bool cpu_only = false;
if (auto project = step_root->as<hdk::ir::Project>()) {
if (project->isSimple()) {
const auto input_node = project->getInput(0);
if (input_node->is<hdk::ir::Sort>()) {
cpu_only = true;
// TODO: why do we need scan limit here?
auto token = get_temporary_table(&temporary_tables_, -input_node->getId());
work_unit.exe_unit.scan_limit = token->rowCount();
}
}
}
// Request single ResultSet in the resulting table if we are going to sort it.
if (sort) {
eo_with_limit.multifrag_result = false;
}
auto res = executeWorkUnit(work_unit,
step_root->getOutputMetainfo(),
is_agg_step(step_root),
cpu_only ? CompilationOptions::makeCpuOnly(co) : co,
eo_with_limit,
queue_time_ms);
if (sort) {
if (res.isFilterPushDownEnabled()) {
return res;
}
auto rows_to_sort = res.getRows();
if (eo.just_explain) {
return res;
}
const size_t limit = sort->getLimit();
const size_t offset = sort->getOffset();
if (sort->collationCount() != 0 && !rows_to_sort->definitelyHasNoRows() &&
!use_speculative_top_n(work_unit.exe_unit, rows_to_sort->getQueryMemDesc())) {
const size_t top_n = limit == 0 ? 0 : limit + offset;
sortResultSet(rows_to_sort.get(),
work_unit.exe_unit.sort_info.order_entries,
top_n,
executor_);
}
if (limit || offset) {
rows_to_sort->dropFirstN(offset);