forked from heavyai/heavydb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExecute.cpp
More file actions
5711 lines (5333 loc) · 234 KB
/
Execute.cpp
File metadata and controls
5711 lines (5333 loc) · 234 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 2022 HEAVY.AI, 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 "QueryEngine/Execute.h"
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#ifdef HAVE_CUDA
#include <cuda.h>
#endif // HAVE_CUDA
#include <RexVisitor.h>
#include <chrono>
#include <ctime>
#include <future>
#include <memory>
#include <mutex>
#include <numeric>
#include <set>
#include <thread>
#include <type_traits>
#include "Catalog/Catalog.h"
#include "CudaMgr/CudaMgr.h"
#include "DataMgr/BufferMgr/BufferMgr.h"
#include "DataMgr/ForeignStorage/FsiChunkUtils.h"
#include "OSDependent/heavyai_path.h"
#include "Parser/ParserNode.h"
#include "QueryEngine/AggregateUtils.h"
#include "QueryEngine/AggregatedColRange.h"
#include "QueryEngine/CodeGenerator.h"
#include "QueryEngine/ColumnFetcher.h"
#include "QueryEngine/Descriptors/QueryCompilationDescriptor.h"
#include "QueryEngine/Descriptors/QueryFragmentDescriptor.h"
#include "QueryEngine/ErrorHandling.h"
#include "QueryEngine/ExecutorResourceMgr/ExecutorResourceMgr.h"
#include "QueryEngine/ExpressionRewrite.h"
#include "QueryEngine/ExternalCacheInvalidators.h"
#include "QueryEngine/JoinHashTable/BaselineJoinHashTable.h"
#include "QueryEngine/OutputBufferInitialization.h"
#include "QueryEngine/QueryDispatchQueue.h"
#include "QueryEngine/QueryEngine.h"
#include "QueryEngine/QueryRewrite.h"
#include "QueryEngine/QueryTemplateGenerator.h"
#include "QueryEngine/RelAlgDag.h"
#include "QueryEngine/ResultSetReductionJIT.h"
#include "QueryEngine/RuntimeFunctions.h"
#include "QueryEngine/SpeculativeTopN.h"
#include "QueryEngine/StringDictionaryGenerations.h"
#include "QueryEngine/TableFunctions/TableFunctionCompilationContext.h"
#include "QueryEngine/TableFunctions/TableFunctionExecutionContext.h"
#include "QueryEngine/Utils/SerializeLiterals.h"
#include "QueryEngine/Visitors/TransientStringLiteralsVisitor.h"
#include "Shared/SystemParameters.h"
#include "Shared/TypedDataAccessors.h"
#include "Shared/measure.h"
#include "Shared/misc.h"
#include "Shared/scope.h"
#include "Shared/threading.h"
bool g_enable_watchdog{false};
bool g_enable_dynamic_watchdog{false};
size_t g_watchdog_none_encoded_string_translation_limit{1000000UL};
size_t g_watchdog_max_projected_rows_per_device{128000000};
size_t g_preflight_count_query_threshold{1000000};
size_t g_watchdog_in_clause_max_num_elem_non_bitmap{10000};
size_t g_watchdog_in_clause_max_num_elem_bitmap{1 << 25};
size_t g_watchdog_in_clause_max_num_input_rows{5000000};
size_t g_in_clause_num_elem_skip_bitmap{100};
bool g_enable_cpu_sub_tasks{false};
size_t g_cpu_sub_task_size{500'000};
bool g_enable_filter_function{true};
unsigned g_dynamic_watchdog_time_limit{10000};
bool g_allow_cpu_retry{true};
bool g_allow_query_step_cpu_retry{true};
bool g_null_div_by_zero{false};
unsigned g_trivial_loop_join_threshold{1000};
bool g_from_table_reordering{true};
bool g_inner_join_fragment_skipping{true};
extern bool g_enable_smem_group_by;
extern std::unique_ptr<llvm::Module> udf_gpu_module;
extern std::unique_ptr<llvm::Module> udf_cpu_module;
bool g_enable_filter_push_down{false};
float g_filter_push_down_max_selectivity{0.1f};
size_t g_filter_push_down_selectivity_override_max_passing_num_rows{4000000};
bool g_enable_columnar_output{false};
bool g_enable_left_join_filter_hoisting{true};
bool g_optimize_row_initialization{true};
bool g_enable_bbox_intersect_hashjoin{true};
size_t g_ratio_num_hash_entry_to_num_tuple_switch_to_baseline{100};
bool g_enable_distance_rangejoin{true};
bool g_enable_hashjoin_many_to_many{true};
size_t g_bbox_intersect_max_table_size_bytes{1024 * 1024 * 1024};
double g_bbox_intersect_target_entries_per_bin{1.3};
bool g_strip_join_covered_quals{false};
size_t g_constrained_by_in_threshold{10};
size_t g_default_max_groups_buffer_entry_guess{16384};
size_t g_big_group_threshold{g_default_max_groups_buffer_entry_guess};
size_t g_baseline_groupby_threshold{
1000000}; // if a perfect hash needs more entries, use baseline
bool g_enable_window_functions{true};
bool g_enable_table_functions{true};
bool g_enable_ml_functions{true};
bool g_restrict_ml_model_metadata_to_superusers{false};
bool g_enable_dev_table_functions{false};
bool g_enable_geo_ops_on_uncompressed_coords{true};
bool g_enable_rf_prop_table_functions{true};
bool g_allow_memory_status_log{true};
size_t g_max_memory_allocation_size{2000000000}; // set to max slab size
size_t g_min_memory_allocation_size{
256}; // minimum memory allocation required for projection query output buffer
// without pre-flight count
bool g_enable_bump_allocator{false};
double g_bump_allocator_step_reduction{0.75};
bool g_enable_direct_columnarization{true};
extern bool g_enable_string_functions;
bool g_enable_lazy_fetch{true};
bool g_enable_runtime_query_interrupt{true};
bool g_enable_non_kernel_time_query_interrupt{true};
bool g_use_estimator_result_cache{true};
unsigned g_pending_query_interrupt_freq{1000};
double g_running_query_interrupt_freq{0.1};
size_t g_gpu_smem_threshold{
0}; // GPU shared memory threshold (in bytes).
// If larger buffer sizes are required we do not use GPU shared
// memory optimizations. Setting this to 0 means unlimited
// (subject to other dynamically calculated caps).
bool g_enable_smem_grouped_non_count_agg{
true}; // enable use of shared memory when performing group-by with select non-count
// aggregates
bool g_enable_smem_non_grouped_agg{
true}; // enable optimizations for using GPU shared memory in implementation of
// non-grouped aggregates
bool g_is_test_env{false}; // operating under a unit test environment. Currently only
// limits the allocation for the output buffer arena
// and data recycler test
size_t g_enable_parallel_linearization{
10000}; // # rows that we are trying to linearize varlen col in parallel
bool g_enable_data_recycler{true};
bool g_use_hashtable_cache{true};
bool g_use_query_resultset_cache{true};
bool g_use_chunk_metadata_cache{true};
bool g_allow_auto_resultset_caching{false};
bool g_allow_query_step_skipping{true};
size_t g_hashtable_cache_total_bytes{size_t(1) << 32};
size_t g_max_cacheable_hashtable_size_bytes{size_t(1) << 31};
size_t g_query_resultset_cache_total_bytes{size_t(1) << 32};
size_t g_max_cacheable_query_resultset_size_bytes{size_t(1) << 31};
size_t g_auto_resultset_caching_threshold{size_t(1) << 20};
bool g_optimize_cuda_block_and_grid_sizes{false};
size_t g_approx_quantile_buffer{1000};
size_t g_approx_quantile_centroids{300};
bool g_enable_automatic_ir_metadata{true};
size_t g_max_log_length{500};
bool g_enable_executor_resource_mgr{true};
double g_executor_resource_mgr_cpu_result_mem_ratio{0.8};
size_t g_executor_resource_mgr_cpu_result_mem_bytes{Executor::auto_cpu_mem_bytes};
double g_executor_resource_mgr_per_query_max_cpu_slots_ratio{0.9};
double g_executor_resource_mgr_per_query_max_cpu_result_mem_ratio{0.8};
// Todo: rework ConcurrentResourceGrantPolicy and ExecutorResourcePool to allow
// thresholds for concurrent oversubscription, rather than just boolean allowed/disallowed
bool g_executor_resource_mgr_allow_cpu_kernel_concurrency{true};
bool g_executor_resource_mgr_allow_cpu_gpu_kernel_concurrency{true};
// Whether a single query can oversubscribe CPU slots should be controlled with
// g_executor_resource_mgr_per_query_max_cpu_slots_ratio
bool g_executor_resource_mgr_allow_cpu_slot_oversubscription_concurrency{false};
// Whether a single query can oversubscribe CPU memory should be controlled with
// g_executor_resource_mgr_per_query_max_cpu_slots_ratio
bool g_executor_resource_mgr_allow_cpu_result_mem_oversubscription_concurrency{false};
double g_executor_resource_mgr_max_available_resource_use_ratio{0.8};
bool g_executor_resource_mgr_allow_auto_shrink_num_cpu_slot_for_groupby_query{true};
bool g_use_cpu_mem_pool_for_output_buffers{true};
extern bool g_cache_string_hash;
extern bool g_allow_memory_status_log;
int const Executor::max_gpu_count;
int g_max_num_gpu_per_query{0};
int Executor::last_selected_device_id_{0};
std::mutex Executor::last_selected_device_id_mutex_;
std::map<Executor::ExtModuleKinds, std::string> Executor::extension_module_sources;
extern std::unique_ptr<llvm::Module> read_llvm_module_from_bc_file(
const std::string& udf_ir_filename,
llvm::LLVMContext& ctx);
extern std::unique_ptr<llvm::Module> read_llvm_module_from_ir_file(
const std::string& udf_ir_filename,
llvm::LLVMContext& ctx,
bool is_gpu = false);
extern std::unique_ptr<llvm::Module> read_llvm_module_from_ir_string(
const std::string& udf_ir_string,
llvm::LLVMContext& ctx,
bool is_gpu = false);
namespace {
// This function is notably different from that in RelAlgExecutor because it already
// expects SPI values and therefore needs to avoid that transformation.
void prepare_string_dictionaries(const std::unordered_set<PhysicalInput>& phys_inputs) {
for (const auto [col_id, table_id, db_id] : phys_inputs) {
foreign_storage::populate_string_dictionary(table_id, col_id, db_id);
}
}
bool is_empty_table(Fragmenter_Namespace::AbstractFragmenter* fragmenter) {
const auto& fragments = fragmenter->getFragmentsForQuery().fragments;
// The fragmenter always returns at least one fragment, even when the table is empty.
return (fragments.size() == 1 && fragments[0].getChunkMetadataMap().empty());
}
size_t determineMaxCpuSlabSize(DataMgr* data_mgr, size_t default_max_cpu_slab_size) {
if (data_mgr) {
return data_mgr->getCpuBufferMgr()->getMaxSlabSize();
}
return default_max_cpu_slab_size;
}
} // namespace
namespace foreign_storage {
// Foreign tables skip the population of dictionaries during metadata scan. This function
// will populate a dictionary's missing entries by fetching any unpopulated chunks.
void populate_string_dictionary(int32_t table_id, int32_t col_id, int32_t db_id) {
const auto catalog = Catalog_Namespace::SysCatalog::instance().getCatalog(db_id);
CHECK(catalog);
if (const auto foreign_table = dynamic_cast<const ForeignTable*>(
catalog->getMetadataForTable(table_id, false))) {
const auto col_desc = catalog->getMetadataForColumn(table_id, col_id);
if (col_desc->columnType.is_dict_encoded_type()) {
auto& fragmenter = foreign_table->fragmenter;
CHECK(fragmenter != nullptr);
if (is_empty_table(fragmenter.get())) {
return;
}
for (const auto& frag : fragmenter->getFragmentsForQuery().fragments) {
ChunkKey chunk_key = {db_id, table_id, col_id, frag.fragmentId};
// If the key is sharded across leaves, only populate fragments that are sharded
// to this leaf.
if (key_does_not_shard_to_leaf(chunk_key)) {
continue;
}
const ChunkMetadataMap& metadata_map = frag.getChunkMetadataMap();
CHECK(metadata_map.find(col_id) != metadata_map.end());
if (auto& meta = metadata_map.at(col_id); meta->isPlaceholder()) {
// When this goes out of scope it will stay in CPU cache but become
// evictable
auto chunk = Chunk_NS::Chunk::getChunk(col_desc,
&(catalog->getDataMgr()),
chunk_key,
Data_Namespace::CPU_LEVEL,
0,
0,
0);
}
}
}
}
}
} // namespace foreign_storage
Executor::Executor(const ExecutorId executor_id,
Data_Namespace::DataMgr* data_mgr,
const size_t block_size_x,
const size_t grid_size_x,
const size_t max_cpu_slab_size,
const size_t max_gpu_slab_size,
const std::string& debug_dir,
const std::string& debug_file)
: executor_id_(executor_id)
, context_(new llvm::LLVMContext())
, cgen_state_(new CgenState({}, false, this))
, block_size_x_(block_size_x)
, grid_size_x_(grid_size_x)
, max_cpu_slab_size_(determineMaxCpuSlabSize(data_mgr, max_cpu_slab_size))
, max_gpu_slab_size_(max_gpu_slab_size)
, debug_dir_(debug_dir)
, debug_file_(debug_file)
, data_mgr_(data_mgr)
, temporary_tables_(nullptr)
, input_table_info_cache_(this) {
Executor::initialize_extension_module_sources();
update_extension_modules();
}
void Executor::initialize_extension_module_sources() {
if (Executor::extension_module_sources.find(
Executor::ExtModuleKinds::template_module) ==
Executor::extension_module_sources.end()) {
auto root_path = heavyai::get_root_abs_path();
auto template_path = root_path + "/QueryEngine/RuntimeFunctions.bc";
CHECK(boost::filesystem::exists(template_path));
Executor::extension_module_sources[Executor::ExtModuleKinds::template_module] =
template_path;
#ifdef ENABLE_GEOS
auto rt_geos_path = root_path + "/QueryEngine/GeosRuntime.bc";
CHECK(boost::filesystem::exists(rt_geos_path));
Executor::extension_module_sources[Executor::ExtModuleKinds::rt_geos_module] =
rt_geos_path;
#endif
auto rt_h3_path = root_path + "/QueryEngine/H3Runtime.bc";
CHECK(boost::filesystem::exists(rt_h3_path));
Executor::extension_module_sources[Executor::ExtModuleKinds::rt_h3_module] =
rt_h3_path;
#ifdef HAVE_CUDA
auto rt_libdevice_path = get_cuda_libdevice_dir() + "/libdevice.10.bc";
if (boost::filesystem::exists(rt_libdevice_path)) {
Executor::extension_module_sources[Executor::ExtModuleKinds::rt_libdevice_module] =
rt_libdevice_path;
} else {
LOG(WARNING) << "File " << rt_libdevice_path
<< " does not exist; support for some UDF "
"functions might not be available.";
}
#endif
}
}
void Executor::reset(bool discard_runtime_modules_only) {
// TODO: keep cached results that do not depend on runtime UDF/UDTFs
auto qe = QueryEngine::getInstance();
qe->s_code_accessor->clear();
qe->s_stubs_accessor->clear();
qe->cpu_code_accessor->clear();
qe->gpu_code_accessor->clear();
qe->tf_code_accessor->clear();
if (discard_runtime_modules_only) {
extension_modules_.erase(Executor::ExtModuleKinds::rt_udf_cpu_module);
#ifdef HAVE_CUDA
extension_modules_.erase(Executor::ExtModuleKinds::rt_udf_gpu_module);
#endif
cgen_state_->module_ = nullptr;
} else {
extension_modules_.clear();
cgen_state_.reset();
context_.reset(new llvm::LLVMContext());
cgen_state_.reset(new CgenState({}, false, this));
}
}
void Executor::update_extension_modules(bool update_runtime_modules_only) {
auto read_module = [&](Executor::ExtModuleKinds module_kind,
const std::string& source) {
/*
source can be either a filename of a LLVM IR
or LLVM BC source, or a string containing
LLVM IR code.
*/
CHECK(!source.empty());
switch (module_kind) {
case Executor::ExtModuleKinds::template_module:
case Executor::ExtModuleKinds::rt_geos_module:
case Executor::ExtModuleKinds::rt_h3_module:
case Executor::ExtModuleKinds::rt_libdevice_module: {
return read_llvm_module_from_bc_file(source, getContext());
}
case Executor::ExtModuleKinds::udf_cpu_module: {
return read_llvm_module_from_ir_file(source, getContext(), /**is_gpu=*/false);
}
case Executor::ExtModuleKinds::udf_gpu_module: {
return read_llvm_module_from_ir_file(source, getContext(), /**is_gpu=*/true);
}
case Executor::ExtModuleKinds::rt_udf_cpu_module: {
return read_llvm_module_from_ir_string(source, getContext(), /**is_gpu=*/false);
}
case Executor::ExtModuleKinds::rt_udf_gpu_module: {
return read_llvm_module_from_ir_string(source, getContext(), /**is_gpu=*/true);
}
default: {
UNREACHABLE();
return std::unique_ptr<llvm::Module>();
}
}
};
auto update_module = [&](Executor::ExtModuleKinds module_kind,
bool erase_not_found = false) {
auto it = Executor::extension_module_sources.find(module_kind);
if (it != Executor::extension_module_sources.end()) {
auto llvm_module = read_module(module_kind, it->second);
if (llvm_module) {
extension_modules_[module_kind] = std::move(llvm_module);
} else if (erase_not_found) {
extension_modules_.erase(module_kind);
} else {
if (extension_modules_.find(module_kind) == extension_modules_.end()) {
LOG(WARNING) << "Failed to update " << ::toString(module_kind)
<< " LLVM module. The module will be unavailable.";
} else {
LOG(WARNING) << "Failed to update " << ::toString(module_kind)
<< " LLVM module. Using the existing module.";
}
}
} else {
if (erase_not_found) {
extension_modules_.erase(module_kind);
} else {
if (extension_modules_.find(module_kind) == extension_modules_.end()) {
LOG(WARNING) << "Source of " << ::toString(module_kind)
<< " LLVM module is unavailable. The module will be unavailable.";
} else {
LOG(WARNING) << "Source of " << ::toString(module_kind)
<< " LLVM module is unavailable. Using the existing module.";
}
}
}
};
if (!update_runtime_modules_only) {
// required compile-time modules, their requirements are enforced
// by Executor::initialize_extension_module_sources():
update_module(Executor::ExtModuleKinds::template_module);
#ifdef ENABLE_GEOS
update_module(Executor::ExtModuleKinds::rt_geos_module);
#endif
update_module(Executor::ExtModuleKinds::rt_h3_module);
// load-time modules, these are optional:
update_module(Executor::ExtModuleKinds::udf_cpu_module, true);
#ifdef HAVE_CUDA
update_module(Executor::ExtModuleKinds::udf_gpu_module, true);
update_module(Executor::ExtModuleKinds::rt_libdevice_module);
#endif
}
// run-time modules, these are optional and erasable:
update_module(Executor::ExtModuleKinds::rt_udf_cpu_module, true);
#ifdef HAVE_CUDA
update_module(Executor::ExtModuleKinds::rt_udf_gpu_module, true);
#endif
}
// Used by StubGenerator::generateStub
Executor::CgenStateManager::CgenStateManager(Executor& executor)
: executor_(executor)
, lock_queue_clock_(timer_start())
, lock_(executor_.compilation_mutex_)
, cgen_state_(std::move(executor_.cgen_state_)) // store old CgenState instance
{
executor_.compilation_queue_time_ms_ += timer_stop(lock_queue_clock_);
executor_.cgen_state_.reset(new CgenState(0, false, &executor));
}
Executor::CgenStateManager::CgenStateManager(
Executor& executor,
const bool allow_lazy_fetch,
const std::vector<InputTableInfo>& query_infos,
const PlanState::DeletedColumnsMap& deleted_cols_map,
const RelAlgExecutionUnit* ra_exe_unit)
: executor_(executor)
, lock_queue_clock_(timer_start())
, lock_(executor_.compilation_mutex_)
, cgen_state_(std::move(executor_.cgen_state_)) // store old CgenState instance
{
executor_.compilation_queue_time_ms_ += timer_stop(lock_queue_clock_);
// nukeOldState creates new CgenState and PlanState instances for
// the subsequent code generation. It also resets
// kernel_queue_time_ms_ and compilation_queue_time_ms_ that we do
// not currently restore.. should we accumulate these timings?
executor_.nukeOldState(allow_lazy_fetch, query_infos, deleted_cols_map, ra_exe_unit);
}
Executor::CgenStateManager::~CgenStateManager() {
// prevent memory leak from hoisted literals
for (auto& p : executor_.cgen_state_->row_func_hoisted_literals_) {
auto inst = llvm::dyn_cast<llvm::LoadInst>(p.first);
if (inst && inst->getNumUses() == 0 && inst->getParent() == nullptr) {
// The llvm::Value instance stored in p.first is created by the
// CodeGenerator::codegenHoistedConstantsPlaceholders method.
p.first->deleteValue();
}
}
executor_.cgen_state_->row_func_hoisted_literals_.clear();
// move generated StringDictionaryTranslationMgrs and InValueBitmaps
// to the old CgenState instance as the execution of the generated
// code uses these bitmaps
for (auto& bm : executor_.cgen_state_->in_values_bitmaps_) {
cgen_state_->moveInValuesBitmap(bm);
}
executor_.cgen_state_->in_values_bitmaps_.clear();
for (auto& str_dict_translation_mgr :
executor_.cgen_state_->str_dict_translation_mgrs_) {
cgen_state_->moveStringDictionaryTranslationMgr(std::move(str_dict_translation_mgr));
}
executor_.cgen_state_->str_dict_translation_mgrs_.clear();
for (auto& tree_model_prediction_mgr :
executor_.cgen_state_->tree_model_prediction_mgrs_) {
cgen_state_->moveTreeModelPredictionMgr(std::move(tree_model_prediction_mgr));
}
executor_.cgen_state_->tree_model_prediction_mgrs_.clear();
// Delete worker module that may have been set by
// set_module_shallow_copy. If QueryMustRunOnCpu is thrown, the
// worker module is not instantiated, so the worker module needs to
// be deleted conditionally [see "Managing LLVM modules" comment in
// CgenState.h]:
if (executor_.cgen_state_->module_) {
delete executor_.cgen_state_->module_;
}
// restore the old CgenState instance
executor_.cgen_state_.reset(cgen_state_.release());
}
std::shared_ptr<Executor> Executor::getExecutor(
const ExecutorId executor_id,
const std::string& debug_dir,
const std::string& debug_file,
const SystemParameters& system_parameters) {
heavyai::unique_lock<heavyai::shared_mutex> write_lock(executors_cache_mutex_);
auto it = executors_.find(executor_id);
if (it != executors_.end()) {
return it->second;
}
auto& data_mgr = Catalog_Namespace::SysCatalog::instance().getDataMgr();
auto executor = std::make_shared<Executor>(executor_id,
&data_mgr,
system_parameters.cuda_block_size,
system_parameters.cuda_grid_size,
system_parameters.max_cpu_slab_size,
system_parameters.max_gpu_slab_size,
debug_dir,
debug_file);
CHECK(executors_.insert(std::make_pair(executor_id, executor)).second);
return executor;
}
void Executor::clearMemory(const Data_Namespace::MemoryLevel memory_level) {
switch (memory_level) {
case Data_Namespace::MemoryLevel::CPU_LEVEL:
case Data_Namespace::MemoryLevel::GPU_LEVEL: {
heavyai::unique_lock<heavyai::shared_mutex> flush_lock(
execute_mutex_); // Don't flush memory while queries are running
if (memory_level == Data_Namespace::MemoryLevel::CPU_LEVEL) {
// The hash table cache uses CPU memory not managed by the buffer manager. In the
// future, we should manage these allocations with the buffer manager directly.
// For now, assume the user wants to purge the hash table cache when they clear
// CPU memory (currently used in ExecuteTest to lower memory pressure)
// TODO: Move JoinHashTableCacheInvalidator to Executor::clearExternalCaches();
JoinHashTableCacheInvalidator::invalidateCaches();
}
Executor::clearExternalCaches(true, nullptr, 0);
Catalog_Namespace::SysCatalog::instance().getDataMgr().clearMemory(memory_level);
break;
}
default: {
throw std::runtime_error(
"Clearing memory levels other than the CPU level or GPU level is not "
"supported.");
}
}
}
size_t Executor::getArenaBlockSize() {
return g_is_test_env ? 100000000 : (1UL << 32) + kArenaBlockOverhead;
}
StringDictionaryProxy* Executor::getStringDictionaryProxy(
const shared::StringDictKey& dict_id_in,
std::shared_ptr<RowSetMemoryOwner> row_set_mem_owner,
const bool with_generation) const {
CHECK(row_set_mem_owner);
std::lock_guard<std::mutex> lock(
str_dict_mutex_); // TODO: can we use RowSetMemOwner state mutex here?
return row_set_mem_owner->getOrAddStringDictProxy(dict_id_in, with_generation);
}
StringDictionaryProxy* RowSetMemoryOwner::getOrAddStringDictProxy(
const shared::StringDictKey& dict_key_in,
const bool with_generation) {
if (dict_key_in.db_id < 0) {
// Temporary dictionaries should already be created and stored in the
// str_dict_proxy_owned_ map when this method is called.
auto it = str_dict_proxy_owned_.find(dict_key_in);
CHECK(it != str_dict_proxy_owned_.end());
return it->second.get();
}
const int dict_id{dict_key_in.dict_id < 0 ? REGULAR_DICT(dict_key_in.dict_id)
: dict_key_in.dict_id};
const auto catalog =
Catalog_Namespace::SysCatalog::instance().getCatalog(dict_key_in.db_id);
if (catalog) {
const auto dd = catalog->getMetadataForDict(dict_id);
if (dd) {
auto dict_key = dict_key_in;
dict_key.dict_id = dict_id;
CHECK(dd->stringDict);
CHECK_LE(dd->dictNBits, 32);
const int64_t generation =
with_generation ? string_dictionary_generations_.getGeneration(dict_key) : -1;
return addStringDict(dd->stringDict, dict_key, generation);
}
}
CHECK_EQ(dict_id, DictRef::literalsDictId);
if (!lit_str_dict_proxy_) {
DictRef literal_dict_ref(dict_key_in.db_id, DictRef::literalsDictId);
std::shared_ptr<StringDictionary> tsd = std::make_shared<StringDictionary>(
literal_dict_ref, "", false, true, g_cache_string_hash);
lit_str_dict_proxy_ = std::make_shared<StringDictionaryProxy>(
tsd, shared::StringDictKey{literal_dict_ref.dbId, literal_dict_ref.dictId}, 0);
}
return lit_str_dict_proxy_.get();
}
const StringDictionaryProxy::IdMap* Executor::getStringProxyTranslationMap(
const shared::StringDictKey& source_dict_key,
const shared::StringDictKey& dest_dict_key,
const RowSetMemoryOwner::StringTranslationType translation_type,
const std::vector<StringOps_Namespace::StringOpInfo>& string_op_infos,
std::shared_ptr<RowSetMemoryOwner> row_set_mem_owner,
const bool with_generation) const {
CHECK(row_set_mem_owner);
std::lock_guard<std::mutex> lock(
str_dict_mutex_); // TODO: can we use RowSetMemOwner state mutex here?
return row_set_mem_owner->getOrAddStringProxyTranslationMap(
source_dict_key, dest_dict_key, with_generation, translation_type, string_op_infos);
}
const StringDictionaryProxy::IdMap*
Executor::getJoinIntersectionStringProxyTranslationMap(
const StringDictionaryProxy* source_proxy,
StringDictionaryProxy* dest_proxy,
const std::vector<StringOps_Namespace::StringOpInfo>& source_string_op_infos,
const std::vector<StringOps_Namespace::StringOpInfo>& dest_string_op_infos,
std::shared_ptr<RowSetMemoryOwner> row_set_mem_owner) const {
CHECK(row_set_mem_owner);
std::lock_guard<std::mutex> lock(
str_dict_mutex_); // TODO: can we use RowSetMemOwner state mutex here?
// First translate lhs onto itself if there are string ops
if (!dest_string_op_infos.empty()) {
row_set_mem_owner->addStringProxyUnionTranslationMap(
dest_proxy, dest_proxy, dest_string_op_infos);
}
return row_set_mem_owner->addStringProxyIntersectionTranslationMap(
source_proxy, dest_proxy, source_string_op_infos);
}
const StringDictionaryProxy::TranslationMap<Datum>*
Executor::getStringProxyNumericTranslationMap(
const shared::StringDictKey& source_dict_key,
const std::vector<StringOps_Namespace::StringOpInfo>& string_op_infos,
std::shared_ptr<RowSetMemoryOwner> row_set_mem_owner,
const bool with_generation) const {
CHECK(row_set_mem_owner);
std::lock_guard<std::mutex> lock(
str_dict_mutex_); // TODO: can we use RowSetMemOwner state mutex here?
return row_set_mem_owner->getOrAddStringProxyNumericTranslationMap(
source_dict_key, with_generation, string_op_infos);
}
const StringDictionaryProxy::IdMap* RowSetMemoryOwner::getOrAddStringProxyTranslationMap(
const shared::StringDictKey& source_dict_key_in,
const shared::StringDictKey& dest_dict_key_in,
const bool with_generation,
const RowSetMemoryOwner::StringTranslationType translation_type,
const std::vector<StringOps_Namespace::StringOpInfo>& string_op_infos) {
const auto source_proxy = getOrAddStringDictProxy(source_dict_key_in, with_generation);
const auto dest_proxy = getOrAddStringDictProxy(dest_dict_key_in, with_generation);
if (translation_type == RowSetMemoryOwner::StringTranslationType::SOURCE_INTERSECTION) {
return addStringProxyIntersectionTranslationMap(
source_proxy, dest_proxy, string_op_infos);
} else {
return addStringProxyUnionTranslationMap(source_proxy, dest_proxy, string_op_infos);
}
}
const StringDictionaryProxy::TranslationMap<Datum>*
RowSetMemoryOwner::getOrAddStringProxyNumericTranslationMap(
const shared::StringDictKey& source_dict_key_in,
const bool with_generation,
const std::vector<StringOps_Namespace::StringOpInfo>& string_op_infos) {
const auto source_proxy = getOrAddStringDictProxy(source_dict_key_in, with_generation);
return addStringProxyNumericTranslationMap(source_proxy, string_op_infos);
}
quantile::TDigest* RowSetMemoryOwner::initTDigest(size_t const thread_idx,
ApproxQuantileDescriptor const desc,
double const q) {
static_assert(std::is_trivially_copyable_v<ApproxQuantileDescriptor>);
std::lock_guard<std::mutex> lock(state_mutex_);
auto t_digest = std::make_unique<quantile::TDigest>(
q, &t_digest_allocators_[thread_idx], desc.buffer_size, desc.centroids_size);
return t_digests_.emplace_back(std::move(t_digest)).get();
}
void RowSetMemoryOwner::reserveTDigestMemory(size_t thread_idx, size_t capacity) {
std::unique_lock<std::mutex> lock(state_mutex_);
if (t_digest_allocators_.size() <= thread_idx) {
t_digest_allocators_.resize(thread_idx + 1u);
}
if (t_digest_allocators_[thread_idx].capacity()) {
// This can only happen when a thread_idx is re-used. In other words,
// two or more kernels have launched (serially!) using the same thread_idx.
// This is ok since TDigestAllocator does not own the memory it allocates.
VLOG(2) << "Replacing t_digest_allocators_[" << thread_idx << "].";
}
lock.unlock();
// This is not locked due to use of same state_mutex_ during allocation.
// The corresponding deallocation happens in ~DramArena().
int8_t* const buffer = allocate(capacity, thread_idx);
lock.lock();
t_digest_allocators_[thread_idx] = TDigestAllocator(buffer, capacity);
}
bool Executor::isCPUOnly() const {
CHECK(data_mgr_);
return !data_mgr_->getCudaMgr();
}
const ColumnDescriptor* Executor::getColumnDescriptor(
const Analyzer::ColumnVar* col_var) const {
return get_column_descriptor_maybe(col_var->getColumnKey());
}
const ColumnDescriptor* Executor::getPhysicalColumnDescriptor(
const Analyzer::ColumnVar* col_var,
int n) const {
const auto cd = getColumnDescriptor(col_var);
if (!cd || n > cd->columnType.get_physical_cols()) {
return nullptr;
}
auto column_key = col_var->getColumnKey();
column_key.column_id += n;
return get_column_descriptor_maybe(column_key);
}
const std::shared_ptr<RowSetMemoryOwner> Executor::getRowSetMemoryOwner() const {
return row_set_mem_owner_;
}
const TemporaryTables* Executor::getTemporaryTables() const {
return temporary_tables_;
}
Fragmenter_Namespace::TableInfo Executor::getTableInfo(
const shared::TableKey& table_key) const {
return input_table_info_cache_.getTableInfo(table_key);
}
const TableGeneration& Executor::getTableGeneration(
const shared::TableKey& table_key) const {
return table_generations_.getGeneration(table_key);
}
ExpressionRange Executor::getColRange(const PhysicalInput& phys_input) const {
return agg_col_range_cache_.getColRange(phys_input);
}
namespace {
void log_system_memory_info_impl(std::string const& mem_log,
size_t executor_id,
size_t log_time_ms,
std::string const& log_tag,
size_t const thread_idx) {
std::ostringstream oss;
oss << mem_log;
oss << " (" << log_tag << ", EXECUTOR-" << executor_id << ", THREAD-" << thread_idx
<< ", TOOK: " << log_time_ms << " ms)";
VLOG(1) << oss.str();
}
} // namespace
void Executor::logSystemCPUMemoryStatus(std::string const& log_tag,
size_t const thread_idx) const {
if (g_allow_memory_status_log && getDataMgr()) {
auto timer = timer_start();
std::ostringstream oss;
oss << getDataMgr()->getSystemMemoryUsage();
log_system_memory_info_impl(
oss.str(), executor_id_, timer_stop(timer), log_tag, thread_idx);
}
}
void Executor::logSystemGPUMemoryStatus(std::string const& log_tag,
size_t const thread_idx) const {
#ifdef HAVE_CUDA
if (g_allow_memory_status_log && getDataMgr() && getDataMgr()->gpusPresent() &&
getDataMgr()->getCudaMgr()) {
auto timer = timer_start();
auto mem_log = getDataMgr()->getCudaMgr()->getCudaMemoryUsageInString();
log_system_memory_info_impl(
mem_log, executor_id_, timer_stop(timer), log_tag, thread_idx);
}
#endif
}
namespace {
size_t get_col_byte_width(const shared::ColumnKey& column_key) {
if (column_key.table_id < 0) {
// We have an intermediate results table
// Todo(todd): Get more accurate representation of column width
// for intermediate tables
return size_t(8);
} else {
const auto cd = Catalog_Namespace::get_metadata_for_column(column_key);
const auto& ti = cd->columnType;
const auto sz = ti.get_size();
if (sz < 0) {
// for varlen types, only account for the pointer/size for each row, for now
if (ti.is_logical_geo_type()) {
// Don't count size for logical geo types, as they are
// backed by physical columns
return size_t(0);
} else {
return size_t(16);
}
} else {
return sz;
}
}
}
} // anonymous namespace
std::map<shared::ColumnKey, size_t> Executor::getColumnByteWidthMap(
const std::set<shared::TableKey>& table_ids_to_fetch,
const bool include_lazy_fetched_cols) const {
std::map<shared::ColumnKey, size_t> col_byte_width_map;
for (const auto& fetched_col : plan_state_->getColumnsToFetch()) {
if (table_ids_to_fetch.count({fetched_col.db_id, fetched_col.table_id}) == 0) {
continue;
}
const size_t col_byte_width = get_col_byte_width(fetched_col);
CHECK(col_byte_width_map.insert({fetched_col, col_byte_width}).second);
}
if (include_lazy_fetched_cols) {
for (const auto& lazy_fetched_col : plan_state_->getColumnsToNotFetch()) {
if (table_ids_to_fetch.count({lazy_fetched_col.db_id, lazy_fetched_col.table_id}) ==
0) {
continue;
}
const size_t col_byte_width = get_col_byte_width(lazy_fetched_col);
CHECK(col_byte_width_map.insert({lazy_fetched_col, col_byte_width}).second);
}
}
return col_byte_width_map;
}
size_t Executor::getNumBytesForFetchedRow(
const std::set<shared::TableKey>& table_ids_to_fetch) const {
size_t num_bytes = 0;
if (!plan_state_) {
return 0;
}
for (const auto& fetched_col : plan_state_->getColumnsToFetch()) {
if (table_ids_to_fetch.count({fetched_col.db_id, fetched_col.table_id}) == 0) {
continue;
}
if (fetched_col.table_id < 0) {
num_bytes += 8;
} else {
const auto cd = Catalog_Namespace::get_metadata_for_column(
{fetched_col.db_id, fetched_col.table_id, fetched_col.column_id});
const auto& ti = cd->columnType;
const auto sz = ti.get_size();
if (sz < 0) {
// for varlen types, only account for the pointer/size for each row, for now
if (!ti.is_logical_geo_type()) {
// Don't count size for logical geo types, as they are
// backed by physical columns
num_bytes += 16;
}
} else {
num_bytes += sz;
}
}
}
return num_bytes;
}
ExecutorResourceMgr_Namespace::ChunkRequestInfo Executor::getChunkRequestInfo(
const ExecutorDeviceType device_type,
const std::vector<InputDescriptor>& input_descs,
const std::vector<InputTableInfo>& query_infos,
const std::vector<std::pair<int32_t, FragmentsList>>& kernel_fragment_lists) const {
using TableFragmentId = std::pair<shared::TableKey, int32_t>;
using TableFragmentSizeMap = std::map<TableFragmentId, size_t>;
/* Calculate bytes per column */
// Only fetch lhs table ids for now...
// Allows us to cleanly lower number of kernels in flight to save
// buffer pool space, but is not a perfect estimate when big rhs
// join tables are involved. Will revisit.
std::set<shared::TableKey> lhs_table_keys;
for (const auto& input_desc : input_descs) {
if (input_desc.getNestLevel() == 0) {
lhs_table_keys.insert(input_desc.getTableKey());
}
}
const bool include_lazy_fetch_cols = device_type == ExecutorDeviceType::CPU;
const auto column_byte_width_map =
getColumnByteWidthMap(lhs_table_keys, include_lazy_fetch_cols);
/* Calculate the byte width per row (sum of all columns widths)
Assumes each fragment touches the same columns, which is a DB-wide
invariant for now */
size_t const byte_width_per_row =
std::accumulate(column_byte_width_map.begin(),
column_byte_width_map.end(),
size_t(0),
[](size_t sum, auto& col_entry) { return sum + col_entry.second; });
/* Calculate num tuples for all fragments */
TableFragmentSizeMap all_table_fragments_size_map;
for (auto& query_info : query_infos) {
const auto& table_key = query_info.table_key;
for (const auto& frag : query_info.info.fragments) {
const int32_t frag_id = frag.fragmentId;
const TableFragmentId table_frag_id = std::make_pair(table_key, frag_id);
const size_t fragment_num_tuples = frag.getNumTuples(); // num_tuples;
all_table_fragments_size_map.insert(
std::make_pair(table_frag_id, fragment_num_tuples));
}
}
/* Calculate num tuples only for fragments actually touched by query
Also calculate the num bytes needed for each kernel */
TableFragmentSizeMap query_table_fragments_size_map;
std::vector<size_t> bytes_per_kernel;
bytes_per_kernel.reserve(kernel_fragment_lists.size());
size_t max_kernel_bytes{0};
for (auto& kernel_frag_list : kernel_fragment_lists) {
size_t kernel_bytes{0};
const auto frag_list = kernel_frag_list.second;
for (const auto& table_frags : frag_list) {
const auto& table_key = table_frags.table_key;
for (const size_t frag_id : table_frags.fragment_ids) {
const TableFragmentId table_frag_id = std::make_pair(table_key, frag_id);
const size_t fragment_num_tuples = all_table_fragments_size_map[table_frag_id];
kernel_bytes += fragment_num_tuples * byte_width_per_row;
query_table_fragments_size_map.insert(
std::make_pair(table_frag_id, fragment_num_tuples));
}
}
bytes_per_kernel.emplace_back(kernel_bytes);
if (kernel_bytes > max_kernel_bytes) {
max_kernel_bytes = kernel_bytes;
}
}
/* Calculate bytes per chunk touched by the query */
std::map<ChunkKey, size_t> all_chunks_byte_sizes_map;
constexpr int32_t subkey_min = std::numeric_limits<int32_t>::min();
for (const auto& col_byte_width_entry : column_byte_width_map) {
// Build a chunk key prefix of (db_id, table_id, column_id)
const int32_t db_id = col_byte_width_entry.first.db_id;
const int32_t table_id = col_byte_width_entry.first.table_id;
const int32_t col_id = col_byte_width_entry.first.column_id;
const size_t col_byte_width = col_byte_width_entry.second;
const shared::TableKey table_key(db_id, table_id);
const auto frag_start =
query_table_fragments_size_map.lower_bound({table_key, subkey_min});
for (auto frag_itr = frag_start; frag_itr != query_table_fragments_size_map.end() &&
frag_itr->first.first == table_key;
frag_itr++) {
const ChunkKey chunk_key = {db_id, table_id, col_id, frag_itr->first.second};
const size_t chunk_byte_size = col_byte_width * frag_itr->second;
all_chunks_byte_sizes_map.insert({chunk_key, chunk_byte_size});
}