OmniSciDB  ca0c39ec8f
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Execute.cpp
Go to the documentation of this file.
1 /*
2  * Copyright 2022 HEAVY.AI, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "QueryEngine/Execute.h"
18 
19 #include <llvm/Transforms/Utils/BasicBlockUtils.h>
20 #include <boost/filesystem/operations.hpp>
21 #include <boost/filesystem/path.hpp>
22 
23 #ifdef HAVE_CUDA
24 #include <cuda.h>
25 #endif // HAVE_CUDA
26 #include <chrono>
27 #include <ctime>
28 #include <future>
29 #include <iostream>
30 #include <memory>
31 #include <mutex>
32 #include <numeric>
33 #include <set>
34 #include <thread>
35 
36 #include "Catalog/Catalog.h"
37 #include "CudaMgr/CudaMgr.h"
41 #include "Parser/ParserNode.h"
72 #include "Shared/checked_alloc.h"
73 #include "Shared/measure.h"
74 #include "Shared/misc.h"
75 #include "Shared/scope.h"
76 #include "Shared/shard_key.h"
77 #include "Shared/threading.h"
78 
79 bool g_enable_watchdog{false};
83 size_t g_cpu_sub_task_size{500'000};
84 bool g_enable_filter_function{true};
85 unsigned g_dynamic_watchdog_time_limit{10000};
86 bool g_allow_cpu_retry{true};
87 bool g_allow_query_step_cpu_retry{true};
88 bool g_null_div_by_zero{false};
89 unsigned g_trivial_loop_join_threshold{1000};
90 bool g_from_table_reordering{true};
91 bool g_inner_join_fragment_skipping{true};
92 extern bool g_enable_smem_group_by;
93 extern std::unique_ptr<llvm::Module> udf_gpu_module;
94 extern std::unique_ptr<llvm::Module> udf_cpu_module;
95 bool g_enable_filter_push_down{false};
96 float g_filter_push_down_low_frac{-1.0f};
97 float g_filter_push_down_high_frac{-1.0f};
98 size_t g_filter_push_down_passing_row_ubound{0};
99 bool g_enable_columnar_output{false};
100 bool g_enable_left_join_filter_hoisting{true};
101 bool g_optimize_row_initialization{true};
102 bool g_enable_overlaps_hashjoin{true};
103 bool g_enable_distance_rangejoin{true};
104 bool g_enable_hashjoin_many_to_many{false};
105 size_t g_overlaps_max_table_size_bytes{1024 * 1024 * 1024};
106 double g_overlaps_target_entries_per_bin{1.3};
107 bool g_strip_join_covered_quals{false};
108 size_t g_constrained_by_in_threshold{10};
109 size_t g_default_max_groups_buffer_entry_guess{16384};
110 size_t g_big_group_threshold{g_default_max_groups_buffer_entry_guess};
111 bool g_enable_window_functions{true};
112 bool g_enable_table_functions{true};
113 bool g_enable_dev_table_functions{false};
114 bool g_enable_geo_ops_on_uncompressed_coords{true};
115 bool g_enable_rf_prop_table_functions{true};
116 size_t g_max_memory_allocation_size{2000000000}; // set to max slab size
117 size_t g_min_memory_allocation_size{
118  256}; // minimum memory allocation required for projection query output buffer
119  // without pre-flight count
120 bool g_enable_bump_allocator{false};
121 double g_bump_allocator_step_reduction{0.75};
122 bool g_enable_direct_columnarization{true};
123 extern bool g_enable_string_functions;
124 bool g_enable_lazy_fetch{true};
125 bool g_enable_runtime_query_interrupt{true};
126 bool g_enable_non_kernel_time_query_interrupt{true};
127 bool g_use_estimator_result_cache{true};
128 unsigned g_pending_query_interrupt_freq{1000};
129 double g_running_query_interrupt_freq{0.1};
130 size_t g_gpu_smem_threshold{
131  4096}; // GPU shared memory threshold (in bytes), if larger
132  // buffer sizes are required we do not use GPU shared
133  // memory optimizations Setting this to 0 means unlimited
134  // (subject to other dynamically calculated caps)
135 bool g_enable_smem_grouped_non_count_agg{
136  true}; // enable use of shared memory when performing group-by with select non-count
137  // aggregates
138 bool g_enable_smem_non_grouped_agg{
139  true}; // enable optimizations for using GPU shared memory in implementation of
140  // non-grouped aggregates
141 bool g_is_test_env{false}; // operating under a unit test environment. Currently only
142  // limits the allocation for the output buffer arena
143  // and data recycler test
144 size_t g_enable_parallel_linearization{
145  10000}; // # rows that we are trying to linearize varlen col in parallel
146 bool g_enable_data_recycler{true};
147 bool g_use_hashtable_cache{true};
148 bool g_use_query_resultset_cache{true};
149 bool g_use_chunk_metadata_cache{true};
150 bool g_allow_auto_resultset_caching{false};
151 bool g_allow_query_step_skipping{true};
152 size_t g_hashtable_cache_total_bytes{size_t(1) << 32};
153 size_t g_max_cacheable_hashtable_size_bytes{size_t(1) << 31};
154 size_t g_query_resultset_cache_total_bytes{size_t(1) << 32};
155 size_t g_max_cacheable_query_resultset_size_bytes{size_t(1) << 31};
156 size_t g_auto_resultset_caching_threshold{size_t(1) << 20};
157 
158 size_t g_approx_quantile_buffer{1000};
159 size_t g_approx_quantile_centroids{300};
160 
161 bool g_enable_automatic_ir_metadata{true};
162 
163 size_t g_max_log_length{500};
164 
165 extern bool g_cache_string_hash;
166 
167 int const Executor::max_gpu_count;
168 
169 const int32_t Executor::ERR_SINGLE_VALUE_FOUND_MULTIPLE_VALUES;
170 
171 std::map<Executor::ExtModuleKinds, std::string> Executor::extension_module_sources;
172 
173 extern std::unique_ptr<llvm::Module> read_llvm_module_from_bc_file(
174  const std::string& udf_ir_filename,
175  llvm::LLVMContext& ctx);
176 extern std::unique_ptr<llvm::Module> read_llvm_module_from_ir_file(
177  const std::string& udf_ir_filename,
178  llvm::LLVMContext& ctx,
179  bool is_gpu = false);
180 extern std::unique_ptr<llvm::Module> read_llvm_module_from_ir_string(
181  const std::string& udf_ir_string,
182  llvm::LLVMContext& ctx,
183  bool is_gpu = false);
184 
185 namespace {
186 // This function is notably different from that in RelAlgExecutor because it already
187 // expects SPI values and therefore needs to avoid that transformation.
188 void prepare_string_dictionaries(const std::unordered_set<PhysicalInput>& phys_inputs,
189  const Catalog_Namespace::Catalog& catalog) {
190  for (const auto [col_id, table_id] : phys_inputs) {
191  foreign_storage::populate_string_dictionary(table_id, col_id, catalog);
192  }
193 }
194 
195 bool is_empty_table(Fragmenter_Namespace::AbstractFragmenter* fragmenter) {
196  const auto& fragments = fragmenter->getFragmentsForQuery().fragments;
197  // The fragmenter always returns at least one fragment, even when the table is empty.
198  return (fragments.size() == 1 && fragments[0].getChunkMetadataMap().empty());
199 }
200 } // namespace
201 
202 namespace foreign_storage {
203 // Foreign tables skip the population of dictionaries during metadata scan. This function
204 // will populate a dictionary's missing entries by fetching any unpopulated chunks.
205 void populate_string_dictionary(const int32_t table_id,
206  const int32_t col_id,
207  const Catalog_Namespace::Catalog& catalog) {
208  if (const auto foreign_table = dynamic_cast<const ForeignTable*>(
209  catalog.getMetadataForTable(table_id, false))) {
210  const auto col_desc = catalog.getMetadataForColumn(table_id, col_id);
211  if (col_desc->columnType.is_dict_encoded_type()) {
212  auto& fragmenter = foreign_table->fragmenter;
213  CHECK(fragmenter != nullptr);
214  if (is_empty_table(fragmenter.get())) {
215  return;
216  }
217  for (const auto& frag : fragmenter->getFragmentsForQuery().fragments) {
218  ChunkKey chunk_key = {catalog.getDatabaseId(), table_id, col_id, frag.fragmentId};
219  // If the key is sharded across leaves, only populate fragments that are sharded
220  // to this leaf.
221  if (key_does_not_shard_to_leaf(chunk_key)) {
222  continue;
223  }
224 
225  const ChunkMetadataMap& metadata_map = frag.getChunkMetadataMap();
226  CHECK(metadata_map.find(col_id) != metadata_map.end());
227  if (auto& meta = metadata_map.at(col_id); meta->isPlaceholder()) {
228  // When this goes out of scope it will stay in CPU cache but become
229  // evictable
230  auto chunk = Chunk_NS::Chunk::getChunk(col_desc,
231  &(catalog.getDataMgr()),
232  chunk_key,
234  0,
235  0,
236  0);
237  }
238  }
239  }
240  }
241 }
242 } // namespace foreign_storage
243 
244 Executor::Executor(const ExecutorId executor_id,
245  Data_Namespace::DataMgr* data_mgr,
246  const size_t block_size_x,
247  const size_t grid_size_x,
248  const size_t max_gpu_slab_size,
249  const std::string& debug_dir,
250  const std::string& debug_file)
251  : executor_id_(executor_id)
252  , context_(new llvm::LLVMContext())
253  , cgen_state_(new CgenState({}, false, this))
254  , block_size_x_(block_size_x)
255  , grid_size_x_(grid_size_x)
256  , max_gpu_slab_size_(max_gpu_slab_size)
257  , debug_dir_(debug_dir)
258  , debug_file_(debug_file)
259  , catalog_(nullptr)
260  , data_mgr_(data_mgr)
261  , temporary_tables_(nullptr)
265  update_extension_modules();
266 }
267 
272  auto root_path = heavyai::get_root_abs_path();
273  auto template_path = root_path + "/QueryEngine/RuntimeFunctions.bc";
274  CHECK(boost::filesystem::exists(template_path));
276  template_path;
277 #ifdef ENABLE_GEOS
278  auto rt_geos_path = root_path + "/QueryEngine/GeosRuntime.bc";
279  CHECK(boost::filesystem::exists(rt_geos_path));
281  rt_geos_path;
282 #endif
283 #ifdef HAVE_CUDA
284  auto rt_libdevice_path = get_cuda_home() + "/nvvm/libdevice/libdevice.10.bc";
285  if (boost::filesystem::exists(rt_libdevice_path)) {
287  rt_libdevice_path;
288  } else {
289  LOG(WARNING) << "File " << rt_libdevice_path
290  << " does not exist; support for some UDF "
291  "functions might not be available.";
292  }
293 #endif
294  }
295 }
296 
297 void Executor::reset(bool discard_runtime_modules_only) {
298  // TODO: keep cached results that do not depend on runtime UDF/UDTFs
299  auto qe = QueryEngine::getInstance();
300  qe->s_code_accessor->clear();
301  qe->s_stubs_accessor->clear();
302  qe->cpu_code_accessor->clear();
303  qe->gpu_code_accessor->clear();
304  qe->tf_code_accessor->clear();
305 
306  if (discard_runtime_modules_only) {
307  extension_modules_.erase(Executor::ExtModuleKinds::rt_udf_cpu_module);
308 #ifdef HAVE_CUDA
309  extension_modules_.erase(Executor::ExtModuleKinds::rt_udf_gpu_module);
310 #endif
311  cgen_state_->module_ = nullptr;
312  } else {
313  extension_modules_.clear();
314  cgen_state_.reset();
315  context_.reset(new llvm::LLVMContext());
316  cgen_state_.reset(new CgenState({}, false, this));
317  }
318 }
319 
320 void Executor::update_extension_modules(bool update_runtime_modules_only) {
321  auto read_module = [&](Executor::ExtModuleKinds module_kind,
322  const std::string& source) {
323  /*
324  source can be either a filename of a LLVM IR
325  or LLVM BC source, or a string containing
326  LLVM IR code.
327  */
328  CHECK(!source.empty());
329  switch (module_kind) {
333  return read_llvm_module_from_bc_file(source, getContext());
334  }
336  return read_llvm_module_from_ir_file(source, getContext(), false);
337  }
339  return read_llvm_module_from_ir_file(source, getContext(), true);
340  }
342  return read_llvm_module_from_ir_string(source, getContext(), false);
343  }
345  return read_llvm_module_from_ir_string(source, getContext(), true);
346  }
347  default: {
348  UNREACHABLE();
349  return std::unique_ptr<llvm::Module>();
350  }
351  }
352  };
353  auto update_module = [&](Executor::ExtModuleKinds module_kind,
354  bool erase_not_found = false) {
355  auto it = Executor::extension_module_sources.find(module_kind);
356  if (it != Executor::extension_module_sources.end()) {
357  auto llvm_module = read_module(module_kind, it->second);
358  if (llvm_module) {
359  extension_modules_[module_kind] = std::move(llvm_module);
360  } else if (erase_not_found) {
361  extension_modules_.erase(module_kind);
362  } else {
363  if (extension_modules_.find(module_kind) == extension_modules_.end()) {
364  LOG(WARNING) << "Failed to update " << ::toString(module_kind)
365  << " LLVM module. The module will be unavailable.";
366  } else {
367  LOG(WARNING) << "Failed to update " << ::toString(module_kind)
368  << " LLVM module. Using the existing module.";
369  }
370  }
371  } else {
372  if (erase_not_found) {
373  extension_modules_.erase(module_kind);
374  } else {
375  if (extension_modules_.find(module_kind) == extension_modules_.end()) {
376  LOG(WARNING) << "Source of " << ::toString(module_kind)
377  << " LLVM module is unavailable. The module will be unavailable.";
378  } else {
379  LOG(WARNING) << "Source of " << ::toString(module_kind)
380  << " LLVM module is unavailable. Using the existing module.";
381  }
382  }
383  }
384  };
385 
386  if (!update_runtime_modules_only) {
387  // required compile-time modules, their requirements are enforced
388  // by Executor::initialize_extension_module_sources():
390 #ifdef ENABLE_GEOS
392 #endif
393  // load-time modules, these are optional:
394  update_module(Executor::ExtModuleKinds::udf_cpu_module, true);
395 #ifdef HAVE_CUDA
396  update_module(Executor::ExtModuleKinds::udf_gpu_module, true);
398 #endif
399  }
400  // run-time modules, these are optional and erasable:
401  update_module(Executor::ExtModuleKinds::rt_udf_cpu_module, true);
402 #ifdef HAVE_CUDA
403  update_module(Executor::ExtModuleKinds::rt_udf_gpu_module, true);
404 #endif
405 }
406 
407 // Used by StubGenerator::generateStub
409  : executor_(executor)
410  , lock_queue_clock_(timer_start())
411  , lock_(executor_.compilation_mutex_)
412  , cgen_state_(std::move(executor_.cgen_state_)) // store old CgenState instance
413 {
414  executor_.compilation_queue_time_ms_ += timer_stop(lock_queue_clock_);
415  executor_.cgen_state_.reset(new CgenState(0, false, &executor));
416 }
417 
419  Executor& executor,
420  const bool allow_lazy_fetch,
421  const std::vector<InputTableInfo>& query_infos,
422  const PlanState::DeletedColumnsMap& deleted_cols_map,
423  const RelAlgExecutionUnit* ra_exe_unit)
424  : executor_(executor)
425  , lock_queue_clock_(timer_start())
426  , lock_(executor_.compilation_mutex_)
427  , cgen_state_(std::move(executor_.cgen_state_)) // store old CgenState instance
428 {
429  executor_.compilation_queue_time_ms_ += timer_stop(lock_queue_clock_);
430  // nukeOldState creates new CgenState and PlanState instances for
431  // the subsequent code generation. It also resets
432  // kernel_queue_time_ms_ and compilation_queue_time_ms_ that we do
433  // not currently restore.. should we accumulate these timings?
434  executor_.nukeOldState(allow_lazy_fetch, query_infos, deleted_cols_map, ra_exe_unit);
435 }
436 
438  // prevent memory leak from hoisted literals
439  for (auto& p : executor_.cgen_state_->row_func_hoisted_literals_) {
440  auto inst = llvm::dyn_cast<llvm::LoadInst>(p.first);
441  if (inst && inst->getNumUses() == 0 && inst->getParent() == nullptr) {
442  // The llvm::Value instance stored in p.first is created by the
443  // CodeGenerator::codegenHoistedConstantsPlaceholders method.
444  p.first->deleteValue();
445  }
446  }
447  executor_.cgen_state_->row_func_hoisted_literals_.clear();
448 
449  // move generated StringDictionaryTranslationMgrs and InValueBitmaps
450  // to the old CgenState instance as the execution of the generated
451  // code uses these bitmaps
452 
453  for (auto& str_dict_translation_mgr :
454  executor_.cgen_state_->str_dict_translation_mgrs_) {
455  cgen_state_->moveStringDictionaryTranslationMgr(std::move(str_dict_translation_mgr));
456  }
457  executor_.cgen_state_->str_dict_translation_mgrs_.clear();
458 
459  for (auto& bm : executor_.cgen_state_->in_values_bitmaps_) {
460  cgen_state_->moveInValuesBitmap(bm);
461  }
462  executor_.cgen_state_->in_values_bitmaps_.clear();
463 
464  // Delete worker module that may have been set by
465  // set_module_shallow_copy. If QueryMustRunOnCpu is thrown, the
466  // worker module is not instantiated, so the worker module needs to
467  // be deleted conditionally [see "Managing LLVM modules" comment in
468  // CgenState.h]:
469  if (executor_.cgen_state_->module_) {
470  delete executor_.cgen_state_->module_;
471  }
472 
473  // restore the old CgenState instance
474  executor_.cgen_state_.reset(cgen_state_.release());
475 }
476 
477 std::shared_ptr<Executor> Executor::getExecutor(
478  const ExecutorId executor_id,
479  const std::string& debug_dir,
480  const std::string& debug_file,
481  const SystemParameters& system_parameters) {
483 
485  auto it = executors_.find(executor_id);
486  if (it != executors_.end()) {
487  return it->second;
488  }
490  auto executor = std::make_shared<Executor>(executor_id,
491  &data_mgr,
492  system_parameters.cuda_block_size,
493  system_parameters.cuda_grid_size,
494  system_parameters.max_gpu_slab_size,
495  debug_dir,
496  debug_file);
497  CHECK(executors_.insert(std::make_pair(executor_id, executor)).second);
498  return executor;
499 }
500 
502  switch (memory_level) {
506  execute_mutex_); // Don't flush memory while queries are running
507 
508  if (memory_level == Data_Namespace::MemoryLevel::CPU_LEVEL) {
509  // The hash table cache uses CPU memory not managed by the buffer manager. In the
510  // future, we should manage these allocations with the buffer manager directly.
511  // For now, assume the user wants to purge the hash table cache when they clear
512  // CPU memory (currently used in ExecuteTest to lower memory pressure)
514  }
517  break;
518  }
519  default: {
520  throw std::runtime_error(
521  "Clearing memory levels other than the CPU level or GPU level is not "
522  "supported.");
523  }
524  }
525 }
526 
528  return g_is_test_env ? 100000000 : (1UL << 32) + kArenaBlockOverhead;
529 }
530 
532  const int dict_id_in,
533  std::shared_ptr<RowSetMemoryOwner> row_set_mem_owner,
534  const bool with_generation) const {
535  CHECK(row_set_mem_owner);
536  std::lock_guard<std::mutex> lock(
537  str_dict_mutex_); // TODO: can we use RowSetMemOwner state mutex here?
538  return row_set_mem_owner->getOrAddStringDictProxy(
539  dict_id_in, with_generation, catalog_);
540 }
541 
543  const int dict_id_in,
544  const bool with_generation,
545  const Catalog_Namespace::Catalog* catalog) {
546  const int dict_id{dict_id_in < 0 ? REGULAR_DICT(dict_id_in) : dict_id_in};
547  CHECK(catalog);
548  const auto dd = catalog->getMetadataForDict(dict_id);
549  if (dd) {
550  CHECK(dd->stringDict);
551  CHECK_LE(dd->dictNBits, 32);
552  const int64_t generation =
553  with_generation ? string_dictionary_generations_.getGeneration(dict_id) : -1;
554  return addStringDict(dd->stringDict, dict_id, generation);
555  }
557  if (!lit_str_dict_proxy_) {
558  DictRef literal_dict_ref(catalog->getDatabaseId(), DictRef::literalsDictId);
559  std::shared_ptr<StringDictionary> tsd = std::make_shared<StringDictionary>(
560  literal_dict_ref, "", false, true, g_cache_string_hash);
561  lit_str_dict_proxy_ =
562  std::make_shared<StringDictionaryProxy>(tsd, literal_dict_ref.dictId, 0);
563  }
564  return lit_str_dict_proxy_.get();
565 }
566 
568  const int source_dict_id,
569  const int dest_dict_id,
570  const RowSetMemoryOwner::StringTranslationType translation_type,
571  const std::vector<StringOps_Namespace::StringOpInfo>& string_op_infos,
572  std::shared_ptr<RowSetMemoryOwner> row_set_mem_owner,
573  const bool with_generation) const {
574  CHECK(row_set_mem_owner);
575  std::lock_guard<std::mutex> lock(
576  str_dict_mutex_); // TODO: can we use RowSetMemOwner state mutex here?
577  return row_set_mem_owner->getOrAddStringProxyTranslationMap(source_dict_id,
578  dest_dict_id,
579  with_generation,
580  translation_type,
581  string_op_infos,
582  catalog_);
583 }
584 
587  const StringDictionaryProxy* source_proxy,
588  StringDictionaryProxy* dest_proxy,
589  const std::vector<StringOps_Namespace::StringOpInfo>& source_string_op_infos,
590  const std::vector<StringOps_Namespace::StringOpInfo>& dest_string_op_infos,
591  std::shared_ptr<RowSetMemoryOwner> row_set_mem_owner) const {
592  CHECK(row_set_mem_owner);
593  std::lock_guard<std::mutex> lock(
594  str_dict_mutex_); // TODO: can we use RowSetMemOwner state mutex here?
595  // First translate lhs onto itself if there are string ops
596  if (!dest_string_op_infos.empty()) {
597  row_set_mem_owner->addStringProxyUnionTranslationMap(
598  dest_proxy, dest_proxy, dest_string_op_infos);
599  }
600  return row_set_mem_owner->addStringProxyIntersectionTranslationMap(
601  source_proxy, dest_proxy, source_string_op_infos);
602 }
603 
606  const int source_dict_id,
607  const std::vector<StringOps_Namespace::StringOpInfo>& string_op_infos,
608  std::shared_ptr<RowSetMemoryOwner> row_set_mem_owner,
609  const bool with_generation) const {
610  CHECK(row_set_mem_owner);
611  std::lock_guard<std::mutex> lock(
612  str_dict_mutex_); // TODO: can we use RowSetMemOwner state mutex here?
613  return row_set_mem_owner->getOrAddStringProxyNumericTranslationMap(
614  source_dict_id, with_generation, string_op_infos, catalog_);
615 }
616 
618  const int source_dict_id_in,
619  const int dest_dict_id_in,
620  const bool with_generation,
621  const RowSetMemoryOwner::StringTranslationType translation_type,
622  const std::vector<StringOps_Namespace::StringOpInfo>& string_op_infos,
623  const Catalog_Namespace::Catalog* catalog) {
624  const auto source_proxy =
625  getOrAddStringDictProxy(source_dict_id_in, with_generation, catalog);
626  auto dest_proxy = getOrAddStringDictProxy(dest_dict_id_in, with_generation, catalog);
628  return addStringProxyIntersectionTranslationMap(
629  source_proxy, dest_proxy, string_op_infos);
630  } else {
631  return addStringProxyUnionTranslationMap(source_proxy, dest_proxy, string_op_infos);
632  }
633 }
634 
637  const int source_dict_id_in,
638  const bool with_generation,
639  const std::vector<StringOps_Namespace::StringOpInfo>& string_op_infos,
640  const Catalog_Namespace::Catalog* catalog) {
641  const auto source_proxy =
642  getOrAddStringDictProxy(source_dict_id_in, with_generation, catalog);
643  return addStringProxyNumericTranslationMap(source_proxy, string_op_infos);
644 }
645 
647  std::lock_guard<std::mutex> lock(state_mutex_);
648  return t_digests_
649  .emplace_back(std::make_unique<quantile::TDigest>(
651  .get();
652 }
653 
654 bool Executor::isCPUOnly() const {
655  CHECK(data_mgr_);
656  return !data_mgr_->getCudaMgr();
657 }
658 
660  const Analyzer::ColumnVar* col_var) const {
662  col_var->get_column_id(), col_var->get_table_id(), *catalog_);
663 }
664 
666  const Analyzer::ColumnVar* col_var,
667  int n) const {
668  const auto cd = getColumnDescriptor(col_var);
669  if (!cd || n > cd->columnType.get_physical_cols()) {
670  return nullptr;
671  }
673  col_var->get_column_id() + n, col_var->get_table_id(), *catalog_);
674 }
675 
677  return catalog_;
678 }
679 
681  catalog_ = catalog;
682 }
683 
684 const std::shared_ptr<RowSetMemoryOwner> Executor::getRowSetMemoryOwner() const {
685  return row_set_mem_owner_;
686 }
687 
689  return temporary_tables_;
690 }
691 
693  return input_table_info_cache_.getTableInfo(table_id);
694 }
695 
696 const TableGeneration& Executor::getTableGeneration(const int table_id) const {
697  return table_generations_.getGeneration(table_id);
698 }
699 
701  return agg_col_range_cache_.getColRange(phys_input);
702 }
703 
704 size_t Executor::getNumBytesForFetchedRow(const std::set<int>& table_ids_to_fetch) const {
705  size_t num_bytes = 0;
706  if (!plan_state_) {
707  return 0;
708  }
709  for (const auto& fetched_col_pair : plan_state_->columns_to_fetch_) {
710  if (table_ids_to_fetch.count(fetched_col_pair.first) == 0) {
711  continue;
712  }
713 
714  if (fetched_col_pair.first < 0) {
715  num_bytes += 8;
716  } else {
717  const auto cd =
718  catalog_->getMetadataForColumn(fetched_col_pair.first, fetched_col_pair.second);
719  const auto& ti = cd->columnType;
720  const auto sz = ti.get_size();
721  if (sz < 0) {
722  // for varlen types, only account for the pointer/size for each row, for now
723  if (!ti.is_logical_geo_type()) {
724  // Don't count size for logical geo types, as they are
725  // backed by physical columns
726  num_bytes += 16;
727  }
728  } else {
729  num_bytes += sz;
730  }
731  }
732  }
733  return num_bytes;
734 }
735 
737  const std::vector<Analyzer::Expr*>& target_exprs) const {
739  for (const auto target_expr : target_exprs) {
740  if (plan_state_->isLazyFetchColumn(target_expr)) {
741  return true;
742  }
743  }
744  return false;
745 }
746 
747 std::vector<ColumnLazyFetchInfo> Executor::getColLazyFetchInfo(
748  const std::vector<Analyzer::Expr*>& target_exprs) const {
750  CHECK(catalog_);
751  std::vector<ColumnLazyFetchInfo> col_lazy_fetch_info;
752  for (const auto target_expr : target_exprs) {
753  if (!plan_state_->isLazyFetchColumn(target_expr)) {
754  col_lazy_fetch_info.emplace_back(
755  ColumnLazyFetchInfo{false, -1, SQLTypeInfo(kNULLT, false)});
756  } else {
757  const auto col_var = dynamic_cast<const Analyzer::ColumnVar*>(target_expr);
758  CHECK(col_var);
759  auto col_id = col_var->get_column_id();
760  auto rte_idx = (col_var->get_rte_idx() == -1) ? 0 : col_var->get_rte_idx();
761  auto cd = (col_var->get_table_id() > 0)
762  ? get_column_descriptor(col_id, col_var->get_table_id(), *catalog_)
763  : nullptr;
764  if (cd && IS_GEO(cd->columnType.get_type())) {
765  // Geo coords cols will be processed in sequence. So we only need to track the
766  // first coords col in lazy fetch info.
767  {
768  auto cd0 =
769  get_column_descriptor(col_id + 1, col_var->get_table_id(), *catalog_);
770  auto col0_ti = cd0->columnType;
771  CHECK(!cd0->isVirtualCol);
772  auto col0_var = makeExpr<Analyzer::ColumnVar>(
773  col0_ti, col_var->get_table_id(), cd0->columnId, rte_idx);
774  auto local_col0_id = plan_state_->getLocalColumnId(col0_var.get(), false);
775  col_lazy_fetch_info.emplace_back(
776  ColumnLazyFetchInfo{true, local_col0_id, col0_ti});
777  }
778  } else {
779  auto local_col_id = plan_state_->getLocalColumnId(col_var, false);
780  const auto& col_ti = col_var->get_type_info();
781  col_lazy_fetch_info.emplace_back(ColumnLazyFetchInfo{true, local_col_id, col_ti});
782  }
783  }
784  }
785  return col_lazy_fetch_info;
786 }
787 
792 }
793 
794 std::vector<int8_t> Executor::serializeLiterals(
795  const std::unordered_map<int, CgenState::LiteralValues>& literals,
796  const int device_id) {
797  if (literals.empty()) {
798  return {};
799  }
800  const auto dev_literals_it = literals.find(device_id);
801  CHECK(dev_literals_it != literals.end());
802  const auto& dev_literals = dev_literals_it->second;
803  size_t lit_buf_size{0};
804  std::vector<std::string> real_strings;
805  std::vector<std::vector<double>> double_array_literals;
806  std::vector<std::vector<int8_t>> align64_int8_array_literals;
807  std::vector<std::vector<int32_t>> int32_array_literals;
808  std::vector<std::vector<int8_t>> align32_int8_array_literals;
809  std::vector<std::vector<int8_t>> int8_array_literals;
810  for (const auto& lit : dev_literals) {
811  lit_buf_size = CgenState::addAligned(lit_buf_size, CgenState::literalBytes(lit));
812  if (lit.which() == 7) {
813  const auto p = boost::get<std::string>(&lit);
814  CHECK(p);
815  real_strings.push_back(*p);
816  } else if (lit.which() == 8) {
817  const auto p = boost::get<std::vector<double>>(&lit);
818  CHECK(p);
819  double_array_literals.push_back(*p);
820  } else if (lit.which() == 9) {
821  const auto p = boost::get<std::vector<int32_t>>(&lit);
822  CHECK(p);
823  int32_array_literals.push_back(*p);
824  } else if (lit.which() == 10) {
825  const auto p = boost::get<std::vector<int8_t>>(&lit);
826  CHECK(p);
827  int8_array_literals.push_back(*p);
828  } else if (lit.which() == 11) {
829  const auto p = boost::get<std::pair<std::vector<int8_t>, int>>(&lit);
830  CHECK(p);
831  if (p->second == 64) {
832  align64_int8_array_literals.push_back(p->first);
833  } else if (p->second == 32) {
834  align32_int8_array_literals.push_back(p->first);
835  } else {
836  CHECK(false);
837  }
838  }
839  }
840  if (lit_buf_size > static_cast<size_t>(std::numeric_limits<int16_t>::max())) {
841  throw TooManyLiterals();
842  }
843  int16_t crt_real_str_off = lit_buf_size;
844  for (const auto& real_str : real_strings) {
845  CHECK_LE(real_str.size(), static_cast<size_t>(std::numeric_limits<int16_t>::max()));
846  lit_buf_size += real_str.size();
847  }
848  if (double_array_literals.size() > 0) {
849  lit_buf_size = align(lit_buf_size, sizeof(double));
850  }
851  int16_t crt_double_arr_lit_off = lit_buf_size;
852  for (const auto& double_array_literal : double_array_literals) {
853  CHECK_LE(double_array_literal.size(),
854  static_cast<size_t>(std::numeric_limits<int16_t>::max()));
855  lit_buf_size += double_array_literal.size() * sizeof(double);
856  }
857  if (align64_int8_array_literals.size() > 0) {
858  lit_buf_size = align(lit_buf_size, sizeof(uint64_t));
859  }
860  int16_t crt_align64_int8_arr_lit_off = lit_buf_size;
861  for (const auto& align64_int8_array_literal : align64_int8_array_literals) {
862  CHECK_LE(align64_int8_array_literals.size(),
863  static_cast<size_t>(std::numeric_limits<int16_t>::max()));
864  lit_buf_size += align64_int8_array_literal.size();
865  }
866  if (int32_array_literals.size() > 0) {
867  lit_buf_size = align(lit_buf_size, sizeof(int32_t));
868  }
869  int16_t crt_int32_arr_lit_off = lit_buf_size;
870  for (const auto& int32_array_literal : int32_array_literals) {
871  CHECK_LE(int32_array_literal.size(),
872  static_cast<size_t>(std::numeric_limits<int16_t>::max()));
873  lit_buf_size += int32_array_literal.size() * sizeof(int32_t);
874  }
875  if (align32_int8_array_literals.size() > 0) {
876  lit_buf_size = align(lit_buf_size, sizeof(int32_t));
877  }
878  int16_t crt_align32_int8_arr_lit_off = lit_buf_size;
879  for (const auto& align32_int8_array_literal : align32_int8_array_literals) {
880  CHECK_LE(align32_int8_array_literals.size(),
881  static_cast<size_t>(std::numeric_limits<int16_t>::max()));
882  lit_buf_size += align32_int8_array_literal.size();
883  }
884  int16_t crt_int8_arr_lit_off = lit_buf_size;
885  for (const auto& int8_array_literal : int8_array_literals) {
886  CHECK_LE(int8_array_literal.size(),
887  static_cast<size_t>(std::numeric_limits<int16_t>::max()));
888  lit_buf_size += int8_array_literal.size();
889  }
890  unsigned crt_real_str_idx = 0;
891  unsigned crt_double_arr_lit_idx = 0;
892  unsigned crt_align64_int8_arr_lit_idx = 0;
893  unsigned crt_int32_arr_lit_idx = 0;
894  unsigned crt_align32_int8_arr_lit_idx = 0;
895  unsigned crt_int8_arr_lit_idx = 0;
896  std::vector<int8_t> serialized(lit_buf_size);
897  size_t off{0};
898  for (const auto& lit : dev_literals) {
899  const auto lit_bytes = CgenState::literalBytes(lit);
900  off = CgenState::addAligned(off, lit_bytes);
901  switch (lit.which()) {
902  case 0: {
903  const auto p = boost::get<int8_t>(&lit);
904  CHECK(p);
905  serialized[off - lit_bytes] = *p;
906  break;
907  }
908  case 1: {
909  const auto p = boost::get<int16_t>(&lit);
910  CHECK(p);
911  memcpy(&serialized[off - lit_bytes], p, lit_bytes);
912  break;
913  }
914  case 2: {
915  const auto p = boost::get<int32_t>(&lit);
916  CHECK(p);
917  memcpy(&serialized[off - lit_bytes], p, lit_bytes);
918  break;
919  }
920  case 3: {
921  const auto p = boost::get<int64_t>(&lit);
922  CHECK(p);
923  memcpy(&serialized[off - lit_bytes], p, lit_bytes);
924  break;
925  }
926  case 4: {
927  const auto p = boost::get<float>(&lit);
928  CHECK(p);
929  memcpy(&serialized[off - lit_bytes], p, lit_bytes);
930  break;
931  }
932  case 5: {
933  const auto p = boost::get<double>(&lit);
934  CHECK(p);
935  memcpy(&serialized[off - lit_bytes], p, lit_bytes);
936  break;
937  }
938  case 6: {
939  const auto p = boost::get<std::pair<std::string, int>>(&lit);
940  CHECK(p);
941  const auto str_id =
943  ? getStringDictionaryProxy(p->second, row_set_mem_owner_, true)
944  ->getOrAddTransient(p->first)
945  : getStringDictionaryProxy(p->second, row_set_mem_owner_, true)
946  ->getIdOfString(p->first);
947  memcpy(&serialized[off - lit_bytes], &str_id, lit_bytes);
948  break;
949  }
950  case 7: {
951  const auto p = boost::get<std::string>(&lit);
952  CHECK(p);
953  int32_t off_and_len = crt_real_str_off << 16;
954  const auto& crt_real_str = real_strings[crt_real_str_idx];
955  off_and_len |= static_cast<int16_t>(crt_real_str.size());
956  memcpy(&serialized[off - lit_bytes], &off_and_len, lit_bytes);
957  memcpy(&serialized[crt_real_str_off], crt_real_str.data(), crt_real_str.size());
958  ++crt_real_str_idx;
959  crt_real_str_off += crt_real_str.size();
960  break;
961  }
962  case 8: {
963  const auto p = boost::get<std::vector<double>>(&lit);
964  CHECK(p);
965  int32_t off_and_len = crt_double_arr_lit_off << 16;
966  const auto& crt_double_arr_lit = double_array_literals[crt_double_arr_lit_idx];
967  int32_t len = crt_double_arr_lit.size();
968  CHECK_EQ((len >> 16), 0);
969  off_and_len |= static_cast<int16_t>(len);
970  int32_t double_array_bytesize = len * sizeof(double);
971  memcpy(&serialized[off - lit_bytes], &off_and_len, lit_bytes);
972  memcpy(&serialized[crt_double_arr_lit_off],
973  crt_double_arr_lit.data(),
974  double_array_bytesize);
975  ++crt_double_arr_lit_idx;
976  crt_double_arr_lit_off += double_array_bytesize;
977  break;
978  }
979  case 9: {
980  const auto p = boost::get<std::vector<int32_t>>(&lit);
981  CHECK(p);
982  int32_t off_and_len = crt_int32_arr_lit_off << 16;
983  const auto& crt_int32_arr_lit = int32_array_literals[crt_int32_arr_lit_idx];
984  int32_t len = crt_int32_arr_lit.size();
985  CHECK_EQ((len >> 16), 0);
986  off_and_len |= static_cast<int16_t>(len);
987  int32_t int32_array_bytesize = len * sizeof(int32_t);
988  memcpy(&serialized[off - lit_bytes], &off_and_len, lit_bytes);
989  memcpy(&serialized[crt_int32_arr_lit_off],
990  crt_int32_arr_lit.data(),
991  int32_array_bytesize);
992  ++crt_int32_arr_lit_idx;
993  crt_int32_arr_lit_off += int32_array_bytesize;
994  break;
995  }
996  case 10: {
997  const auto p = boost::get<std::vector<int8_t>>(&lit);
998  CHECK(p);
999  int32_t off_and_len = crt_int8_arr_lit_off << 16;
1000  const auto& crt_int8_arr_lit = int8_array_literals[crt_int8_arr_lit_idx];
1001  int32_t len = crt_int8_arr_lit.size();
1002  CHECK_EQ((len >> 16), 0);
1003  off_and_len |= static_cast<int16_t>(len);
1004  int32_t int8_array_bytesize = len;
1005  memcpy(&serialized[off - lit_bytes], &off_and_len, lit_bytes);
1006  memcpy(&serialized[crt_int8_arr_lit_off],
1007  crt_int8_arr_lit.data(),
1008  int8_array_bytesize);
1009  ++crt_int8_arr_lit_idx;
1010  crt_int8_arr_lit_off += int8_array_bytesize;
1011  break;
1012  }
1013  case 11: {
1014  const auto p = boost::get<std::pair<std::vector<int8_t>, int>>(&lit);
1015  CHECK(p);
1016  if (p->second == 64) {
1017  int32_t off_and_len = crt_align64_int8_arr_lit_off << 16;
1018  const auto& crt_align64_int8_arr_lit =
1019  align64_int8_array_literals[crt_align64_int8_arr_lit_idx];
1020  int32_t len = crt_align64_int8_arr_lit.size();
1021  CHECK_EQ((len >> 16), 0);
1022  off_and_len |= static_cast<int16_t>(len);
1023  int32_t align64_int8_array_bytesize = len;
1024  memcpy(&serialized[off - lit_bytes], &off_and_len, lit_bytes);
1025  memcpy(&serialized[crt_align64_int8_arr_lit_off],
1026  crt_align64_int8_arr_lit.data(),
1027  align64_int8_array_bytesize);
1028  ++crt_align64_int8_arr_lit_idx;
1029  crt_align64_int8_arr_lit_off += align64_int8_array_bytesize;
1030  } else if (p->second == 32) {
1031  int32_t off_and_len = crt_align32_int8_arr_lit_off << 16;
1032  const auto& crt_align32_int8_arr_lit =
1033  align32_int8_array_literals[crt_align32_int8_arr_lit_idx];
1034  int32_t len = crt_align32_int8_arr_lit.size();
1035  CHECK_EQ((len >> 16), 0);
1036  off_and_len |= static_cast<int16_t>(len);
1037  int32_t align32_int8_array_bytesize = len;
1038  memcpy(&serialized[off - lit_bytes], &off_and_len, lit_bytes);
1039  memcpy(&serialized[crt_align32_int8_arr_lit_off],
1040  crt_align32_int8_arr_lit.data(),
1041  align32_int8_array_bytesize);
1042  ++crt_align32_int8_arr_lit_idx;
1043  crt_align32_int8_arr_lit_off += align32_int8_array_bytesize;
1044  } else {
1045  CHECK(false);
1046  }
1047  break;
1048  }
1049  default:
1050  CHECK(false);
1051  }
1052  }
1053  return serialized;
1054 }
1055 
1056 int Executor::deviceCount(const ExecutorDeviceType device_type) const {
1057  if (device_type == ExecutorDeviceType::GPU) {
1058  return cudaMgr()->getDeviceCount();
1059  } else {
1060  return 1;
1061  }
1062 }
1063 
1065  const Data_Namespace::MemoryLevel memory_level) const {
1066  return memory_level == GPU_LEVEL ? deviceCount(ExecutorDeviceType::GPU)
1068 }
1069 
1070 // TODO(alex): remove or split
1071 std::pair<int64_t, int32_t> Executor::reduceResults(const SQLAgg agg,
1072  const SQLTypeInfo& ti,
1073  const int64_t agg_init_val,
1074  const int8_t out_byte_width,
1075  const int64_t* out_vec,
1076  const size_t out_vec_sz,
1077  const bool is_group_by,
1078  const bool float_argument_input) {
1079  switch (agg) {
1080  case kAVG:
1081  case kSUM:
1082  if (0 != agg_init_val) {
1083  if (ti.is_integer() || ti.is_decimal() || ti.is_time() || ti.is_boolean()) {
1084  int64_t agg_result = agg_init_val;
1085  for (size_t i = 0; i < out_vec_sz; ++i) {
1086  agg_sum_skip_val(&agg_result, out_vec[i], agg_init_val);
1087  }
1088  return {agg_result, 0};
1089  } else {
1090  CHECK(ti.is_fp());
1091  switch (out_byte_width) {
1092  case 4: {
1093  int agg_result = static_cast<int32_t>(agg_init_val);
1094  for (size_t i = 0; i < out_vec_sz; ++i) {
1096  &agg_result,
1097  *reinterpret_cast<const float*>(may_alias_ptr(&out_vec[i])),
1098  *reinterpret_cast<const float*>(may_alias_ptr(&agg_init_val)));
1099  }
1100  const int64_t converted_bin =
1101  float_argument_input
1102  ? static_cast<int64_t>(agg_result)
1103  : float_to_double_bin(static_cast<int32_t>(agg_result), true);
1104  return {converted_bin, 0};
1105  break;
1106  }
1107  case 8: {
1108  int64_t agg_result = agg_init_val;
1109  for (size_t i = 0; i < out_vec_sz; ++i) {
1111  &agg_result,
1112  *reinterpret_cast<const double*>(may_alias_ptr(&out_vec[i])),
1113  *reinterpret_cast<const double*>(may_alias_ptr(&agg_init_val)));
1114  }
1115  return {agg_result, 0};
1116  break;
1117  }
1118  default:
1119  CHECK(false);
1120  }
1121  }
1122  }
1123  if (ti.is_integer() || ti.is_decimal() || ti.is_time()) {
1124  int64_t agg_result = 0;
1125  for (size_t i = 0; i < out_vec_sz; ++i) {
1126  agg_result += out_vec[i];
1127  }
1128  return {agg_result, 0};
1129  } else {
1130  CHECK(ti.is_fp());
1131  switch (out_byte_width) {
1132  case 4: {
1133  float r = 0.;
1134  for (size_t i = 0; i < out_vec_sz; ++i) {
1135  r += *reinterpret_cast<const float*>(may_alias_ptr(&out_vec[i]));
1136  }
1137  const auto float_bin = *reinterpret_cast<const int32_t*>(may_alias_ptr(&r));
1138  const int64_t converted_bin =
1139  float_argument_input ? float_bin : float_to_double_bin(float_bin, true);
1140  return {converted_bin, 0};
1141  }
1142  case 8: {
1143  double r = 0.;
1144  for (size_t i = 0; i < out_vec_sz; ++i) {
1145  r += *reinterpret_cast<const double*>(may_alias_ptr(&out_vec[i]));
1146  }
1147  return {*reinterpret_cast<const int64_t*>(may_alias_ptr(&r)), 0};
1148  }
1149  default:
1150  CHECK(false);
1151  }
1152  }
1153  break;
1154  case kCOUNT: {
1155  uint64_t agg_result = 0;
1156  for (size_t i = 0; i < out_vec_sz; ++i) {
1157  const uint64_t out = static_cast<uint64_t>(out_vec[i]);
1158  agg_result += out;
1159  }
1160  return {static_cast<int64_t>(agg_result), 0};
1161  }
1162  case kMIN: {
1163  if (ti.is_integer() || ti.is_decimal() || ti.is_time() || ti.is_boolean()) {
1164  int64_t agg_result = agg_init_val;
1165  for (size_t i = 0; i < out_vec_sz; ++i) {
1166  agg_min_skip_val(&agg_result, out_vec[i], agg_init_val);
1167  }
1168  return {agg_result, 0};
1169  } else {
1170  switch (out_byte_width) {
1171  case 4: {
1172  int32_t agg_result = static_cast<int32_t>(agg_init_val);
1173  for (size_t i = 0; i < out_vec_sz; ++i) {
1175  &agg_result,
1176  *reinterpret_cast<const float*>(may_alias_ptr(&out_vec[i])),
1177  *reinterpret_cast<const float*>(may_alias_ptr(&agg_init_val)));
1178  }
1179  const int64_t converted_bin =
1180  float_argument_input
1181  ? static_cast<int64_t>(agg_result)
1182  : float_to_double_bin(static_cast<int32_t>(agg_result), true);
1183  return {converted_bin, 0};
1184  }
1185  case 8: {
1186  int64_t agg_result = agg_init_val;
1187  for (size_t i = 0; i < out_vec_sz; ++i) {
1189  &agg_result,
1190  *reinterpret_cast<const double*>(may_alias_ptr(&out_vec[i])),
1191  *reinterpret_cast<const double*>(may_alias_ptr(&agg_init_val)));
1192  }
1193  return {agg_result, 0};
1194  }
1195  default:
1196  CHECK(false);
1197  }
1198  }
1199  }
1200  case kMAX:
1201  if (ti.is_integer() || ti.is_decimal() || ti.is_time() || ti.is_boolean()) {
1202  int64_t agg_result = agg_init_val;
1203  for (size_t i = 0; i < out_vec_sz; ++i) {
1204  agg_max_skip_val(&agg_result, out_vec[i], agg_init_val);
1205  }
1206  return {agg_result, 0};
1207  } else {
1208  switch (out_byte_width) {
1209  case 4: {
1210  int32_t agg_result = static_cast<int32_t>(agg_init_val);
1211  for (size_t i = 0; i < out_vec_sz; ++i) {
1213  &agg_result,
1214  *reinterpret_cast<const float*>(may_alias_ptr(&out_vec[i])),
1215  *reinterpret_cast<const float*>(may_alias_ptr(&agg_init_val)));
1216  }
1217  const int64_t converted_bin =
1218  float_argument_input ? static_cast<int64_t>(agg_result)
1219  : float_to_double_bin(agg_result, !ti.get_notnull());
1220  return {converted_bin, 0};
1221  }
1222  case 8: {
1223  int64_t agg_result = agg_init_val;
1224  for (size_t i = 0; i < out_vec_sz; ++i) {
1226  &agg_result,
1227  *reinterpret_cast<const double*>(may_alias_ptr(&out_vec[i])),
1228  *reinterpret_cast<const double*>(may_alias_ptr(&agg_init_val)));
1229  }
1230  return {agg_result, 0};
1231  }
1232  default:
1233  CHECK(false);
1234  }
1235  }
1236  case kSINGLE_VALUE: {
1237  int64_t agg_result = agg_init_val;
1238  for (size_t i = 0; i < out_vec_sz; ++i) {
1239  if (out_vec[i] != agg_init_val) {
1240  if (agg_result == agg_init_val) {
1241  agg_result = out_vec[i];
1242  } else if (out_vec[i] != agg_result) {
1244  }
1245  }
1246  }
1247  return {agg_result, 0};
1248  }
1249  case kSAMPLE: {
1250  int64_t agg_result = agg_init_val;
1251  for (size_t i = 0; i < out_vec_sz; ++i) {
1252  if (out_vec[i] != agg_init_val) {
1253  agg_result = out_vec[i];
1254  break;
1255  }
1256  }
1257  return {agg_result, 0};
1258  }
1259  default:
1260  CHECK(false);
1261  }
1262  abort();
1263 }
1264 
1265 namespace {
1266 
1268  std::vector<std::pair<ResultSetPtr, std::vector<size_t>>>& results_per_device,
1269  std::vector<TargetInfo> const& targets) {
1270  auto& first = results_per_device.front().first;
1271  CHECK(first);
1272  auto const first_target_idx = result_set::first_dict_encoded_idx(targets);
1273  if (first_target_idx) {
1274  first->translateDictEncodedColumns(targets, *first_target_idx);
1275  }
1276  for (size_t dev_idx = 1; dev_idx < results_per_device.size(); ++dev_idx) {
1277  const auto& next = results_per_device[dev_idx].first;
1278  CHECK(next);
1279  if (first_target_idx) {
1280  next->translateDictEncodedColumns(targets, *first_target_idx);
1281  }
1282  first->append(*next);
1283  }
1284  return std::move(first);
1285 }
1286 
1288  TargetInfo operator()(Analyzer::Expr const* const target_expr) const {
1289  return get_target_info(target_expr, g_bigint_count);
1290  }
1291 };
1292 
1293 } // namespace
1294 
1296  const RelAlgExecutionUnit& ra_exe_unit) {
1297  auto timer = DEBUG_TIMER(__func__);
1298  auto& results_per_device = shared_context.getFragmentResults();
1299  auto const targets = shared::transform<std::vector<TargetInfo>>(
1300  ra_exe_unit.target_exprs, GetTargetInfo{});
1301  if (results_per_device.empty()) {
1302  return std::make_shared<ResultSet>(targets,
1306  catalog_,
1307  blockSize(),
1308  gridSize());
1309  }
1310  using IndexedResultSet = std::pair<ResultSetPtr, std::vector<size_t>>;
1311  std::sort(results_per_device.begin(),
1312  results_per_device.end(),
1313  [](const IndexedResultSet& lhs, const IndexedResultSet& rhs) {
1314  CHECK_GE(lhs.second.size(), size_t(1));
1315  CHECK_GE(rhs.second.size(), size_t(1));
1316  return lhs.second.front() < rhs.second.front();
1317  });
1318 
1319  return get_merged_result(results_per_device, targets);
1320 }
1321 
1323  const RelAlgExecutionUnit& ra_exe_unit,
1324  std::vector<std::pair<ResultSetPtr, std::vector<size_t>>>& results_per_device,
1325  std::shared_ptr<RowSetMemoryOwner> row_set_mem_owner,
1326  const QueryMemoryDescriptor& query_mem_desc) const {
1327  auto timer = DEBUG_TIMER(__func__);
1328  if (ra_exe_unit.estimator) {
1329  return reduce_estimator_results(ra_exe_unit, results_per_device);
1330  }
1331 
1332  if (results_per_device.empty()) {
1333  auto const targets = shared::transform<std::vector<TargetInfo>>(
1334  ra_exe_unit.target_exprs, GetTargetInfo{});
1335  return std::make_shared<ResultSet>(targets,
1338  nullptr,
1339  catalog_,
1340  blockSize(),
1341  gridSize());
1342  }
1343 
1345  results_per_device,
1346  row_set_mem_owner,
1347  ResultSet::fixupQueryMemoryDescriptor(query_mem_desc));
1348 }
1349 
1350 namespace {
1351 
1353  const size_t executor_id,
1354  std::vector<std::pair<ResultSetPtr, std::vector<size_t>>>& results_per_device,
1355  int64_t* compilation_queue_time) {
1356  auto clock_begin = timer_start();
1357  // ResultSetReductionJIT::codegen compilation-locks if new code will be generated
1358  *compilation_queue_time = timer_stop(clock_begin);
1359  const auto& this_result_set = results_per_device[0].first;
1360  ResultSetReductionJIT reduction_jit(this_result_set->getQueryMemDesc(),
1361  this_result_set->getTargetInfos(),
1362  this_result_set->getTargetInitVals(),
1363  executor_id);
1364  return reduction_jit.codegen();
1365 };
1366 
1367 } // namespace
1368 
1370  std::vector<std::pair<ResultSetPtr, std::vector<size_t>>>& results_per_device,
1371  std::shared_ptr<RowSetMemoryOwner> row_set_mem_owner,
1372  const QueryMemoryDescriptor& query_mem_desc) const {
1373  auto timer = DEBUG_TIMER(__func__);
1374  std::shared_ptr<ResultSet> reduced_results;
1375 
1376  const auto& first = results_per_device.front().first;
1377 
1378  if (query_mem_desc.getQueryDescriptionType() ==
1380  results_per_device.size() > 1) {
1381  const auto total_entry_count = std::accumulate(
1382  results_per_device.begin(),
1383  results_per_device.end(),
1384  size_t(0),
1385  [](const size_t init, const std::pair<ResultSetPtr, std::vector<size_t>>& rs) {
1386  const auto& r = rs.first;
1387  return init + r->getQueryMemDesc().getEntryCount();
1388  });
1389  CHECK(total_entry_count);
1390  auto query_mem_desc = first->getQueryMemDesc();
1391  query_mem_desc.setEntryCount(total_entry_count);
1392  reduced_results = std::make_shared<ResultSet>(first->getTargetInfos(),
1395  row_set_mem_owner,
1396  catalog_,
1397  blockSize(),
1398  gridSize());
1399  auto result_storage = reduced_results->allocateStorage(plan_state_->init_agg_vals_);
1400  reduced_results->initializeStorage();
1401  switch (query_mem_desc.getEffectiveKeyWidth()) {
1402  case 4:
1403  first->getStorage()->moveEntriesToBuffer<int32_t>(
1404  result_storage->getUnderlyingBuffer(), query_mem_desc.getEntryCount());
1405  break;
1406  case 8:
1407  first->getStorage()->moveEntriesToBuffer<int64_t>(
1408  result_storage->getUnderlyingBuffer(), query_mem_desc.getEntryCount());
1409  break;
1410  default:
1411  CHECK(false);
1412  }
1413  } else {
1414  reduced_results = first;
1415  }
1416 
1417  int64_t compilation_queue_time = 0;
1418  const auto reduction_code =
1419  get_reduction_code(executor_id_, results_per_device, &compilation_queue_time);
1420 
1421  for (size_t i = 1; i < results_per_device.size(); ++i) {
1422  reduced_results->getStorage()->reduce(
1423  *(results_per_device[i].first->getStorage()), {}, reduction_code, executor_id_);
1424  }
1425  reduced_results->addCompilationQueueTime(compilation_queue_time);
1426  return reduced_results;
1427 }
1428 
1430  const RelAlgExecutionUnit& ra_exe_unit,
1431  std::vector<std::pair<ResultSetPtr, std::vector<size_t>>>& results_per_device,
1432  std::shared_ptr<RowSetMemoryOwner> row_set_mem_owner,
1433  const QueryMemoryDescriptor& query_mem_desc) const {
1434  if (results_per_device.size() == 1) {
1435  return std::move(results_per_device.front().first);
1436  }
1437  const auto top_n = ra_exe_unit.sort_info.limit + ra_exe_unit.sort_info.offset;
1439  for (const auto& result : results_per_device) {
1440  auto rows = result.first;
1441  CHECK(rows);
1442  if (!rows) {
1443  continue;
1444  }
1445  SpeculativeTopNMap that(
1446  *rows,
1447  ra_exe_unit.target_exprs,
1448  std::max(size_t(10000 * std::max(1, static_cast<int>(log(top_n)))), top_n));
1449  m.reduce(that);
1450  }
1451  CHECK_EQ(size_t(1), ra_exe_unit.sort_info.order_entries.size());
1452  const auto desc = ra_exe_unit.sort_info.order_entries.front().is_desc;
1453  return m.asRows(ra_exe_unit, row_set_mem_owner, query_mem_desc, this, top_n, desc);
1454 }
1455 
1456 std::unordered_set<int> get_available_gpus(const Data_Namespace::DataMgr* data_mgr) {
1457  CHECK(data_mgr);
1458  std::unordered_set<int> available_gpus;
1459  if (data_mgr->gpusPresent()) {
1460  CHECK(data_mgr->getCudaMgr());
1461  const int gpu_count = data_mgr->getCudaMgr()->getDeviceCount();
1462  CHECK_GT(gpu_count, 0);
1463  for (int gpu_id = 0; gpu_id < gpu_count; ++gpu_id) {
1464  available_gpus.insert(gpu_id);
1465  }
1466  }
1467  return available_gpus;
1468 }
1469 
1470 size_t get_context_count(const ExecutorDeviceType device_type,
1471  const size_t cpu_count,
1472  const size_t gpu_count) {
1473  return device_type == ExecutorDeviceType::GPU ? gpu_count
1474  : static_cast<size_t>(cpu_count);
1475 }
1476 
1477 namespace {
1478 
1479 // Compute a very conservative entry count for the output buffer entry count using no
1480 // other information than the number of tuples in each table and multiplying them
1481 // together.
1482 size_t compute_buffer_entry_guess(const std::vector<InputTableInfo>& query_infos) {
1484  // Check for overflows since we're multiplying potentially big table sizes.
1485  using checked_size_t = boost::multiprecision::number<
1486  boost::multiprecision::cpp_int_backend<64,
1487  64,
1488  boost::multiprecision::unsigned_magnitude,
1489  boost::multiprecision::checked,
1490  void>>;
1491  checked_size_t max_groups_buffer_entry_guess = 1;
1492  for (const auto& query_info : query_infos) {
1493  CHECK(!query_info.info.fragments.empty());
1494  auto it = std::max_element(query_info.info.fragments.begin(),
1495  query_info.info.fragments.end(),
1496  [](const FragmentInfo& f1, const FragmentInfo& f2) {
1497  return f1.getNumTuples() < f2.getNumTuples();
1498  });
1499  max_groups_buffer_entry_guess *= it->getNumTuples();
1500  }
1501  // Cap the rough approximation to 100M entries, it's unlikely we can do a great job for
1502  // baseline group layout with that many entries anyway.
1503  constexpr size_t max_groups_buffer_entry_guess_cap = 100000000;
1504  try {
1505  return std::min(static_cast<size_t>(max_groups_buffer_entry_guess),
1506  max_groups_buffer_entry_guess_cap);
1507  } catch (...) {
1508  return max_groups_buffer_entry_guess_cap;
1509  }
1510 }
1511 
1512 std::string get_table_name(const InputDescriptor& input_desc,
1514  const auto source_type = input_desc.getSourceType();
1515  if (source_type == InputSourceType::TABLE) {
1516  const auto td = cat.getMetadataForTable(input_desc.getTableId());
1517  CHECK(td);
1518  return td->tableName;
1519  } else {
1520  return "$TEMPORARY_TABLE" + std::to_string(-input_desc.getTableId());
1521  }
1522 }
1523 
1524 inline size_t getDeviceBasedScanLimit(const ExecutorDeviceType device_type,
1525  const int device_count) {
1526  if (device_type == ExecutorDeviceType::GPU) {
1527  return device_count * Executor::high_scan_limit;
1528  }
1530 }
1531 
1533  const std::vector<InputTableInfo>& table_infos,
1535  const ExecutorDeviceType device_type,
1536  const int device_count) {
1537  for (const auto target_expr : ra_exe_unit.target_exprs) {
1538  if (dynamic_cast<const Analyzer::AggExpr*>(target_expr)) {
1539  return;
1540  }
1541  }
1542  if (!ra_exe_unit.scan_limit && table_infos.size() == 1 &&
1543  table_infos.front().info.getPhysicalNumTuples() < Executor::high_scan_limit) {
1544  // Allow a query with no scan limit to run on small tables
1545  return;
1546  }
1547  if (ra_exe_unit.use_bump_allocator) {
1548  // Bump allocator removes the scan limit (and any knowledge of the size of the output
1549  // relative to the size of the input), so we bypass this check for now
1550  return;
1551  }
1552  if (ra_exe_unit.sort_info.algorithm != SortAlgorithm::StreamingTopN &&
1553  ra_exe_unit.groupby_exprs.size() == 1 && !ra_exe_unit.groupby_exprs.front() &&
1554  (!ra_exe_unit.scan_limit ||
1555  ra_exe_unit.scan_limit > getDeviceBasedScanLimit(device_type, device_count))) {
1556  std::vector<std::string> table_names;
1557  const auto& input_descs = ra_exe_unit.input_descs;
1558  for (const auto& input_desc : input_descs) {
1559  table_names.push_back(get_table_name(input_desc, cat));
1560  }
1561  if (!ra_exe_unit.scan_limit) {
1562  throw WatchdogException(
1563  "Projection query would require a scan without a limit on table(s): " +
1564  boost::algorithm::join(table_names, ", "));
1565  } else {
1566  throw WatchdogException(
1567  "Projection query output result set on table(s): " +
1568  boost::algorithm::join(table_names, ", ") + " would contain " +
1569  std::to_string(ra_exe_unit.scan_limit) +
1570  " rows, which is more than the current system limit of " +
1571  std::to_string(getDeviceBasedScanLimit(device_type, device_count)));
1572  }
1573  }
1574 }
1575 
1576 } // namespace
1577 
1578 bool is_trivial_loop_join(const std::vector<InputTableInfo>& query_infos,
1579  const RelAlgExecutionUnit& ra_exe_unit) {
1580  if (ra_exe_unit.input_descs.size() < 2) {
1581  return false;
1582  }
1583 
1584  // We only support loop join at the end of folded joins
1585  // where ra_exe_unit.input_descs.size() > 2 for now.
1586  const auto inner_table_id = ra_exe_unit.input_descs.back().getTableId();
1587 
1588  std::optional<size_t> inner_table_idx;
1589  for (size_t i = 0; i < query_infos.size(); ++i) {
1590  if (query_infos[i].table_id == inner_table_id) {
1591  inner_table_idx = i;
1592  break;
1593  }
1594  }
1595  CHECK(inner_table_idx);
1596  return query_infos[*inner_table_idx].info.getNumTuples() <=
1598 }
1599 
1600 namespace {
1601 
1602 template <typename T>
1603 std::vector<std::string> expr_container_to_string(const T& expr_container) {
1604  std::vector<std::string> expr_strs;
1605  for (const auto& expr : expr_container) {
1606  if (!expr) {
1607  expr_strs.emplace_back("NULL");
1608  } else {
1609  expr_strs.emplace_back(expr->toString());
1610  }
1611  }
1612  return expr_strs;
1613 }
1614 
1615 template <>
1616 std::vector<std::string> expr_container_to_string(
1617  const std::list<Analyzer::OrderEntry>& expr_container) {
1618  std::vector<std::string> expr_strs;
1619  for (const auto& expr : expr_container) {
1620  expr_strs.emplace_back(expr.toString());
1621  }
1622  return expr_strs;
1623 }
1624 
1625 std::string sort_algorithm_to_string(const SortAlgorithm algorithm) {
1626  switch (algorithm) {
1628  return "ResultSet";
1630  return "Speculative Top N";
1632  return "Streaming Top N";
1633  }
1634  UNREACHABLE();
1635  return "";
1636 }
1637 
1638 } // namespace
1639 
1640 std::string ra_exec_unit_desc_for_caching(const RelAlgExecutionUnit& ra_exe_unit) {
1641  // todo(yoonmin): replace a cache key as a DAG representation of a query plan
1642  // instead of ra_exec_unit description if possible
1643  std::ostringstream os;
1644  for (const auto& input_col_desc : ra_exe_unit.input_col_descs) {
1645  const auto& scan_desc = input_col_desc->getScanDesc();
1646  os << scan_desc.getTableId() << "," << input_col_desc->getColId() << ","
1647  << scan_desc.getNestLevel();
1648  }
1649  if (!ra_exe_unit.simple_quals.empty()) {
1650  for (const auto& qual : ra_exe_unit.simple_quals) {
1651  if (qual) {
1652  os << qual->toString() << ",";
1653  }
1654  }
1655  }
1656  if (!ra_exe_unit.quals.empty()) {
1657  for (const auto& qual : ra_exe_unit.quals) {
1658  if (qual) {
1659  os << qual->toString() << ",";
1660  }
1661  }
1662  }
1663  if (!ra_exe_unit.join_quals.empty()) {
1664  for (size_t i = 0; i < ra_exe_unit.join_quals.size(); i++) {
1665  const auto& join_condition = ra_exe_unit.join_quals[i];
1666  os << std::to_string(i) << ::toString(join_condition.type);
1667  for (const auto& qual : join_condition.quals) {
1668  if (qual) {
1669  os << qual->toString() << ",";
1670  }
1671  }
1672  }
1673  }
1674  if (!ra_exe_unit.groupby_exprs.empty()) {
1675  for (const auto& qual : ra_exe_unit.groupby_exprs) {
1676  if (qual) {
1677  os << qual->toString() << ",";
1678  }
1679  }
1680  }
1681  for (const auto& expr : ra_exe_unit.target_exprs) {
1682  if (expr) {
1683  os << expr->toString() << ",";
1684  }
1685  }
1686  os << ::toString(ra_exe_unit.estimator == nullptr);
1687  os << std::to_string(ra_exe_unit.scan_limit);
1688  return os.str();
1689 }
1690 
1691 std::ostream& operator<<(std::ostream& os, const RelAlgExecutionUnit& ra_exe_unit) {
1692  os << "\n\tExtracted Query Plan Dag Hash: " << ra_exe_unit.query_plan_dag_hash;
1693  os << "\n\tTable/Col/Levels: ";
1694  for (const auto& input_col_desc : ra_exe_unit.input_col_descs) {
1695  const auto& scan_desc = input_col_desc->getScanDesc();
1696  os << "(" << scan_desc.getTableId() << ", " << input_col_desc->getColId() << ", "
1697  << scan_desc.getNestLevel() << ") ";
1698  }
1699  if (!ra_exe_unit.simple_quals.empty()) {
1700  os << "\n\tSimple Quals: "
1702  ", ");
1703  }
1704  if (!ra_exe_unit.quals.empty()) {
1705  os << "\n\tQuals: "
1706  << boost::algorithm::join(expr_container_to_string(ra_exe_unit.quals), ", ");
1707  }
1708  if (!ra_exe_unit.join_quals.empty()) {
1709  os << "\n\tJoin Quals: ";
1710  for (size_t i = 0; i < ra_exe_unit.join_quals.size(); i++) {
1711  const auto& join_condition = ra_exe_unit.join_quals[i];
1712  os << "\t\t" << std::to_string(i) << " " << ::toString(join_condition.type);
1713  os << boost::algorithm::join(expr_container_to_string(join_condition.quals), ", ");
1714  }
1715  }
1716  if (!ra_exe_unit.groupby_exprs.empty()) {
1717  os << "\n\tGroup By: "
1719  ", ");
1720  }
1721  os << "\n\tProjected targets: "
1723  os << "\n\tHas Estimator: " << ::toString(ra_exe_unit.estimator == nullptr);
1724  os << "\n\tSort Info: ";
1725  const auto& sort_info = ra_exe_unit.sort_info;
1726  os << "\n\t Order Entries: "
1727  << boost::algorithm::join(expr_container_to_string(sort_info.order_entries), ", ");
1728  os << "\n\t Algorithm: " << sort_algorithm_to_string(sort_info.algorithm);
1729  os << "\n\t Limit: " << std::to_string(sort_info.limit);
1730  os << "\n\t Offset: " << std::to_string(sort_info.offset);
1731  os << "\n\tScan Limit: " << std::to_string(ra_exe_unit.scan_limit);
1732  os << "\n\tBump Allocator: " << ::toString(ra_exe_unit.use_bump_allocator);
1733  if (ra_exe_unit.union_all) {
1734  os << "\n\tUnion: " << std::string(*ra_exe_unit.union_all ? "UNION ALL" : "UNION");
1735  }
1736  return os;
1737 }
1738 
1739 namespace {
1740 
1742  const size_t new_scan_limit) {
1743  return {ra_exe_unit_in.input_descs,
1744  ra_exe_unit_in.input_col_descs,
1745  ra_exe_unit_in.simple_quals,
1746  ra_exe_unit_in.quals,
1747  ra_exe_unit_in.join_quals,
1748  ra_exe_unit_in.groupby_exprs,
1749  ra_exe_unit_in.target_exprs,
1750  ra_exe_unit_in.target_exprs_original_type_infos,
1751  ra_exe_unit_in.estimator,
1752  ra_exe_unit_in.sort_info,
1753  new_scan_limit,
1754  ra_exe_unit_in.query_hint,
1755  ra_exe_unit_in.query_plan_dag_hash,
1756  ra_exe_unit_in.hash_table_build_plan_dag,
1757  ra_exe_unit_in.table_id_to_node_map,
1758  ra_exe_unit_in.use_bump_allocator,
1759  ra_exe_unit_in.union_all,
1760  ra_exe_unit_in.query_state};
1761 }
1762 
1763 } // namespace
1764 
1765 ResultSetPtr Executor::executeWorkUnit(size_t& max_groups_buffer_entry_guess,
1766  const bool is_agg,
1767  const std::vector<InputTableInfo>& query_infos,
1768  const RelAlgExecutionUnit& ra_exe_unit_in,
1769  const CompilationOptions& co,
1770  const ExecutionOptions& eo,
1772  RenderInfo* render_info,
1773  const bool has_cardinality_estimation,
1774  ColumnCacheMap& column_cache) {
1775  VLOG(1) << "Executor " << executor_id_ << " is executing work unit:" << ra_exe_unit_in;
1776 
1777  ScopeGuard cleanup_post_execution = [this] {
1778  // cleanup/unpin GPU buffer allocations
1779  // TODO: separate out this state into a single object
1780  plan_state_.reset(nullptr);
1781  if (cgen_state_) {
1782  cgen_state_->in_values_bitmaps_.clear();
1783  cgen_state_->str_dict_translation_mgrs_.clear();
1784  }
1785  };
1786 
1787  try {
1788  auto result = executeWorkUnitImpl(max_groups_buffer_entry_guess,
1789  is_agg,
1790  true,
1791  query_infos,
1792  ra_exe_unit_in,
1793  co,
1794  eo,
1795  cat,
1797  render_info,
1798  has_cardinality_estimation,
1799  column_cache);
1800  if (result) {
1801  result->setKernelQueueTime(kernel_queue_time_ms_);
1802  result->addCompilationQueueTime(compilation_queue_time_ms_);
1803  if (eo.just_validate) {
1804  result->setValidationOnlyRes();
1805  }
1806  }
1807  return result;
1808  } catch (const CompilationRetryNewScanLimit& e) {
1809  auto result =
1810  executeWorkUnitImpl(max_groups_buffer_entry_guess,
1811  is_agg,
1812  false,
1813  query_infos,
1814  replace_scan_limit(ra_exe_unit_in, e.new_scan_limit_),
1815  co,
1816  eo,
1817  cat,
1819  render_info,
1820  has_cardinality_estimation,
1821  column_cache);
1822  if (result) {
1823  result->setKernelQueueTime(kernel_queue_time_ms_);
1824  result->addCompilationQueueTime(compilation_queue_time_ms_);
1825  if (eo.just_validate) {
1826  result->setValidationOnlyRes();
1827  }
1828  }
1829  return result;
1830  }
1831 }
1832 
1834  size_t& max_groups_buffer_entry_guess,
1835  const bool is_agg,
1836  const bool allow_single_frag_table_opt,
1837  const std::vector<InputTableInfo>& query_infos,
1838  const RelAlgExecutionUnit& ra_exe_unit_in,
1839  const CompilationOptions& co,
1840  const ExecutionOptions& eo,
1842  std::shared_ptr<RowSetMemoryOwner> row_set_mem_owner,
1843  RenderInfo* render_info,
1844  const bool has_cardinality_estimation,
1845  ColumnCacheMap& column_cache) {
1846  INJECT_TIMER(Exec_executeWorkUnit);
1847  const auto [ra_exe_unit, deleted_cols_map] = addDeletedColumn(ra_exe_unit_in, co);
1848  const auto device_type = getDeviceTypeForTargets(ra_exe_unit, co.device_type);
1849  CHECK(!query_infos.empty());
1850  if (!max_groups_buffer_entry_guess) {
1851  // The query has failed the first execution attempt because of running out
1852  // of group by slots. Make the conservative choice: allocate fragment size
1853  // slots and run on the CPU.
1854  CHECK(device_type == ExecutorDeviceType::CPU);
1855  max_groups_buffer_entry_guess = compute_buffer_entry_guess(query_infos);
1856  }
1857 
1858  int8_t crt_min_byte_width{MAX_BYTE_WIDTH_SUPPORTED};
1859  do {
1860  SharedKernelContext shared_context(query_infos);
1861  ColumnFetcher column_fetcher(this, column_cache);
1862  ScopeGuard scope_guard = [&column_fetcher] {
1863  column_fetcher.freeLinearizedBuf();
1864  column_fetcher.freeTemporaryCpuLinearizedIdxBuf();
1865  };
1866  auto query_comp_desc_owned = std::make_unique<QueryCompilationDescriptor>();
1867  std::unique_ptr<QueryMemoryDescriptor> query_mem_desc_owned;
1868 
1869  if (eo.executor_type == ExecutorType::Native) {
1870  try {
1871  INJECT_TIMER(query_step_compilation);
1872  query_mem_desc_owned =
1873  query_comp_desc_owned->compile(max_groups_buffer_entry_guess,
1874  crt_min_byte_width,
1875  has_cardinality_estimation,
1876  ra_exe_unit,
1877  query_infos,
1878  deleted_cols_map,
1879  column_fetcher,
1880  {device_type,
1881  co.hoist_literals,
1882  co.opt_level,
1884  co.allow_lazy_fetch,
1886  co.explain_type,
1888  eo,
1889  render_info,
1890  this);
1891  CHECK(query_mem_desc_owned);
1892  crt_min_byte_width = query_comp_desc_owned->getMinByteWidth();
1893  } catch (CompilationRetryNoCompaction&) {
1894  crt_min_byte_width = MAX_BYTE_WIDTH_SUPPORTED;
1895  continue;
1896  }
1897  } else {
1898  plan_state_.reset(new PlanState(false, query_infos, deleted_cols_map, this));
1899  plan_state_->allocateLocalColumnIds(ra_exe_unit.input_col_descs);
1900  CHECK(!query_mem_desc_owned);
1901  query_mem_desc_owned.reset(
1903  }
1904  if (eo.just_explain) {
1905  return executeExplain(*query_comp_desc_owned);
1906  }
1907 
1908  for (const auto target_expr : ra_exe_unit.target_exprs) {
1909  plan_state_->target_exprs_.push_back(target_expr);
1910  }
1911 
1912  if (!eo.just_validate) {
1913  int available_cpus = cpu_threads();
1914  auto available_gpus = get_available_gpus(data_mgr_);
1915 
1916  const auto context_count =
1917  get_context_count(device_type, available_cpus, available_gpus.size());
1918  try {
1919  auto kernels = createKernels(shared_context,
1920  ra_exe_unit,
1921  column_fetcher,
1922  query_infos,
1923  eo,
1924  is_agg,
1925  allow_single_frag_table_opt,
1926  context_count,
1927  *query_comp_desc_owned,
1928  *query_mem_desc_owned,
1929  render_info,
1930  available_gpus,
1931  available_cpus);
1932  launchKernels(
1933  shared_context, std::move(kernels), query_comp_desc_owned->getDeviceType());
1934  } catch (QueryExecutionError& e) {
1935  if (eo.with_dynamic_watchdog && interrupted_.load() &&
1936  e.getErrorCode() == ERR_OUT_OF_TIME) {
1938  }
1939  if (e.getErrorCode() == ERR_INTERRUPTED) {
1941  }
1943  static_cast<size_t>(crt_min_byte_width << 1) <= sizeof(int64_t)) {
1944  crt_min_byte_width <<= 1;
1945  continue;
1946  }
1947  throw;
1948  }
1949  }
1950  if (is_agg) {
1951  if (eo.allow_runtime_query_interrupt && ra_exe_unit.query_state) {
1952  // update query status to let user know we are now in the reduction phase
1953  std::string curRunningSession{""};
1954  std::string curRunningQuerySubmittedTime{""};
1955  bool sessionEnrolled = false;
1956  {
1959  curRunningSession = getCurrentQuerySession(session_read_lock);
1960  curRunningQuerySubmittedTime = ra_exe_unit.query_state->getQuerySubmittedTime();
1961  sessionEnrolled =
1962  checkIsQuerySessionEnrolled(curRunningSession, session_read_lock);
1963  }
1964  if (!curRunningSession.empty() && !curRunningQuerySubmittedTime.empty() &&
1965  sessionEnrolled) {
1966  updateQuerySessionStatus(curRunningSession,
1967  curRunningQuerySubmittedTime,
1969  }
1970  }
1971  try {
1972  return collectAllDeviceResults(shared_context,
1973  ra_exe_unit,
1974  *query_mem_desc_owned,
1975  query_comp_desc_owned->getDeviceType(),
1976  row_set_mem_owner);
1977  } catch (ReductionRanOutOfSlots&) {
1979  } catch (OverflowOrUnderflow&) {
1980  crt_min_byte_width <<= 1;
1981  continue;
1982  } catch (QueryExecutionError& e) {
1983  VLOG(1) << "Error received! error_code: " << e.getErrorCode()
1984  << ", what(): " << e.what();
1985  throw QueryExecutionError(e.getErrorCode());
1986  }
1987  }
1988  return resultsUnion(shared_context, ra_exe_unit);
1989 
1990  } while (static_cast<size_t>(crt_min_byte_width) <= sizeof(int64_t));
1991 
1992  return std::make_shared<ResultSet>(std::vector<TargetInfo>{},
1995  nullptr,
1996  catalog_,
1997  blockSize(),
1998  gridSize());
1999 }
2000 
2002  const RelAlgExecutionUnit& ra_exe_unit_in,
2003  const InputTableInfo& table_info,
2004  const CompilationOptions& co,
2005  const ExecutionOptions& eo,
2007  PerFragmentCallBack& cb,
2008  const std::set<size_t>& fragment_indexes_param) {
2009  const auto [ra_exe_unit, deleted_cols_map] = addDeletedColumn(ra_exe_unit_in, co);
2010  ColumnCacheMap column_cache;
2011 
2012  std::vector<InputTableInfo> table_infos{table_info};
2013  SharedKernelContext kernel_context(table_infos);
2014 
2015  ColumnFetcher column_fetcher(this, column_cache);
2016  auto query_comp_desc_owned = std::make_unique<QueryCompilationDescriptor>();
2017  std::unique_ptr<QueryMemoryDescriptor> query_mem_desc_owned;
2018  {
2019  query_mem_desc_owned =
2020  query_comp_desc_owned->compile(0,
2021  8,
2022  /*has_cardinality_estimation=*/false,
2023  ra_exe_unit,
2024  table_infos,
2025  deleted_cols_map,
2026  column_fetcher,
2027  co,
2028  eo,
2029  nullptr,
2030  this);
2031  }
2032  CHECK(query_mem_desc_owned);
2033  CHECK_EQ(size_t(1), ra_exe_unit.input_descs.size());
2034  const auto table_id = ra_exe_unit.input_descs[0].getTableId();
2035  const auto& outer_fragments = table_info.info.fragments;
2036 
2037  std::set<size_t> fragment_indexes;
2038  if (fragment_indexes_param.empty()) {
2039  // An empty `fragment_indexes_param` set implies executing
2040  // the query for all fragments in the table. In this
2041  // case, populate `fragment_indexes` with all fragment indexes.
2042  for (size_t i = 0; i < outer_fragments.size(); i++) {
2043  fragment_indexes.emplace(i);
2044  }
2045  } else {
2046  fragment_indexes = fragment_indexes_param;
2047  }
2048 
2049  {
2050  auto clock_begin = timer_start();
2051  std::lock_guard<std::mutex> kernel_lock(kernel_mutex_);
2052  kernel_queue_time_ms_ += timer_stop(clock_begin);
2053 
2054  for (auto fragment_index : fragment_indexes) {
2055  // We may want to consider in the future allowing this to execute on devices other
2056  // than CPU
2057  FragmentsList fragments_list{{table_id, {fragment_index}}};
2058  ExecutionKernel kernel(ra_exe_unit,
2059  co.device_type,
2060  /*device_id=*/0,
2061  eo,
2062  column_fetcher,
2063  *query_comp_desc_owned,
2064  *query_mem_desc_owned,
2065  fragments_list,
2067  /*render_info=*/nullptr,
2068  /*rowid_lookup_key=*/-1);
2069  kernel.run(this, 0, kernel_context);
2070  }
2071  }
2072 
2073  const auto& all_fragment_results = kernel_context.getFragmentResults();
2074 
2075  for (const auto& [result_set_ptr, result_fragment_indexes] : all_fragment_results) {
2076  CHECK_EQ(result_fragment_indexes.size(), 1);
2077  cb(result_set_ptr, outer_fragments[result_fragment_indexes[0]]);
2078  }
2079 }
2080 
2082  const TableFunctionExecutionUnit exe_unit,
2083  const std::vector<InputTableInfo>& table_infos,
2084  const CompilationOptions& co,
2085  const ExecutionOptions& eo,
2087  INJECT_TIMER(Exec_executeTableFunction);
2088  if (eo.just_validate) {
2090  /*entry_count=*/0,
2092  /*is_table_function=*/true);
2093  query_mem_desc.setOutputColumnar(true);
2094  return std::make_shared<ResultSet>(
2095  target_exprs_to_infos(exe_unit.target_exprs, query_mem_desc),
2096  co.device_type,
2097  ResultSet::fixupQueryMemoryDescriptor(query_mem_desc),
2098  this->getRowSetMemoryOwner(),
2099  this->getCatalog(),
2100  this->blockSize(),
2101  this->gridSize());
2102  }
2103 
2104  // Avoid compile functions that set the sizer at runtime if the device is GPU
2105  // This should be fixed in the python script as well to minimize the number of
2106  // QueryMustRunOnCpu exceptions
2109  throw QueryMustRunOnCpu();
2110  }
2111 
2112  ColumnCacheMap column_cache; // Note: if we add retries to the table function
2113  // framework, we may want to move this up a level
2114 
2115  ColumnFetcher column_fetcher(this, column_cache);
2117 
2118  if (exe_unit.table_func.containsPreFlightFn()) {
2119  std::shared_ptr<CompilationContext> compilation_context;
2120  {
2121  Executor::CgenStateManager cgenstate_manager(*this,
2122  false,
2123  table_infos,
2125  nullptr); // locks compilation_mutex
2127  TableFunctionCompilationContext tf_compilation_context(this, pre_flight_co);
2128  compilation_context =
2129  tf_compilation_context.compile(exe_unit, true /* emit_only_preflight_fn*/);
2130  }
2131  exe_context.execute(exe_unit,
2132  table_infos,
2133  compilation_context,
2134  column_fetcher,
2136  this,
2137  true /* is_pre_launch_udtf */);
2138  }
2139  std::shared_ptr<CompilationContext> compilation_context;
2140  {
2141  Executor::CgenStateManager cgenstate_manager(*this,
2142  false,
2143  table_infos,
2145  nullptr); // locks compilation_mutex
2146  TableFunctionCompilationContext tf_compilation_context(this, co);
2147  compilation_context =
2148  tf_compilation_context.compile(exe_unit, false /* emit_only_preflight_fn */);
2149  }
2150  return exe_context.execute(exe_unit,
2151  table_infos,
2152  compilation_context,
2153  column_fetcher,
2154  co.device_type,
2155  this,
2156  false /* is_pre_launch_udtf */);
2157 }
2158 
2160  return std::make_shared<ResultSet>(query_comp_desc.getIR());
2161 }
2162 
2164  const RelAlgExecutionUnit& ra_exe_unit,
2165  const std::shared_ptr<RowSetMemoryOwner>& row_set_mem_owner) {
2166  TransientDictIdVisitor dict_id_visitor;
2167 
2168  auto visit_expr =
2169  [this, &dict_id_visitor, &row_set_mem_owner](const Analyzer::Expr* expr) {
2170  if (!expr) {
2171  return;
2172  }
2173  const auto dict_id = dict_id_visitor.visit(expr);
2174  if (dict_id >= 0) {
2175  auto sdp = getStringDictionaryProxy(dict_id, row_set_mem_owner, true);
2176  CHECK(sdp);
2177  TransientStringLiteralsVisitor visitor(sdp, this);
2178  visitor.visit(expr);
2179  }
2180  };
2181 
2182  for (const auto& group_expr : ra_exe_unit.groupby_exprs) {
2183  visit_expr(group_expr.get());
2184  }
2185 
2186  for (const auto& group_expr : ra_exe_unit.quals) {
2187  visit_expr(group_expr.get());
2188  }
2189 
2190  for (const auto& group_expr : ra_exe_unit.simple_quals) {
2191  visit_expr(group_expr.get());
2192  }
2193 
2194  const auto visit_target_expr = [&](const Analyzer::Expr* target_expr) {
2195  const auto& target_type = target_expr->get_type_info();
2196  if (!target_type.is_string() || target_type.get_compression() == kENCODING_DICT) {
2197  const auto agg_expr = dynamic_cast<const Analyzer::AggExpr*>(target_expr);
2198  if (agg_expr) {
2199  if (agg_expr->get_aggtype() == kSINGLE_VALUE ||
2200  agg_expr->get_aggtype() == kSAMPLE) {
2201  visit_expr(agg_expr->get_arg());
2202  }
2203  } else {
2204  visit_expr(target_expr);
2205  }
2206  }
2207  };
2208  const auto& target_exprs = ra_exe_unit.target_exprs;
2209  std::for_each(target_exprs.begin(), target_exprs.end(), visit_target_expr);
2210  const auto& target_exprs_union = ra_exe_unit.target_exprs_union;
2211  std::for_each(target_exprs_union.begin(), target_exprs_union.end(), visit_target_expr);
2212 }
2213 
2215  const RelAlgExecutionUnit& ra_exe_unit,
2216  const ExecutorDeviceType requested_device_type) {
2217  for (const auto target_expr : ra_exe_unit.target_exprs) {
2218  const auto agg_info = get_target_info(target_expr, g_bigint_count);
2219  if (!ra_exe_unit.groupby_exprs.empty() &&
2220  !isArchPascalOrLater(requested_device_type)) {
2221  if ((agg_info.agg_kind == kAVG || agg_info.agg_kind == kSUM) &&
2222  agg_info.agg_arg_type.get_type() == kDOUBLE) {
2223  return ExecutorDeviceType::CPU;
2224  }
2225  }
2226  if (dynamic_cast<const Analyzer::RegexpExpr*>(target_expr)) {
2227  return ExecutorDeviceType::CPU;
2228  }
2229  }
2230  return requested_device_type;
2231 }
2232 
2233 namespace {
2234 
2235 int64_t inline_null_val(const SQLTypeInfo& ti, const bool float_argument_input) {
2236  CHECK(ti.is_number() || ti.is_time() || ti.is_boolean() || ti.is_string());
2237  if (ti.is_fp()) {
2238  if (float_argument_input && ti.get_type() == kFLOAT) {
2239  int64_t float_null_val = 0;
2240  *reinterpret_cast<float*>(may_alias_ptr(&float_null_val)) =
2241  static_cast<float>(inline_fp_null_val(ti));
2242  return float_null_val;
2243  }
2244  const auto double_null_val = inline_fp_null_val(ti);
2245  return *reinterpret_cast<const int64_t*>(may_alias_ptr(&double_null_val));
2246  }
2247  return inline_int_null_val(ti);
2248 }
2249 
2250 void fill_entries_for_empty_input(std::vector<TargetInfo>& target_infos,
2251  std::vector<int64_t>& entry,
2252  const std::vector<Analyzer::Expr*>& target_exprs,
2254  for (size_t target_idx = 0; target_idx < target_exprs.size(); ++target_idx) {
2255  const auto target_expr = target_exprs[target_idx];
2256  const auto agg_info = get_target_info(target_expr, g_bigint_count);
2257  CHECK(agg_info.is_agg);
2258  target_infos.push_back(agg_info);
2259  if (g_cluster) {
2260  const auto executor = query_mem_desc.getExecutor();
2261  CHECK(executor);
2262  auto row_set_mem_owner = executor->getRowSetMemoryOwner();
2263  CHECK(row_set_mem_owner);
2264  const auto& count_distinct_desc =
2265  query_mem_desc.getCountDistinctDescriptor(target_idx);
2266  if (count_distinct_desc.impl_type_ == CountDistinctImplType::Bitmap) {
2267  CHECK(row_set_mem_owner);
2268  auto count_distinct_buffer = row_set_mem_owner->allocateCountDistinctBuffer(
2269  count_distinct_desc.bitmapPaddedSizeBytes(),
2270  /*thread_idx=*/0); // TODO: can we detect thread idx here?
2271  entry.push_back(reinterpret_cast<int64_t>(count_distinct_buffer));
2272  continue;
2273  }
2274  if (count_distinct_desc.impl_type_ == CountDistinctImplType::UnorderedSet) {
2275  auto count_distinct_set = new CountDistinctSet();
2276  CHECK(row_set_mem_owner);
2277  row_set_mem_owner->addCountDistinctSet(count_distinct_set);
2278  entry.push_back(reinterpret_cast<int64_t>(count_distinct_set));
2279  continue;
2280  }
2281  }
2282  const bool float_argument_input = takes_float_argument(agg_info);
2283  if (agg_info.agg_kind == kCOUNT || agg_info.agg_kind == kAPPROX_COUNT_DISTINCT) {
2284  entry.push_back(0);
2285  } else if (agg_info.agg_kind == kAVG) {
2286  entry.push_back(0);
2287  entry.push_back(0);
2288  } else if (agg_info.agg_kind == kSINGLE_VALUE || agg_info.agg_kind == kSAMPLE) {
2289  if (agg_info.sql_type.is_geometry() && !agg_info.is_varlen_projection) {
2290  for (int i = 0; i < agg_info.sql_type.get_physical_coord_cols() * 2; i++) {
2291  entry.push_back(0);
2292  }
2293  } else if (agg_info.sql_type.is_varlen()) {
2294  entry.push_back(0);
2295  entry.push_back(0);
2296  } else {
2297  entry.push_back(inline_null_val(agg_info.sql_type, float_argument_input));
2298  }
2299  } else {
2300  entry.push_back(inline_null_val(agg_info.sql_type, float_argument_input));
2301  }
2302  }
2303 }
2304 
2306  const std::vector<Analyzer::Expr*>& target_exprs_in,
2308  const ExecutorDeviceType device_type) {
2309  std::vector<std::shared_ptr<Analyzer::Expr>> target_exprs_owned_copies;
2310  std::vector<Analyzer::Expr*> target_exprs;
2311  for (const auto target_expr : target_exprs_in) {
2312  const auto target_expr_copy =
2313  std::dynamic_pointer_cast<Analyzer::AggExpr>(target_expr->deep_copy());
2314  CHECK(target_expr_copy);
2315  auto ti = target_expr->get_type_info();
2316  ti.set_notnull(false);
2317  target_expr_copy->set_type_info(ti);
2318  if (target_expr_copy->get_arg()) {
2319  auto arg_ti = target_expr_copy->get_arg()->get_type_info();
2320  arg_ti.set_notnull(false);
2321  target_expr_copy->get_arg()->set_type_info(arg_ti);
2322  }
2323  target_exprs_owned_copies.push_back(target_expr_copy);
2324  target_exprs.push_back(target_expr_copy.get());
2325  }
2326  std::vector<TargetInfo> target_infos;
2327  std::vector<int64_t> entry;
2328  fill_entries_for_empty_input(target_infos, entry, target_exprs, query_mem_desc);
2329  const auto executor = query_mem_desc.getExecutor();
2330  CHECK(executor);
2331  auto row_set_mem_owner = executor->getRowSetMemoryOwner();
2332  CHECK(row_set_mem_owner);
2333  auto rs = std::make_shared<ResultSet>(target_infos,
2334  device_type,
2336  row_set_mem_owner,
2337  executor->getCatalog(),
2338  executor->blockSize(),
2339  executor->gridSize());
2340  rs->allocateStorage();
2341  rs->fillOneEntry(entry);
2342  return rs;
2343 }
2344 
2345 } // namespace
2346 
2348  SharedKernelContext& shared_context,
2349  const RelAlgExecutionUnit& ra_exe_unit,
2351  const ExecutorDeviceType device_type,
2352  std::shared_ptr<RowSetMemoryOwner> row_set_mem_owner) {
2353  auto timer = DEBUG_TIMER(__func__);
2354  auto& result_per_device = shared_context.getFragmentResults();
2355  if (result_per_device.empty() && query_mem_desc.getQueryDescriptionType() ==
2358  ra_exe_unit.target_exprs, query_mem_desc, device_type);
2359  }
2360  if (use_speculative_top_n(ra_exe_unit, query_mem_desc)) {
2361  try {
2362  return reduceSpeculativeTopN(
2363  ra_exe_unit, result_per_device, row_set_mem_owner, query_mem_desc);
2364  } catch (const std::bad_alloc&) {
2365  throw SpeculativeTopNFailed("Failed during multi-device reduction.");
2366  }
2367  }
2368  const auto shard_count =
2369  device_type == ExecutorDeviceType::GPU
2371  : 0;
2372 
2373  if (shard_count && !result_per_device.empty()) {
2374  return collectAllDeviceShardedTopResults(shared_context, ra_exe_unit);
2375  }
2376  return reduceMultiDeviceResults(
2377  ra_exe_unit, result_per_device, row_set_mem_owner, query_mem_desc);
2378 }
2379 
2380 namespace {
2391 size_t permute_storage_columnar(const ResultSetStorage* input_storage,
2392  const QueryMemoryDescriptor& input_query_mem_desc,
2393  const ResultSetStorage* output_storage,
2394  size_t output_row_index,
2395  const QueryMemoryDescriptor& output_query_mem_desc,
2396  const std::vector<uint32_t>& top_permutation) {
2397  const auto output_buffer = output_storage->getUnderlyingBuffer();
2398  const auto input_buffer = input_storage->getUnderlyingBuffer();
2399  for (const auto sorted_idx : top_permutation) {
2400  // permuting all group-columns in this result set into the final buffer:
2401  for (size_t group_idx = 0; group_idx < input_query_mem_desc.getKeyCount();
2402  group_idx++) {
2403  const auto input_column_ptr =
2404  input_buffer + input_query_mem_desc.getPrependedGroupColOffInBytes(group_idx) +
2405  sorted_idx * input_query_mem_desc.groupColWidth(group_idx);
2406  const auto output_column_ptr =
2407  output_buffer +
2408  output_query_mem_desc.getPrependedGroupColOffInBytes(group_idx) +
2409  output_row_index * output_query_mem_desc.groupColWidth(group_idx);
2410  memcpy(output_column_ptr,
2411  input_column_ptr,
2412  output_query_mem_desc.groupColWidth(group_idx));
2413  }
2414  // permuting all agg-columns in this result set into the final buffer:
2415  for (size_t slot_idx = 0; slot_idx < input_query_mem_desc.getSlotCount();
2416  slot_idx++) {
2417  const auto input_column_ptr =
2418  input_buffer + input_query_mem_desc.getColOffInBytes(slot_idx) +
2419  sorted_idx * input_query_mem_desc.getPaddedSlotWidthBytes(slot_idx);
2420  const auto output_column_ptr =
2421  output_buffer + output_query_mem_desc.getColOffInBytes(slot_idx) +
2422  output_row_index * output_query_mem_desc.getPaddedSlotWidthBytes(slot_idx);
2423  memcpy(output_column_ptr,
2424  input_column_ptr,
2425  output_query_mem_desc.getPaddedSlotWidthBytes(slot_idx));
2426  }
2427  ++output_row_index;
2428  }
2429  return output_row_index;
2430 }
2431 
2441 size_t permute_storage_row_wise(const ResultSetStorage* input_storage,
2442  const ResultSetStorage* output_storage,
2443  size_t output_row_index,
2444  const QueryMemoryDescriptor& output_query_mem_desc,
2445  const std::vector<uint32_t>& top_permutation) {
2446  const auto output_buffer = output_storage->getUnderlyingBuffer();
2447  const auto input_buffer = input_storage->getUnderlyingBuffer();
2448  for (const auto sorted_idx : top_permutation) {
2449  const auto row_ptr = input_buffer + sorted_idx * output_query_mem_desc.getRowSize();
2450  memcpy(output_buffer + output_row_index * output_query_mem_desc.getRowSize(),
2451  row_ptr,
2452  output_query_mem_desc.getRowSize());
2453  ++output_row_index;
2454  }
2455  return output_row_index;
2456 }
2457 } // namespace
2458 
2459 // Collect top results from each device, stitch them together and sort. Partial
2460 // results from each device are guaranteed to be disjunct because we only go on
2461 // this path when one of the columns involved is a shard key.
2463  SharedKernelContext& shared_context,
2464  const RelAlgExecutionUnit& ra_exe_unit) const {
2465  auto& result_per_device = shared_context.getFragmentResults();
2466  const auto first_result_set = result_per_device.front().first;
2467  CHECK(first_result_set);
2468  auto top_query_mem_desc = first_result_set->getQueryMemDesc();
2469  CHECK(!top_query_mem_desc.hasInterleavedBinsOnGpu());
2470  const auto top_n = ra_exe_unit.sort_info.limit + ra_exe_unit.sort_info.offset;
2471  top_query_mem_desc.setEntryCount(0);
2472  for (auto& result : result_per_device) {
2473  const auto result_set = result.first;
2474  CHECK(result_set);
2475  result_set->sort(ra_exe_unit.sort_info.order_entries, top_n, this);
2476  size_t new_entry_cnt = top_query_mem_desc.getEntryCount() + result_set->rowCount();
2477  top_query_mem_desc.setEntryCount(new_entry_cnt);
2478  }
2479  auto top_result_set = std::make_shared<ResultSet>(first_result_set->getTargetInfos(),
2480  first_result_set->getDeviceType(),
2481  top_query_mem_desc,
2482  first_result_set->getRowSetMemOwner(),
2483  catalog_,
2484  blockSize(),
2485  gridSize());
2486  auto top_storage = top_result_set->allocateStorage();
2487  size_t top_output_row_idx{0};
2488  for (auto& result : result_per_device) {
2489  const auto result_set = result.first;
2490  CHECK(result_set);
2491  const auto& top_permutation = result_set->getPermutationBuffer();
2492  CHECK_LE(top_permutation.size(), top_n);
2493  if (top_query_mem_desc.didOutputColumnar()) {
2494  top_output_row_idx = permute_storage_columnar(result_set->getStorage(),
2495  result_set->getQueryMemDesc(),
2496  top_storage,
2497  top_output_row_idx,
2498  top_query_mem_desc,
2499  top_permutation);
2500  } else {
2501  top_output_row_idx = permute_storage_row_wise(result_set->getStorage(),
2502  top_storage,
2503  top_output_row_idx,
2504  top_query_mem_desc,
2505  top_permutation);
2506  }
2507  }
2508  CHECK_EQ(top_output_row_idx, top_query_mem_desc.getEntryCount());
2509  return top_result_set;
2510 }
2511 
2512 std::unordered_map<int, const Analyzer::BinOper*> Executor::getInnerTabIdToJoinCond()
2513  const {
2514  std::unordered_map<int, const Analyzer::BinOper*> id_to_cond;
2515  const auto& join_info = plan_state_->join_info_;
2516  CHECK_EQ(join_info.equi_join_tautologies_.size(), join_info.join_hash_tables_.size());
2517  for (size_t i = 0; i < join_info.join_hash_tables_.size(); ++i) {
2518  int inner_table_id = join_info.join_hash_tables_[i]->getInnerTableId();
2519  id_to_cond.insert(
2520  std::make_pair(inner_table_id, join_info.equi_join_tautologies_[i].get()));
2521  }
2522  return id_to_cond;
2523 }
2524 
2525 namespace {
2526 
2527 bool has_lazy_fetched_columns(const std::vector<ColumnLazyFetchInfo>& fetched_cols) {
2528  for (const auto& col : fetched_cols) {
2529  if (col.is_lazily_fetched) {
2530  return true;
2531  }
2532  }
2533  return false;
2534 }
2535 
2536 } // namespace
2537 
2538 std::vector<std::unique_ptr<ExecutionKernel>> Executor::createKernels(
2539  SharedKernelContext& shared_context,
2540  const RelAlgExecutionUnit& ra_exe_unit,
2541  ColumnFetcher& column_fetcher,
2542  const std::vector<InputTableInfo>& table_infos,
2543  const ExecutionOptions& eo,
2544  const bool is_agg,
2545  const bool allow_single_frag_table_opt,
2546  const size_t context_count,
2547  const QueryCompilationDescriptor& query_comp_desc,
2549  RenderInfo* render_info,
2550  std::unordered_set<int>& available_gpus,
2551  int& available_cpus) {
2552  std::vector<std::unique_ptr<ExecutionKernel>> execution_kernels;
2553 
2554  QueryFragmentDescriptor fragment_descriptor(
2555  ra_exe_unit,
2556  table_infos,
2557  query_comp_desc.getDeviceType() == ExecutorDeviceType::GPU
2559  : std::vector<Data_Namespace::MemoryInfo>{},
2562  CHECK(!ra_exe_unit.input_descs.empty());
2563 
2564  const auto device_type = query_comp_desc.getDeviceType();
2565  const bool uses_lazy_fetch =
2566  plan_state_->allow_lazy_fetch_ &&
2568  const bool use_multifrag_kernel = (device_type == ExecutorDeviceType::GPU) &&
2569  eo.allow_multifrag && (!uses_lazy_fetch || is_agg);
2570  const auto device_count = deviceCount(device_type);
2571  CHECK_GT(device_count, 0);
2572 
2573  fragment_descriptor.buildFragmentKernelMap(ra_exe_unit,
2574  shared_context.getFragOffsets(),
2575  device_count,
2576  device_type,
2577  use_multifrag_kernel,
2579  this);
2580  if (eo.with_watchdog && fragment_descriptor.shouldCheckWorkUnitWatchdog()) {
2581  checkWorkUnitWatchdog(ra_exe_unit, table_infos, *catalog_, device_type, device_count);
2582  }
2583 
2584  if (use_multifrag_kernel) {
2585  VLOG(1) << "Creating multifrag execution kernels";
2586  VLOG(1) << query_mem_desc.toString();
2587 
2588  // NB: We should never be on this path when the query is retried because of running
2589  // out of group by slots; also, for scan only queries on CPU we want the
2590  // high-granularity, fragment by fragment execution instead. For scan only queries on
2591  // GPU, we want the multifrag kernel path to save the overhead of allocating an output
2592  // buffer per fragment.
2593  auto multifrag_kernel_dispatch = [&ra_exe_unit,
2594  &execution_kernels,
2595  &column_fetcher,
2596  &eo,
2597  &query_comp_desc,
2598  &query_mem_desc,
2599  render_info](const int device_id,
2600  const FragmentsList& frag_list,
2601  const int64_t rowid_lookup_key) {
2602  execution_kernels.emplace_back(
2603  std::make_unique<ExecutionKernel>(ra_exe_unit,
2605  device_id,
2606  eo,
2607  column_fetcher,
2608  query_comp_desc,
2609  query_mem_desc,
2610  frag_list,
2612  render_info,
2613  rowid_lookup_key));
2614  };
2615  fragment_descriptor.assignFragsToMultiDispatch(multifrag_kernel_dispatch);
2616  } else {
2617  VLOG(1) << "Creating one execution kernel per fragment";
2618  VLOG(1) << query_mem_desc.toString();
2619 
2620  if (!ra_exe_unit.use_bump_allocator && allow_single_frag_table_opt &&
2622  table_infos.size() == 1 && table_infos.front().table_id > 0) {
2623  const auto max_frag_size =
2624  table_infos.front().info.getFragmentNumTuplesUpperBound();
2625  if (max_frag_size < query_mem_desc.getEntryCount()) {
2626  LOG(INFO) << "Lowering scan limit from " << query_mem_desc.getEntryCount()
2627  << " to match max fragment size " << max_frag_size
2628  << " for kernel per fragment execution path.";
2629  throw CompilationRetryNewScanLimit(max_frag_size);
2630  }
2631  }
2632 
2633  size_t frag_list_idx{0};
2634  auto fragment_per_kernel_dispatch = [&ra_exe_unit,
2635  &execution_kernels,
2636  &column_fetcher,
2637  &eo,
2638  &frag_list_idx,
2639  &device_type,
2640  &query_comp_desc,
2641  &query_mem_desc,
2642  render_info](const int device_id,
2643  const FragmentsList& frag_list,
2644  const int64_t rowid_lookup_key) {
2645  if (!frag_list.size()) {
2646  return;
2647  }
2648  CHECK_GE(device_id, 0);
2649 
2650  execution_kernels.emplace_back(
2651  std::make_unique<ExecutionKernel>(ra_exe_unit,
2652  device_type,
2653  device_id,
2654  eo,
2655  column_fetcher,
2656  query_comp_desc,
2657  query_mem_desc,
2658  frag_list,
2660  render_info,
2661  rowid_lookup_key));
2662  ++frag_list_idx;
2663  };
2664 
2665  fragment_descriptor.assignFragsToKernelDispatch(fragment_per_kernel_dispatch,
2666  ra_exe_unit);
2667  }
2668 
2669  return execution_kernels;
2670 }
2671 
2673  std::vector<std::unique_ptr<ExecutionKernel>>&& kernels,
2674  const ExecutorDeviceType device_type) {
2675  auto clock_begin = timer_start();
2676  std::lock_guard<std::mutex> kernel_lock(kernel_mutex_);
2677  kernel_queue_time_ms_ += timer_stop(clock_begin);
2678 
2680  // A hack to have unused unit for results collection.
2681  const RelAlgExecutionUnit* ra_exe_unit =
2682  kernels.empty() ? nullptr : &kernels[0]->ra_exe_unit_;
2683 
2684 #ifdef HAVE_TBB
2685  if (g_enable_cpu_sub_tasks && device_type == ExecutorDeviceType::CPU) {
2686  shared_context.setThreadPool(&tg);
2687  }
2688  ScopeGuard pool_guard([&shared_context]() { shared_context.setThreadPool(nullptr); });
2689 #endif // HAVE_TBB
2690 
2691  VLOG(1) << "Launching " << kernels.size() << " kernels for query on "
2692  << (device_type == ExecutorDeviceType::CPU ? "CPU"s : "GPU"s) << ".";
2693  size_t kernel_idx = 1;
2694  for (auto& kernel : kernels) {
2695  CHECK(kernel.get());
2696  tg.run([this,
2697  &kernel,
2698  &shared_context,
2699  parent_thread_id = logger::thread_id(),
2700  crt_kernel_idx = kernel_idx++] {
2701  DEBUG_TIMER_NEW_THREAD(parent_thread_id);
2702  const size_t thread_i = crt_kernel_idx % cpu_threads();
2703  kernel->run(this, thread_i, shared_context);
2704  });
2705  }
2706  tg.wait();
2707 
2708  for (auto& exec_ctx : shared_context.getTlsExecutionContext()) {
2709  // The first arg is used for GPU only, it's not our case.
2710  // TODO: add QueryExecutionContext::getRowSet() interface
2711  // for our case.
2712  if (exec_ctx) {
2713  ResultSetPtr results;
2714  if (ra_exe_unit->estimator) {
2715  results = std::shared_ptr<ResultSet>(exec_ctx->estimator_result_set_.release());
2716  } else {
2717  results = exec_ctx->getRowSet(*ra_exe_unit, exec_ctx->query_mem_desc_);
2718  }
2719  shared_context.addDeviceResults(std::move(results), {});
2720  }
2721  }
2722 }
2723 
2725  const RelAlgExecutionUnit& ra_exe_unit,
2726  const ExecutorDeviceType device_type,
2727  const size_t table_idx,
2728  const size_t outer_frag_idx,
2729  std::map<int, const TableFragments*>& selected_tables_fragments,
2730  const std::unordered_map<int, const Analyzer::BinOper*>&
2731  inner_table_id_to_join_condition) {
2732  const int table_id = ra_exe_unit.input_descs[table_idx].getTableId();
2733  auto table_frags_it = selected_tables_fragments.find(table_id);
2734  CHECK(table_frags_it != selected_tables_fragments.end());
2735  const auto& outer_input_desc = ra_exe_unit.input_descs[0];
2736  const auto outer_table_fragments_it =
2737  selected_tables_fragments.find(outer_input_desc.getTableId());
2738  const auto outer_table_fragments = outer_table_fragments_it->second;
2739  CHECK(outer_table_fragments_it != selected_tables_fragments.end());
2740  CHECK_LT(outer_frag_idx, outer_table_fragments->size());
2741  if (!table_idx) {
2742  return {outer_frag_idx};
2743  }
2744  const auto& outer_fragment_info = (*outer_table_fragments)[outer_frag_idx];
2745  auto& inner_frags = table_frags_it->second;
2746  CHECK_LT(size_t(1), ra_exe_unit.input_descs.size());
2747  std::vector<size_t> all_frag_ids;
2748  for (size_t inner_frag_idx = 0; inner_frag_idx < inner_frags->size();
2749  ++inner_frag_idx) {
2750  const auto& inner_frag_info = (*inner_frags)[inner_frag_idx];
2751  if (skipFragmentPair(outer_fragment_info,
2752  inner_frag_info,
2753  table_idx,
2754  inner_table_id_to_join_condition,
2755  ra_exe_unit,
2756  device_type)) {
2757  continue;
2758  }
2759  all_frag_ids.push_back(inner_frag_idx);
2760  }
2761  return all_frag_ids;
2762 }
2763 
2764 // Returns true iff the join between two fragments cannot yield any results, per
2765 // shard information. The pair can be skipped to avoid full broadcast.
2767  const Fragmenter_Namespace::FragmentInfo& outer_fragment_info,
2768  const Fragmenter_Namespace::FragmentInfo& inner_fragment_info,
2769  const int table_idx,
2770  const std::unordered_map<int, const Analyzer::BinOper*>&
2771  inner_table_id_to_join_condition,
2772  const RelAlgExecutionUnit& ra_exe_unit,
2773  const ExecutorDeviceType device_type) {
2774  if (device_type != ExecutorDeviceType::GPU) {
2775  return false;
2776  }
2777  CHECK(table_idx >= 0 &&
2778  static_cast<size_t>(table_idx) < ra_exe_unit.input_descs.size());
2779  const int inner_table_id = ra_exe_unit.input_descs[table_idx].getTableId();
2780  // Both tables need to be sharded the same way.
2781  if (outer_fragment_info.shard == -1 || inner_fragment_info.shard == -1 ||
2782  outer_fragment_info.shard == inner_fragment_info.shard) {
2783  return false;
2784  }
2785  const Analyzer::BinOper* join_condition{nullptr};
2786  if (ra_exe_unit.join_quals.empty()) {
2787  CHECK(!inner_table_id_to_join_condition.empty());
2788  auto condition_it = inner_table_id_to_join_condition.find(inner_table_id);
2789  CHECK(condition_it != inner_table_id_to_join_condition.end());
2790  join_condition = condition_it->second;
2791  CHECK(join_condition);
2792  } else {
2793  CHECK_EQ(plan_state_->join_info_.equi_join_tautologies_.size(),
2794  plan_state_->join_info_.join_hash_tables_.size());
2795  for (size_t i = 0; i < plan_state_->join_info_.join_hash_tables_.size(); ++i) {
2796  if (plan_state_->join_info_.join_hash_tables_[i]->getInnerTableRteIdx() ==
2797  table_idx) {
2798  CHECK(!join_condition);
2799  join_condition = plan_state_->join_info_.equi_join_tautologies_[i].get();
2800  }
2801  }
2802  }
2803  if (!join_condition) {
2804  return false;
2805  }
2806  // TODO(adb): support fragment skipping based on the overlaps operator
2807  if (join_condition->is_overlaps_oper()) {
2808  return false;
2809  }
2810  size_t shard_count{0};
2811  if (dynamic_cast<const Analyzer::ExpressionTuple*>(
2812  join_condition->get_left_operand())) {
2813  auto inner_outer_pairs = HashJoin::normalizeColumnPairs(
2814  join_condition, *getCatalog(), getTemporaryTables())
2815  .first;
2817  join_condition, this, inner_outer_pairs);
2818  } else {
2819  shard_count = get_shard_count(join_condition, this);
2820  }
2821  if (shard_count && !ra_exe_unit.join_quals.empty()) {
2822  plan_state_->join_info_.sharded_range_table_indices_.emplace(table_idx);
2823  }
2824  return shard_count;
2825 }
2826 
2827 namespace {
2828 
2831  const int table_id = col_desc->getScanDesc().getTableId();
2832  const int col_id = col_desc->getColId();
2833  return get_column_descriptor_maybe(col_id, table_id, cat);
2834 }
2835 
2836 } // namespace
2837 
2838 std::map<size_t, std::vector<uint64_t>> get_table_id_to_frag_offsets(
2839  const std::vector<InputDescriptor>& input_descs,
2840  const std::map<int, const TableFragments*>& all_tables_fragments) {
2841  std::map<size_t, std::vector<uint64_t>> tab_id_to_frag_offsets;
2842  for (auto& desc : input_descs) {
2843  const auto fragments_it = all_tables_fragments.find(desc.getTableId());
2844  CHECK(fragments_it != all_tables_fragments.end());
2845  const auto& fragments = *fragments_it->second;
2846  std::vector<uint64_t> frag_offsets(fragments.size(), 0);
2847  for (size_t i = 0, off = 0; i < fragments.size(); ++i) {
2848  frag_offsets[i] = off;
2849  off += fragments[i].getNumTuples();
2850  }
2851  tab_id_to_frag_offsets.insert(std::make_pair(desc.getTableId(), frag_offsets));
2852  }
2853  return tab_id_to_frag_offsets;
2854 }
2855 
2856 std::pair<std::vector<std::vector<int64_t>>, std::vector<std::vector<uint64_t>>>
2858  const RelAlgExecutionUnit& ra_exe_unit,
2859  const CartesianProduct<std::vector<std::vector<size_t>>>& frag_ids_crossjoin,
2860  const std::vector<InputDescriptor>& input_descs,
2861  const std::map<int, const TableFragments*>& all_tables_fragments) {
2862  std::vector<std::vector<int64_t>> all_num_rows;
2863  std::vector<std::vector<uint64_t>> all_frag_offsets;
2864  const auto tab_id_to_frag_offsets =
2865  get_table_id_to_frag_offsets(input_descs, all_tables_fragments);
2866  std::unordered_map<size_t, size_t> outer_id_to_num_row_idx;
2867  for (const auto& selected_frag_ids : frag_ids_crossjoin) {
2868  std::vector<int64_t> num_rows;
2869  std::vector<uint64_t> frag_offsets;
2870  if (!ra_exe_unit.union_all) {
2871  CHECK_EQ(selected_frag_ids.size(), input_descs.size());
2872  }
2873  for (size_t tab_idx = 0; tab_idx < input_descs.size(); ++tab_idx) {
2874  const auto frag_id = ra_exe_unit.union_all ? 0 : selected_frag_ids[tab_idx];
2875  const auto fragments_it =
2876  all_tables_fragments.find(input_descs[tab_idx].getTableId());
2877  CHECK(fragments_it != all_tables_fragments.end());
2878  const auto& fragments = *fragments_it->second;
2879  if (ra_exe_unit.join_quals.empty() || tab_idx == 0 ||
2880  plan_state_->join_info_.sharded_range_table_indices_.count(tab_idx)) {
2881  const auto& fragment = fragments[frag_id];
2882  num_rows.push_back(fragment.getNumTuples());
2883  } else {
2884  size_t total_row_count{0};
2885  for (const auto& fragment : fragments) {
2886  total_row_count += fragment.getNumTuples();
2887  }
2888  num_rows.push_back(total_row_count);
2889  }
2890  const auto frag_offsets_it =
2891  tab_id_to_frag_offsets.find(input_descs[tab_idx].getTableId());
2892  CHECK(frag_offsets_it != tab_id_to_frag_offsets.end());
2893  const auto& offsets = frag_offsets_it->second;
2894  CHECK_LT(frag_id, offsets.size());
2895  frag_offsets.push_back(offsets[frag_id]);
2896  }
2897  all_num_rows.push_back(num_rows);
2898  // Fragment offsets of outer table should be ONLY used by rowid for now.
2899  all_frag_offsets.push_back(frag_offsets);
2900  }
2901  return {all_num_rows, all_frag_offsets};
2902 }
2903 
2904 // Only fetch columns of hash-joined inner fact table whose fetch are not deferred from
2905 // all the table fragments.
2907  const RelAlgExecutionUnit& ra_exe_unit,
2908  const FragmentsList& selected_fragments) const {
2909  const auto& input_descs = ra_exe_unit.input_descs;
2910  const int nest_level = inner_col_desc.getScanDesc().getNestLevel();
2911  if (nest_level < 1 ||
2912  inner_col_desc.getScanDesc().getSourceType() != InputSourceType::TABLE ||
2913  ra_exe_unit.join_quals.empty() || input_descs.size() < 2 ||
2914  (ra_exe_unit.join_quals.empty() &&
2915  plan_state_->isLazyFetchColumn(inner_col_desc))) {
2916  return false;
2917  }
2918  const int table_id = inner_col_desc.getScanDesc().getTableId();
2919  CHECK_LT(static_cast<size_t>(nest_level), selected_fragments.size());
2920  CHECK_EQ(table_id, selected_fragments[nest_level].table_id);
2921  const auto& fragments = selected_fragments[nest_level].fragment_ids;
2922  return fragments.size() > 1;
2923 }
2924 
2926  const ColumnDescriptor* cd,
2927  const InputColDescriptor& inner_col_desc,
2928  const RelAlgExecutionUnit& ra_exe_unit,
2929  const FragmentsList& selected_fragments,
2930  const Data_Namespace::MemoryLevel memory_level) const {
2931  const int nest_level = inner_col_desc.getScanDesc().getNestLevel();
2932  const int table_id = inner_col_desc.getScanDesc().getTableId();
2933  CHECK_LT(static_cast<size_t>(nest_level), selected_fragments.size());
2934  CHECK_EQ(table_id, selected_fragments[nest_level].table_id);
2935  const auto& fragments = selected_fragments[nest_level].fragment_ids;
2936  auto need_linearize =
2937  cd->columnType.is_array() ||
2939  return table_id > 0 && need_linearize && fragments.size() > 1;
2940 }
2941 
2942 std::ostream& operator<<(std::ostream& os, FetchResult const& fetch_result) {
2943  return os << "col_buffers" << shared::printContainer(fetch_result.col_buffers)
2944  << " num_rows" << shared::printContainer(fetch_result.num_rows)
2945  << " frag_offsets" << shared::printContainer(fetch_result.frag_offsets);
2946 }
2947 
2949  const ColumnFetcher& column_fetcher,
2950  const RelAlgExecutionUnit& ra_exe_unit,
2951  const int device_id,
2952  const Data_Namespace::MemoryLevel memory_level,
2953  const std::map<int, const TableFragments*>& all_tables_fragments,
2954  const FragmentsList& selected_fragments,
2956  std::list<ChunkIter>& chunk_iterators,
2957  std::list<std::shared_ptr<Chunk_NS::Chunk>>& chunks,
2958  DeviceAllocator* device_allocator,
2959  const size_t thread_idx,
2960  const bool allow_runtime_interrupt) {
2961  auto timer = DEBUG_TIMER(__func__);
2963  const auto& col_global_ids = ra_exe_unit.input_col_descs;
2964  std::vector<std::vector<size_t>> selected_fragments_crossjoin;
2965  std::vector<size_t> local_col_to_frag_pos;
2966  buildSelectedFragsMapping(selected_fragments_crossjoin,
2967  local_col_to_frag_pos,
2968  col_global_ids,
2969  selected_fragments,
2970  ra_exe_unit);
2971 
2973  selected_fragments_crossjoin);
2974  std::vector<std::vector<const int8_t*>> all_frag_col_buffers;
2975  std::vector<std::vector<int64_t>> all_num_rows;
2976  std::vector<std::vector<uint64_t>> all_frag_offsets;
2977  for (const auto& selected_frag_ids : frag_ids_crossjoin) {
2978  std::vector<const int8_t*> frag_col_buffers(
2979  plan_state_->global_to_local_col_ids_.size());
2980  for (const auto& col_id : col_global_ids) {
2981  if (allow_runtime_interrupt) {
2982  bool isInterrupted = false;
2983  {
2986  const auto query_session = getCurrentQuerySession(session_read_lock);
2987  isInterrupted =
2988  checkIsQuerySessionInterrupted(query_session, session_read_lock);
2989  }
2990  if (isInterrupted) {
2992  }
2993  }
2994  if (g_enable_dynamic_watchdog && interrupted_.load()) {
2996  }
2997  CHECK(col_id);
2998  const int table_id = col_id->getScanDesc().getTableId();
2999  const auto cd = try_get_column_descriptor(col_id.get(), cat);
3000  if (cd && cd->isVirtualCol) {
3001  CHECK_EQ("rowid", cd->columnName);
3002  continue;
3003  }
3004  const auto fragments_it = all_tables_fragments.find(table_id);
3005  CHECK(fragments_it != all_tables_fragments.end());
3006  const auto fragments = fragments_it->second;
3007  auto it = plan_state_->global_to_local_col_ids_.find(*col_id);
3008  CHECK(it != plan_state_->global_to_local_col_ids_.end());
3009  CHECK_LT(static_cast<size_t>(it->second),
3010  plan_state_->global_to_local_col_ids_.size());
3011  const size_t frag_id = selected_frag_ids[local_col_to_frag_pos[it->second]];
3012  if (!fragments->size()) {
3013  return {};
3014  }
3015  CHECK_LT(frag_id, fragments->size());
3016  auto memory_level_for_column = memory_level;
3017  auto tbl_col_ids =
3018  std::make_pair(col_id->getScanDesc().getTableId(), col_id->getColId());
3019  if (plan_state_->columns_to_fetch_.find(tbl_col_ids) ==
3020  plan_state_->columns_to_fetch_.end()) {
3021  memory_level_for_column = Data_Namespace::CPU_LEVEL;
3022  }
3023  if (col_id->getScanDesc().getSourceType() == InputSourceType::RESULT) {
3024  frag_col_buffers[it->second] =
3025  column_fetcher.getResultSetColumn(col_id.get(),
3026  memory_level_for_column,
3027  device_id,
3028  device_allocator,
3029  thread_idx);
3030  } else {
3031  if (needFetchAllFragments(*col_id, ra_exe_unit, selected_fragments)) {
3032  // determine if we need special treatment to linearlize multi-frag table
3033  // i.e., a column that is classified as varlen type, i.e., array
3034  // for now, we only support fixed-length array that contains
3035  // geo point coordianates but we can support more types in this way
3037  cd, *col_id, ra_exe_unit, selected_fragments, memory_level)) {
3038  bool for_lazy_fetch = false;
3039  if (plan_state_->columns_to_not_fetch_.find(tbl_col_ids) !=
3040  plan_state_->columns_to_not_fetch_.end()) {
3041  for_lazy_fetch = true;
3042  VLOG(2) << "Try to linearize lazy fetch column (col_id: " << cd->columnId
3043  << ", col_name: " << cd->columnName << ")";
3044  }
3045  frag_col_buffers[it->second] = column_fetcher.linearizeColumnFragments(
3046  table_id,
3047  col_id->getColId(),
3048  all_tables_fragments,
3049  chunks,
3050  chunk_iterators,
3051  for_lazy_fetch ? Data_Namespace::CPU_LEVEL : memory_level,
3052  for_lazy_fetch ? 0 : device_id,
3053  device_allocator,
3054  thread_idx);
3055  } else {
3056  frag_col_buffers[it->second] =
3057  column_fetcher.getAllTableColumnFragments(table_id,
3058  col_id->getColId(),
3059  all_tables_fragments,
3060  memory_level_for_column,
3061  device_id,
3062  device_allocator,
3063  thread_idx);
3064  }
3065  } else {
3066  frag_col_buffers[it->second] =
3067  column_fetcher.getOneTableColumnFragment(table_id,
3068  frag_id,
3069  col_id->getColId(),
3070  all_tables_fragments,
3071  chunks,
3072  chunk_iterators,
3073  memory_level_for_column,
3074  device_id,
3075  device_allocator);
3076  }
3077  }
3078  }
3079  all_frag_col_buffers.push_back(frag_col_buffers);
3080  }
3081  std::tie(all_num_rows, all_frag_offsets) = getRowCountAndOffsetForAllFrags(
3082  ra_exe_unit, frag_ids_crossjoin, ra_exe_unit.input_descs, all_tables_fragments);
3083  return {all_frag_col_buffers, all_num_rows, all_frag_offsets};
3084 }
3085 
3086 namespace {
3087 size_t get_selected_input_descs_index(int const table_id,
3088  std::vector<InputDescriptor> const& input_descs) {
3089  auto const has_table_id = [table_id](InputDescriptor const& input_desc) {
3090  return table_id == input_desc.getTableId();
3091  };
3092  return std::find_if(input_descs.begin(), input_descs.end(), has_table_id) -
3093  input_descs.begin();
3094 }
3095 
3097  int const table_id,
3098  std::list<std::shared_ptr<InputColDescriptor const>> const& input_col_descs) {
3099  auto const has_table_id = [table_id](auto const& input_desc) {
3100  return table_id == input_desc->getScanDesc().getTableId();
3101  };
3102  return std::distance(
3103  input_col_descs.begin(),
3104  std::find_if(input_col_descs.begin(), input_col_descs.end(), has_table_id));
3105 }
3106 
3107 std::list<std::shared_ptr<const InputColDescriptor>> get_selected_input_col_descs(
3108  int const table_id,
3109  std::list<std::shared_ptr<InputColDescriptor const>> const& input_col_descs) {
3110  std::list<std::shared_ptr<const InputColDescriptor>> selected;
3111  for (auto const& input_col_desc : input_col_descs) {
3112  if (table_id == input_col_desc->getScanDesc().getTableId()) {
3113  selected.push_back(input_col_desc);
3114  }
3115  }
3116  return selected;
3117 }
3118 
3119 // Set N consecutive elements of frag_col_buffers to ptr in the range of local_col_id.
3120 void set_mod_range(std::vector<int8_t const*>& frag_col_buffers,
3121  int8_t const* const ptr,
3122  size_t const local_col_id,
3123  size_t const N) {
3124  size_t const begin = local_col_id - local_col_id % N; // N divides begin
3125  size_t const end = begin + N;
3126  CHECK_LE(end, frag_col_buffers.size()) << (void*)ptr << ' ' << local_col_id << ' ' << N;
3127  for (size_t i = begin; i < end; ++i) {
3128  frag_col_buffers[i] = ptr;
3129  }
3130 }
3131 } // namespace
3132 
3133 // fetchChunks() assumes that multiple inputs implies a JOIN.
3134 // fetchUnionChunks() assumes that multiple inputs implies a UNION ALL.
3136  const ColumnFetcher& column_fetcher,
3137  const RelAlgExecutionUnit& ra_exe_unit,
3138  const int device_id,
3139  const Data_Namespace::MemoryLevel memory_level,
3140  const std::map<int, const TableFragments*>& all_tables_fragments,
3141  const FragmentsList& selected_fragments,
3143  std::list<ChunkIter>& chunk_iterators,
3144  std::list<std::shared_ptr<Chunk_NS::Chunk>>& chunks,
3145  DeviceAllocator* device_allocator,
3146  const size_t thread_idx,
3147  const bool allow_runtime_interrupt) {
3148  auto timer = DEBUG_TIMER(__func__);
3150 
3151  CHECK_EQ(1u, selected_fragments.size());
3152  CHECK_LE(2u, ra_exe_unit.input_descs.size());
3153  CHECK_LE(2u, ra_exe_unit.input_col_descs.size());
3154  auto const& input_descs = ra_exe_unit.input_descs;
3155  using TableId = int;
3156  TableId const selected_table_id = selected_fragments.front().table_id;
3157  size_t const input_descs_index =
3158  get_selected_input_descs_index(selected_table_id, input_descs);
3159  CHECK_LT(input_descs_index, input_descs.size());
3160  size_t const input_col_descs_index =
3161  get_selected_input_col_descs_index(selected_table_id, ra_exe_unit.input_col_descs);
3162  CHECK_LT(input_col_descs_index, ra_exe_unit.input_col_descs.size());
3163  VLOG(2) << "selected_table_id=" << selected_table_id
3164  << " input_descs_index=" << input_descs_index
3165  << " input_col_descs_index=" << input_col_descs_index
3166  << " input_descs=" << shared::printContainer(input_descs)
3167  << " ra_exe_unit.input_col_descs="
3168  << shared::printContainer(ra_exe_unit.input_col_descs);
3169 
3170  std::list<std::shared_ptr<const InputColDescriptor>> selected_input_col_descs =
3171  get_selected_input_col_descs(selected_table_id, ra_exe_unit.input_col_descs);
3172  std::vector<std::vector<size_t>> selected_fragments_crossjoin;
3173 
3175  selected_fragments_crossjoin, selected_fragments, ra_exe_unit);
3176 
3178  selected_fragments_crossjoin);
3179 
3180  if (allow_runtime_interrupt) {
3181  bool isInterrupted = false;
3182  {
3185  const auto query_session = getCurrentQuerySession(session_read_lock);
3186  isInterrupted = checkIsQuerySessionInterrupted(query_session, session_read_lock);
3187  }
3188  if (isInterrupted) {
3190  }
3191  }
3192  std::vector<const int8_t*> frag_col_buffers(
3193  plan_state_->global_to_local_col_ids_.size());
3194  for (const auto& col_id : selected_input_col_descs) {
3195  CHECK(col_id);
3196  const auto cd = try_get_column_descriptor(col_id.get(), cat);
3197  if (cd && cd->isVirtualCol) {
3198  CHECK_EQ("rowid", cd->columnName);
3199  continue;
3200  }
3201  const auto fragments_it = all_tables_fragments.find(selected_table_id);
3202  CHECK(fragments_it != all_tables_fragments.end());
3203  const auto fragments = fragments_it->second;
3204  auto it = plan_state_->global_to_local_col_ids_.find(*col_id);
3205  CHECK(it != plan_state_->global_to_local_col_ids_.end());
3206  size_t const local_col_id = it->second;
3207  CHECK_LT(local_col_id, plan_state_->global_to_local_col_ids_.size());
3208  constexpr size_t frag_id = 0;
3209  if (fragments->empty()) {
3210  return {};
3211  }
3212  MemoryLevel const memory_level_for_column =
3213  plan_state_->columns_to_fetch_.count({selected_table_id, col_id->getColId()})
3214  ? memory_level
3216  int8_t const* ptr;
3217  if (col_id->getScanDesc().getSourceType() == InputSourceType::RESULT) {
3218  ptr = column_fetcher.getResultSetColumn(
3219  col_id.get(), memory_level_for_column, device_id, device_allocator, thread_idx);
3220  } else if (needFetchAllFragments(*col_id, ra_exe_unit, selected_fragments)) {
3221  ptr = column_fetcher.getAllTableColumnFragments(selected_table_id,
3222  col_id->getColId(),
3223  all_tables_fragments,
3224  memory_level_for_column,
3225  device_id,
3226  device_allocator,
3227  thread_idx);
3228  } else {
3229  ptr = column_fetcher.getOneTableColumnFragment(selected_table_id,
3230  frag_id,
3231  col_id->getColId(),
3232  all_tables_fragments,
3233  chunks,
3234  chunk_iterators,
3235  memory_level_for_column,
3236  device_id,
3237  device_allocator);
3238  }
3239  // Set frag_col_buffers[i]=ptr for i in mod input_descs.size() range of local_col_id.
3240  set_mod_range(frag_col_buffers, ptr, local_col_id, input_descs.size());
3241  }
3242  auto const [num_rows, frag_offsets] = getRowCountAndOffsetForAllFrags(
3243  ra_exe_unit, frag_ids_crossjoin, input_descs, all_tables_fragments);
3244 
3245  VLOG(2) << "frag_col_buffers=" << shared::printContainer(frag_col_buffers)
3246  << " num_rows=" << shared::printContainer(num_rows)
3247  << " frag_offsets=" << shared::printContainer(frag_offsets)
3248  << " input_descs_index=" << input_descs_index
3249  << " input_col_descs_index=" << input_col_descs_index;
3250  return {{std::move(frag_col_buffers)},
3251  {{num_rows[0][input_descs_index]}},
3252  {{frag_offsets[0][input_descs_index]}}};
3253 }
3254 
3255 std::vector<size_t> Executor::getFragmentCount(const FragmentsList& selected_fragments,
3256  const size_t scan_idx,
3257  const RelAlgExecutionUnit& ra_exe_unit) {
3258  if ((ra_exe_unit.input_descs.size() > size_t(2) || !ra_exe_unit.join_quals.empty()) &&
3259  scan_idx > 0 &&
3260  !plan_state_->join_info_.sharded_range_table_indices_.count(scan_idx) &&
3261  !selected_fragments[scan_idx].fragment_ids.empty()) {
3262  // Fetch all fragments
3263  return {size_t(0)};
3264  }
3265 
3266  return selected_fragments[scan_idx].fragment_ids;
3267 }
3268 
3270  std::vector<std::vector<size_t>>& selected_fragments_crossjoin,
3271  std::vector<size_t>& local_col_to_frag_pos,
3272  const std::list<std::shared_ptr<const InputColDescriptor>>& col_global_ids,
3273  const FragmentsList& selected_fragments,
3274  const RelAlgExecutionUnit& ra_exe_unit) {
3275  local_col_to_frag_pos.resize(plan_state_->global_to_local_col_ids_.size());
3276  size_t frag_pos{0};
3277  const auto& input_descs = ra_exe_unit.input_descs;
3278  for (size_t scan_idx = 0; scan_idx < input_descs.size(); ++scan_idx) {
3279  const int table_id = input_descs[scan_idx].getTableId();
3280  CHECK_EQ(selected_fragments[scan_idx].table_id, table_id);
3281  selected_fragments_crossjoin.push_back(
3282  getFragmentCount(selected_fragments, scan_idx, ra_exe_unit));
3283  for (const auto& col_id : col_global_ids) {
3284  CHECK(col_id);
3285  const auto& input_desc = col_id->getScanDesc();
3286  if (input_desc.getTableId() != table_id ||
3287  input_desc.getNestLevel() != static_cast<int>(scan_idx)) {
3288  continue;
3289  }
3290  auto it = plan_state_->global_to_local_col_ids_.find(*col_id);
3291  CHECK(it != plan_state_->global_to_local_col_ids_.end());
3292  CHECK_LT(static_cast<size_t>(it->second),
3293  plan_state_->global_to_local_col_ids_.size());
3294  local_col_to_frag_pos[it->second] = frag_pos;
3295  }
3296  ++frag_pos;
3297  }
3298 }
3299 
3301  std::vector<std::vector<size_t>>& selected_fragments_crossjoin,
3302  const FragmentsList& selected_fragments,
3303  const RelAlgExecutionUnit& ra_exe_unit) {
3304  const auto& input_descs = ra_exe_unit.input_descs;
3305  for (size_t scan_idx = 0; scan_idx < input_descs.size(); ++scan_idx) {
3306  // selected_fragments is set in assignFragsToKernelDispatch execution_kernel.fragments
3307  if (selected_fragments[0].table_id == input_descs[scan_idx].getTableId()) {
3308  selected_fragments_crossjoin.push_back({size_t(1)});
3309  }
3310  }
3311 }
3312 
3313 namespace {
3314 
3316  public:
3317  OutVecOwner(const std::vector<int64_t*>& out_vec) : out_vec_(out_vec) {}
3319  for (auto out : out_vec_) {
3320  delete[] out;
3321  }
3322  }
3323 
3324  private:
3325  std::vector<int64_t*> out_vec_;
3326 };
3327 } // namespace
3328 
3330  const RelAlgExecutionUnit& ra_exe_unit,
3331  const CompilationResult& compilation_result,
3332  const bool hoist_literals,
3333  ResultSetPtr* results,
3334  const std::vector<Analyzer::Expr*>& target_exprs,
3335  const ExecutorDeviceType device_type,
3336  std::vector<std::vector<const int8_t*>>& col_buffers,
3337  QueryExecutionContext* query_exe_context,
3338  const std::vector<std::vector<int64_t>>& num_rows,
3339  const std::vector<std::vector<uint64_t>>& frag_offsets,
3340  Data_Namespace::DataMgr* data_mgr,
3341  const int device_id,
3342  const uint32_t start_rowid,
3343  const uint32_t num_tables,
3344  const bool allow_runtime_interrupt,
3345  RenderInfo* render_info,
3346  const int64_t rows_to_process) {
3348  auto timer = DEBUG_TIMER(__func__);
3349  CHECK(!results || !(*results));
3350  if (col_buffers.empty()) {
3351  return 0;
3352  }
3353 
3354  RenderAllocatorMap* render_allocator_map_ptr = nullptr;
3355  if (render_info) {
3356  // TODO(adb): make sure that we either never get here in the CPU case, or if we do get
3357  // here, we are in non-insitu mode.
3358  CHECK(render_info->useCudaBuffers() || !render_info->isInSitu())
3359  << "CUDA disabled rendering in the executePlanWithoutGroupBy query path is "
3360  "currently unsupported.";
3361  render_allocator_map_ptr = render_info->render_allocator_map_ptr.get();
3362  }
3363 
3364  int32_t error_code = device_type == ExecutorDeviceType::GPU ? 0 : start_rowid;
3365  std::vector<int64_t*> out_vec;
3366  const auto hoist_buf = serializeLiterals(compilation_result.literal_values, device_id);
3367  const auto join_hash_table_ptrs = getJoinHashTablePtrs(device_type, device_id);
3368  std::unique_ptr<OutVecOwner> output_memory_scope;
3369  if (allow_runtime_interrupt) {
3370  bool isInterrupted = false;
3371  {
3374  const auto query_session = getCurrentQuerySession(session_read_lock);
3375  isInterrupted = checkIsQuerySessionInterrupted(query_session, session_read_lock);
3376  }
3377  if (isInterrupted) {
3379  }
3380  }
3381  if (g_enable_dynamic_watchdog && interrupted_.load()) {
3383  }
3384  if (device_type == ExecutorDeviceType::CPU) {
3385  CpuCompilationContext* cpu_generated_code =
3386  dynamic_cast<CpuCompilationContext*>(compilation_result.generated_code.get());
3387  CHECK(cpu_generated_code);
3388  out_vec = query_exe_context->launchCpuCode(ra_exe_unit,
3389  cpu_generated_code,
3390  hoist_literals,
3391  hoist_buf,
3392  col_buffers,
3393  num_rows,
3394  frag_offsets,
3395  0,
3396  &error_code,
3397  num_tables,
3398  join_hash_table_ptrs,
3399  rows_to_process);
3400  output_memory_scope.reset(new OutVecOwner(out_vec));
3401  } else {
3402  GpuCompilationContext* gpu_generated_code =
3403  dynamic_cast<GpuCompilationContext*>(compilation_result.generated_code.get());
3404  CHECK(gpu_generated_code);
3405  try {
3406  out_vec = query_exe_context->launchGpuCode(
3407  ra_exe_unit,
3408  gpu_generated_code,
3409  hoist_literals,
3410  hoist_buf,
3411  col_buffers,
3412  num_rows,
3413  frag_offsets,
3414  0,
3415  data_mgr,
3416  blockSize(),
3417  gridSize(),
3418  device_id,
3419  compilation_result.gpu_smem_context.getSharedMemorySize(),
3420  &error_code,
3421  num_tables,
3422  allow_runtime_interrupt,
3423  join_hash_table_ptrs,
3424  render_allocator_map_ptr);
3425  output_memory_scope.reset(new OutVecOwner(out_vec));
3426  } catch (const OutOfMemory&) {
3427  return ERR_OUT_OF_GPU_MEM;
3428  } catch (const std::exception& e) {
3429  LOG(FATAL) << "Error launching the GPU kernel: " << e.what();
3430  }
3431  }
3432  if (error_code == Executor::ERR_OVERFLOW_OR_UNDERFLOW ||
3433  error_code == Executor::ERR_DIV_BY_ZERO ||
3434  error_code == Executor::ERR_OUT_OF_TIME ||
3435  error_code == Executor::ERR_INTERRUPTED ||
3437  error_code == Executor::ERR_GEOS ||
3439  return error_code;
3440  }
3441  if (ra_exe_unit.estimator) {
3442  CHECK(!error_code);
3443  if (results) {
3444  *results =
3445  std::shared_ptr<ResultSet>(query_exe_context->estimator_result_set_.release());
3446  }
3447  return 0;
3448  }
3449  // Expect delayed results extraction (used for sub-fragments) for estimator only;
3450  CHECK(results);
3451  std::vector<int64_t> reduced_outs;
3452  const auto num_frags = col_buffers.size();
3453  const size_t entry_count =
3454  device_type == ExecutorDeviceType::GPU
3455  ? (compilation_result.gpu_smem_context.isSharedMemoryUsed()
3456  ? 1
3457  : blockSize() * gridSize() * num_frags)
3458  : num_frags;
3459  if (size_t(1) == entry_count) {
3460  for (auto out : out_vec) {
3461  CHECK(out);
3462  reduced_outs.push_back(*out);
3463  }
3464  } else {
3465  size_t out_vec_idx = 0;
3466 
3467  for (const auto target_expr : target_exprs) {
3468  const auto agg_info = get_target_info(target_expr, g_bigint_count);
3469  CHECK(agg_info.is_agg || dynamic_cast<Analyzer::Constant*>(target_expr))
3470  << target_expr->toString();
3471 
3472  const int num_iterations = agg_info.sql_type.is_geometry()
3473  ? agg_info.sql_type.get_physical_coord_cols()
3474  : 1;
3475 
3476  for (int i = 0; i < num_iterations; i++) {
3477  int64_t val1;
3478  const bool float_argument_input = takes_float_argument(agg_info);
3479  if (is_distinct_target(agg_info) || agg_info.agg_kind == kAPPROX_QUANTILE) {
3480  CHECK(agg_info.agg_kind == kCOUNT ||
3481  agg_info.agg_kind == kAPPROX_COUNT_DISTINCT ||
3482  agg_info.agg_kind == kAPPROX_QUANTILE);
3483  val1 = out_vec[out_vec_idx][0];
3484  error_code = 0;
3485  } else {
3486  const auto chosen_bytes = static_cast<size_t>(
3487  query_exe_context->query_mem_desc_.getPaddedSlotWidthBytes(out_vec_idx));
3488  std::tie(val1, error_code) = Executor::reduceResults(
3489  agg_info.agg_kind,
3490  agg_info.sql_type,
3491  query_exe_context->getAggInitValForIndex(out_vec_idx),
3492  float_argument_input ? sizeof(int32_t) : chosen_bytes,
3493  out_vec[out_vec_idx],
3494  entry_count,
3495  false,
3496  float_argument_input);
3497  }
3498  if (error_code) {
3499  break;
3500  }
3501  reduced_outs.push_back(val1);
3502  if (agg_info.agg_kind == kAVG ||
3503  (agg_info.agg_kind == kSAMPLE &&
3504  (agg_info.sql_type.is_varlen() || agg_info.sql_type.is_geometry()))) {
3505  const auto chosen_bytes = static_cast<size_t>(
3506  query_exe_context->query_mem_desc_.getPaddedSlotWidthBytes(out_vec_idx +
3507  1));
3508  int64_t val2;
3509  std::tie(val2, error_code) = Executor::reduceResults(
3510  agg_info.agg_kind == kAVG ? kCOUNT : agg_info.agg_kind,
3511  agg_info.sql_type,
3512  query_exe_context->getAggInitValForIndex(out_vec_idx + 1),
3513  float_argument_input ? sizeof(int32_t) : chosen_bytes,
3514  out_vec[out_vec_idx + 1],
3515  entry_count,
3516  false,
3517  false);
3518  if (error_code) {
3519  break;
3520  }
3521  reduced_outs.push_back(val2);
3522  ++out_vec_idx;
3523  }
3524  ++out_vec_idx;
3525  }
3526  }
3527  }
3528 
3529  if (error_code) {
3530  return error_code;
3531  }
3532 
3533  CHECK_EQ(size_t(1), query_exe_context->query_buffers_->result_sets_.size());
3534  auto rows_ptr = std::shared_ptr<ResultSet>(
3535  query_exe_context->query_buffers_->result_sets_[0].release());
3536  rows_ptr->fillOneEntry(reduced_outs);
3537  *results = std::move(rows_ptr);
3538  return error_code;
3539 }
3540 
3541 namespace {
3542 
3543 bool check_rows_less_than_needed(const ResultSetPtr& results, const size_t scan_limit) {
3544  CHECK(scan_limit);
3545  return results && results->rowCount() < scan_limit;
3546 }
3547 
3548 } // namespace
3549 
3551  const RelAlgExecutionUnit& ra_exe_unit,
3552  const CompilationResult& compilation_result,
3553  const bool hoist_literals,
3554  ResultSetPtr* results,
3555  const ExecutorDeviceType device_type,
3556  std::vector<std::vector<const int8_t*>>& col_buffers,
3557  const std::vector<size_t> outer_tab_frag_ids,
3558  QueryExecutionContext* query_exe_context,
3559  const std::vector<std::vector<int64_t>>& num_rows,
3560  const std::vector<std::vector<uint64_t>>& frag_offsets,
3561  Data_Namespace::DataMgr* data_mgr,
3562  const int device_id,
3563  const int outer_table_id,
3564  const int64_t scan_limit,
3565  const uint32_t start_rowid,
3566  const uint32_t num_tables,
3567  const bool allow_runtime_interrupt,
3568  RenderInfo* render_info,
3569  const int64_t rows_to_process) {
3570  auto timer = DEBUG_TIMER(__func__);
3572  // TODO: get results via a separate method, but need to do something with literals.
3573  CHECK(!results || !(*results));
3574  if (col_buffers.empty()) {
3575  return 0;
3576  }
3577  CHECK_NE(ra_exe_unit.groupby_exprs.size(), size_t(0));
3578  // TODO(alex):
3579  // 1. Optimize size (make keys more compact).
3580  // 2. Resize on overflow.
3581  // 3. Optimize runtime.
3582  auto hoist_buf = serializeLiterals(compilation_result.literal_values, device_id);
3583  int32_t error_code = device_type == ExecutorDeviceType::GPU ? 0 : start_rowid;
3584  const auto join_hash_table_ptrs = getJoinHashTablePtrs(device_type, device_id);
3585  if (allow_runtime_interrupt) {
3586  bool isInterrupted = false;
3587  {
3590  const auto query_session = getCurrentQuerySession(session_read_lock);
3591  isInterrupted = checkIsQuerySessionInterrupted(query_session, session_read_lock);
3592  }
3593  if (isInterrupted) {
3595  }
3596  }
3597  if (g_enable_dynamic_watchdog && interrupted_.load()) {
3598  return ERR_INTERRUPTED;
3599  }
3600 
3601  RenderAllocatorMap* render_allocator_map_ptr = nullptr;
3602  if (render_info && render_info->useCudaBuffers()) {
3603  render_allocator_map_ptr = render_info->render_allocator_map_ptr.get();
3604  }
3605 
3606  VLOG(2) << "bool(ra_exe_unit.union_all)=" << bool(ra_exe_unit.union_all)
3607  << " ra_exe_unit.input_descs="
3608  << shared::printContainer(ra_exe_unit.input_descs)
3609  << " ra_exe_unit.input_col_descs="
3610  << shared::printContainer(ra_exe_unit.input_col_descs)
3611  << " ra_exe_unit.scan_limit=" << ra_exe_unit.scan_limit
3612  << " num_rows=" << shared::printContainer(num_rows)
3613  << " frag_offsets=" << shared::printContainer(frag_offsets)
3614  << " query_exe_context->query_buffers_->num_rows_="
3615  << query_exe_context->query_buffers_->num_rows_
3616  << " query_exe_context->query_mem_desc_.getEntryCount()="
3617  << query_exe_context->query_mem_desc_.getEntryCount()
3618  << " device_id=" << device_id << " outer_table_id=" << outer_table_id
3619  << " scan_limit=" << scan_limit << " start_rowid=" << start_rowid
3620  << " num_tables=" << num_tables;
3621 
3622  RelAlgExecutionUnit ra_exe_unit_copy = ra_exe_unit;
3623  // For UNION ALL, filter out input_descs and input_col_descs that are not associated
3624  // with outer_table_id.
3625  if (ra_exe_unit_copy.union_all) {
3626  // Sort outer_table_id first, then pop the rest off of ra_exe_unit_copy.input_descs.
3627  std::stable_sort(ra_exe_unit_copy.input_descs.begin(),
3628  ra_exe_unit_copy.input_descs.end(),
3629  [outer_table_id](auto const& a, auto const& b) {
3630  return a.getTableId() == outer_table_id &&
3631  b.getTableId() != outer_table_id;
3632  });
3633  while (!ra_exe_unit_copy.input_descs.empty() &&
3634  ra_exe_unit_copy.input_descs.back().getTableId() != outer_table_id) {
3635  ra_exe_unit_copy.input_descs.pop_back();
3636  }
3637  // Filter ra_exe_unit_copy.input_col_descs.
3638  ra_exe_unit_copy.input_col_descs.remove_if(
3639  [outer_table_id](auto const& input_col_desc) {
3640  return input_col_desc->getScanDesc().getTableId() != outer_table_id;
3641  });
3642  query_exe_context->query_mem_desc_.setEntryCount(ra_exe_unit_copy.scan_limit);
3643  }
3644 
3645  if (device_type == ExecutorDeviceType::CPU) {
3646  const int32_t scan_limit_for_query =
3647  ra_exe_unit_copy.union_all ? ra_exe_unit_copy.scan_limit : scan_limit;
3648  const int32_t max_matched = scan_limit_for_query == 0
3649  ? query_exe_context->query_mem_desc_.getEntryCount()
3650  : scan_limit_for_query;
3651  CpuCompilationContext* cpu_generated_code =
3652  dynamic_cast<CpuCompilationContext*>(compilation_result.generated_code.get());
3653  CHECK(cpu_generated_code);
3654  query_exe_context->launchCpuCode(ra_exe_unit_copy,
3655  cpu_generated_code,
3656  hoist_literals,
3657  hoist_buf,
3658  col_buffers,
3659  num_rows,
3660  frag_offsets,
3661  max_matched,
3662  &error_code,
3663  num_tables,
3664  join_hash_table_ptrs,
3665  rows_to_process);
3666  } else {
3667  try {
3668  GpuCompilationContext* gpu_generated_code =
3669  dynamic_cast<GpuCompilationContext*>(compilation_result.generated_code.get());
3670  CHECK(gpu_generated_code);
3671  query_exe_context->launchGpuCode(
3672  ra_exe_unit_copy,
3673  gpu_generated_code,
3674  hoist_literals,
3675  hoist_buf,
3676  col_buffers,
3677  num_rows,
3678  frag_offsets,
3679  ra_exe_unit_copy.union_all ? ra_exe_unit_copy.scan_limit : scan_limit,
3680  data_mgr,
3681  blockSize(),
3682  gridSize(),
3683  device_id,
3684  compilation_result.gpu_smem_context.getSharedMemorySize(),
3685  &error_code,
3686  num_tables,
3687  allow_runtime_interrupt,
3688  join_hash_table_ptrs,
3689  render_allocator_map_ptr);
3690  } catch (const OutOfMemory&) {
3691  return ERR_OUT_OF_GPU_MEM;
3692  } catch (const OutOfRenderMemory&) {
3693  return ERR_OUT_OF_RENDER_MEM;
3694  } catch (const StreamingTopNNotSupportedInRenderQuery&) {
3696  } catch (const std::exception& e) {
3697  LOG(FATAL) << "Error launching the GPU kernel: " << e.what();
3698  }
3699  }
3700 
3701  if (error_code == Executor::ERR_OVERFLOW_OR_UNDERFLOW ||
3702  error_code == Executor::ERR_DIV_BY_ZERO ||
3703  error_code == Executor::ERR_OUT_OF_TIME ||
3704  error_code == Executor::ERR_INTERRUPTED ||
3706  error_code == Executor::ERR_GEOS ||
3708  return error_code;
3709  }
3710 
3711  if (results && error_code != Executor::ERR_OVERFLOW_OR_UNDERFLOW &&
3712  error_code != Executor::ERR_DIV_BY_ZERO && !render_allocator_map_ptr) {
3713  *results = query_exe_context->getRowSet(ra_exe_unit_copy,
3714  query_exe_context->query_mem_desc_);
3715  CHECK(*results);
3716  VLOG(2) << "results->rowCount()=" << (*results)->rowCount();
3717  (*results)->holdLiterals(hoist_buf);
3718  }
3719  if (error_code < 0 && render_allocator_map_ptr) {
3720  auto const adjusted_scan_limit =
3721  ra_exe_unit_copy.union_all ? ra_exe_unit_copy.scan_limit : scan_limit;
3722  // More rows passed the filter than available slots. We don't have a count to check,
3723  // so assume we met the limit if a scan limit is set
3724  if (adjusted_scan_limit != 0) {
3725  return 0;
3726  } else {
3727  return error_code;
3728  }
3729  }
3730  if (results && error_code &&
3731  (!scan_limit || check_rows_less_than_needed(*results, scan_limit))) {
3732  return error_code; // unlucky, not enough results and we ran out of slots
3733  }
3734 
3735  return 0;
3736 }
3737 
3738 std::vector<int8_t*> Executor::getJoinHashTablePtrs(const ExecutorDeviceType device_type,
3739  const int device_id) {
3740  std::vector<int8_t*> table_ptrs;
3741  const auto& join_hash_tables = plan_state_->join_info_.join_hash_tables_;
3742  for (auto hash_table : join_hash_tables) {
3743  if (!hash_table) {
3744  CHECK(table_ptrs.empty());
3745  return {};
3746  }
3747  table_ptrs.push_back(hash_table->getJoinHashBuffer(
3748  device_type, device_type == ExecutorDeviceType::GPU ? device_id : 0));
3749  }
3750  return table_ptrs;
3751 }
3752 
3753 void Executor::nukeOldState(const bool allow_lazy_fetch,
3754  const std::vector<InputTableInfo>& query_infos,
3755  const PlanState::DeletedColumnsMap& deleted_cols_map,
3756  const RelAlgExecutionUnit* ra_exe_unit) {
3759  const bool contains_left_deep_outer_join =
3760  ra_exe_unit && std::find_if(ra_exe_unit->join_quals.begin(),
3761  ra_exe_unit->join_quals.end(),
3762  [](const JoinCondition& join_condition) {
3763  return join_condition.type == JoinType::LEFT;
3764  }) != ra_exe_unit->join_quals.end();
3765  cgen_state_.reset(
3766  new CgenState(query_infos.size(), contains_left_deep_outer_join, this));
3767  plan_state_.reset(new PlanState(allow_lazy_fetch && !contains_left_deep_outer_join,
3768  query_infos,
3769  deleted_cols_map,
3770  this));
3771 }
3772 
3773 void Executor::preloadFragOffsets(const std::vector<InputDescriptor>& input_descs,
3774  const std::vector<InputTableInfo>& query_infos) {
3776  const auto ld_count = input_descs.size();
3777  auto frag_off_ptr = get_arg_by_name(cgen_state_->row_func_, "frag_row_off");
3778  for (size_t i = 0; i < ld_count; ++i) {
3779  CHECK_LT(i, query_infos.size());
3780  const auto frag_count = query_infos[i].info.fragments.size();
3781  if (i > 0) {
3782  cgen_state_->frag_offsets_.push_back(nullptr);
3783  } else {
3784  if (frag_count > 1) {
3785  cgen_state_->frag_offsets_.push_back(cgen_state_->ir_builder_.CreateLoad(
3786  frag_off_ptr->getType()->getPointerElementType(), frag_off_ptr));
3787  } else {
3788  cgen_state_->frag_offsets_.push_back(nullptr);
3789  }
3790  }
3791  }
3792 }
3793 
3795  const std::shared_ptr<Analyzer::BinOper>& qual_bin_oper,
3796  const std::vector<InputTableInfo>& query_infos,
3797  const MemoryLevel memory_level,
3798  const JoinType join_type,
3799  const HashType preferred_hash_type,
3800  ColumnCacheMap& column_cache,
3801  const HashTableBuildDagMap& hashtable_build_dag_map,
3802  const RegisteredQueryHint& query_hint,
3803  const TableIdToNodeMap& table_id_to_node_map) {
3804  if (!g_enable_overlaps_hashjoin && qual_bin_oper->is_overlaps_oper()) {
3805  return {nullptr, "Overlaps hash join disabled, attempting to fall back to loop join"};
3806  }
3807  if (g_enable_dynamic_watchdog && interrupted_.load()) {
3809  }
3810  try {
3811  auto tbl = HashJoin::getInstance(qual_bin_oper,
3812  query_infos,
3813  memory_level,
3814  join_type,
3815  preferred_hash_type,
3816  deviceCountForMemoryLevel(memory_level),
3817  column_cache,
3818  this,
3819  hashtable_build_dag_map,
3820  query_hint,
3821  table_id_to_node_map);
3822  return {tbl, ""};
3823  } catch (const HashJoinFail& e) {
3824  return {nullptr, e.what()};
3825  }
3826 }
3827 
3828 int8_t Executor::warpSize() const {
3829  const auto& dev_props = cudaMgr()->getAllDeviceProperties();
3830  CHECK(!dev_props.empty());
3831  return dev_props.front().warpSize;
3832 }
3833 
3834 // TODO(adb): should these three functions have consistent symantics if cuda mgr does not
3835 // exist?
3836 unsigned Executor::gridSize() const {
3837  CHECK(data_mgr_);
3838  const auto cuda_mgr = data_mgr_->getCudaMgr();
3839  if (!cuda_mgr) {
3840  return 0;
3841  }
3842  return grid_size_x_ ? grid_size_x_ : 2 * cuda_mgr->getMinNumMPsForAllDevices();
3843 }
3844 
3845 unsigned Executor::numBlocksPerMP() const {
3846  return grid_size_x_ ? std::ceil(grid_size_x_ / cudaMgr()->getMinNumMPsForAllDevices())
3847  : 2;
3848 }
3849 
3850 unsigned Executor::blockSize() const {
3851  CHECK(data_mgr_);
3852  const auto cuda_mgr = data_mgr_->getCudaMgr();
3853  if (!cuda_mgr) {
3854  return 0;
3855  }
3856  const auto& dev_props = cuda_mgr->getAllDeviceProperties();
3857  return block_size_x_ ? block_size_x_ : dev_props.front().maxThreadsPerBlock;
3858 }
3859 
3860 void Executor::setGridSize(unsigned grid_size) {
3861  grid_size_x_ = grid_size;
3862 }
3863 
3865  grid_size_x_ = 0;
3866 }
3867 
3868 void Executor::setBlockSize(unsigned block_size) {
3869  block_size_x_ = block_size;
3870 }
3871 
3873  block_size_x_ = 0;
3874 }
3875 
3877  return max_gpu_slab_size_;
3878 }
3879 
3880 int64_t Executor::deviceCycles(int milliseconds) const {
3881  const auto& dev_props = cudaMgr()->getAllDeviceProperties();
3882  return static_cast<int64_t>(dev_props.front().clockKhz) * milliseconds;
3883 }
3884 
3885 llvm::Value* Executor::castToFP(llvm::Value* value,
3886  SQLTypeInfo const& from_ti,
3887  SQLTypeInfo const& to_ti) {
3889  if (value->getType()->isIntegerTy() && from_ti.is_number() && to_ti.is_fp() &&
3890  (!from_ti.is_fp() || from_ti.get_size() != to_ti.get_size())) {
3891  llvm::Type* fp_type{nullptr};
3892  switch (to_ti.get_size()) {
3893  case 4:
3894  fp_type = llvm::Type::getFloatTy(cgen_state_->context_);
3895  break;
3896  case 8:
3897  fp_type = llvm::Type::getDoubleTy(cgen_state_->context_);
3898  break;
3899  default:
3900  LOG(FATAL) << "Unsupported FP size: " << to_ti.get_size();
3901  }
3902  value = cgen_state_->ir_builder_.CreateSIToFP(value, fp_type);
3903  if (from_ti.get_scale()) {
3904  value = cgen_state_->ir_builder_.CreateFDiv(
3905  value,
3906  llvm::ConstantFP::get(value->getType(), exp_to_scale(from_ti.get_scale())));
3907  }
3908  }
3909  return value;
3910 }
3911 
3912 llvm::Value* Executor::castToIntPtrTyIn(llvm::Value* val, const size_t bitWidth) {
3914  CHECK(val->getType()->isPointerTy());
3915 
3916  const auto val_ptr_type = static_cast<llvm::PointerType*>(val->getType());
3917  const auto val_type = val_ptr_type->getPointerElementType();
3918  size_t val_width = 0;
3919  if (val_type->isIntegerTy()) {
3920  val_width = val_type->getIntegerBitWidth();
3921  } else {
3922  if (val_type->isFloatTy()) {
3923  val_width = 32;
3924  } else {
3925  CHECK(val_type->isDoubleTy());
3926  val_width = 64;
3927  }
3928  }
3929  CHECK_LT(size_t(0), val_width);
3930  if (bitWidth == val_width) {
3931  return val;
3932  }
3933  return cgen_state_->ir_builder_.CreateBitCast(
3934  val, llvm::PointerType::get(get_int_type(bitWidth, cgen_state_->context_), 0));
3935 }
3936 
3937 #define EXECUTE_INCLUDE
3938 #include "ArrayOps.cpp"
3939 #include "DateAdd.cpp"
3940 #include "GeoOps.cpp"
3941 #include "StringFunctions.cpp"
3943 #undef EXECUTE_INCLUDE
3944 
3945 namespace {
3947  const ColumnDescriptor* deleted_cd) {
3948  auto deleted_cols_it = deleted_cols_map.find(deleted_cd->tableId);
3949  if (deleted_cols_it == deleted_cols_map.end()) {
3950  CHECK(
3951  deleted_cols_map.insert(std::make_pair(deleted_cd->tableId, deleted_cd)).second);
3952  } else {
3953  CHECK_EQ(deleted_cd, deleted_cols_it->second);
3954  }
3955 }
3956 } // namespace
3957 
3958 std::tuple<RelAlgExecutionUnit, PlanState::DeletedColumnsMap> Executor::addDeletedColumn(
3959  const RelAlgExecutionUnit& ra_exe_unit,
3960  const CompilationOptions& co) {
3961  if (!co.filter_on_deleted_column) {
3962  return std::make_tuple(ra_exe_unit, PlanState::DeletedColumnsMap{});
3963  }
3964  auto ra_exe_unit_with_deleted = ra_exe_unit;
3965  PlanState::DeletedColumnsMap deleted_cols_map;
3966  for (const auto& input_table : ra_exe_unit_with_deleted.input_descs) {
3967  if (input_table.getSourceType() != InputSourceType::TABLE) {
3968  continue;
3969  }
3970  const auto td = catalog_->getMetadataForTable(input_table.getTableId());
3971  CHECK(td);
3972  const auto deleted_cd = catalog_->getDeletedColumnIfRowsDeleted(td);
3973  if (!deleted_cd) {
3974  continue;
3975  }
3976  CHECK(deleted_cd->columnType.is_boolean());
3977  // check deleted column is not already present
3978  bool found = false;
3979  for (const auto& input_col : ra_exe_unit_with_deleted.input_col_descs) {
3980  if (input_col.get()->getColId() == deleted_cd->columnId &&
3981  input_col.get()->getScanDesc().getTableId() == deleted_cd->tableId &&
3982  input_col.get()->getScanDesc().getNestLevel() == input_table.getNestLevel()) {
3983  found = true;
3984  add_deleted_col_to_map(deleted_cols_map, deleted_cd);
3985  break;
3986  }
3987  }
3988  if (!found) {
3989  // add deleted column
3990  ra_exe_unit_with_deleted.input_col_descs.emplace_back(new InputColDescriptor(
3991  deleted_cd->columnId, deleted_cd->tableId, input_table.getNestLevel()));
3992  add_deleted_col_to_map(deleted_cols_map, deleted_cd);
3993  }
3994  }
3995  return std::make_tuple(ra_exe_unit_with_deleted, deleted_cols_map);
3996 }
3997 
3998 namespace {
3999 // Note(Wamsi): `get_hpt_overflow_underflow_safe_scaled_value` will return `true` for safe
4000 // scaled epoch value and `false` for overflow/underflow values as the first argument of
4001 // return type.
4002 std::tuple<bool, int64_t, int64_t> get_hpt_overflow_underflow_safe_scaled_values(
4003  const int64_t chunk_min,
4004  const int64_t chunk_max,
4005  const SQLTypeInfo& lhs_type,
4006  const SQLTypeInfo& rhs_type) {
4007  const int32_t ldim = lhs_type.get_dimension();
4008  const int32_t rdim = rhs_type.get_dimension();
4009  CHECK(ldim != rdim);
4010  const auto scale = DateTimeUtils::get_timestamp_precision_scale(abs(rdim - ldim));
4011  if (ldim > rdim) {
4012  // LHS type precision is more than RHS col type. No chance of overflow/underflow.
4013  return {true, chunk_min / scale, chunk_max / scale};
4014  }
4015 
4016  using checked_int64_t = boost::multiprecision::number<
4017  boost::multiprecision::cpp_int_backend<64,
4018  64,
4019  boost::multiprecision::signed_magnitude,
4020  boost::multiprecision::checked,
4021  void>>;
4022 
4023  try {
4024  auto ret =
4025  std::make_tuple(true,
4026  int64_t(checked_int64_t(chunk_min) * checked_int64_t(scale)),
4027  int64_t(checked_int64_t(chunk_max) * checked_int64_t(scale)));
4028  return ret;
4029  } catch (const std::overflow_error& e) {
4030  // noop
4031  }
4032  return std::make_tuple(false, chunk_min, chunk_max);
4033 }
4034 
4035 } // namespace
4036 
4038  const int table_id,
4039  const Fragmenter_Namespace::FragmentInfo& fragment) {
4040  // Skip temporary tables
4041  if (table_id < 0) {
4042  return false;
4043  }
4044 
4045  const auto td = catalog_->getMetadataForTable(fragment.physicalTableId);
4046  CHECK(td);
4047  const auto deleted_cd = catalog_->getDeletedColumnIfRowsDeleted(td);
4048  if (!deleted_cd) {
4049  return false;
4050  }
4051 
4052  const auto& chunk_type = deleted_cd->columnType;
4053  CHECK(chunk_type.is_boolean());
4054 
4055  const auto deleted_col_id = deleted_cd->columnId;
4056  auto chunk_meta_it = fragment.getChunkMetadataMap().find(deleted_col_id);
4057  if (chunk_meta_it != fragment.getChunkMetadataMap().end()) {
4058  const int64_t chunk_min =
4059  extract_min_stat_int_type(chunk_meta_it->second->chunkStats, chunk_type);
4060  const int64_t chunk_max =
4061  extract_max_stat_int_type(chunk_meta_it->second->chunkStats, chunk_type);
4062  if (chunk_min == 1 && chunk_max == 1) { // Delete chunk if metadata says full bytemap
4063  // is true (signifying all rows deleted)
4064  return true;
4065  }
4066  }
4067  return false;
4068 }
4069 
4071  const Analyzer::BinOper* comp_expr,
4072  const Analyzer::ColumnVar* lhs_col,
4073  const Fragmenter_Namespace::FragmentInfo& fragment,
4074  const Analyzer::Constant* rhs_const) const {
4075  const int col_id = lhs_col->get_column_id();
4076  auto chunk_meta_it = fragment.getChunkMetadataMap().find(col_id);
4077  if (chunk_meta_it == fragment.getChunkMetadataMap().end()) {
4079  }
4080  double chunk_min{0.};
4081  double chunk_max{0.};
4082  const auto& chunk_type = lhs_col->get_type_info();
4083  chunk_min = extract_min_stat_fp_type(chunk_meta_it->second->chunkStats, chunk_type);
4084  chunk_max = extract_max_stat_fp_type(chunk_meta_it->second->chunkStats, chunk_type);
4085  if (chunk_min > chunk_max) {
4087  }
4088 
4089  const auto datum_fp = rhs_const->get_constval();
4090  const auto rhs_type = rhs_const->get_type_info().get_type();
4091  CHECK(rhs_type == kFLOAT || rhs_type == kDOUBLE);
4092 
4093  // Do we need to codegen the constant like the integer path does?
4094  const auto rhs_val = rhs_type == kFLOAT ? datum_fp.floatval : datum_fp.doubleval;
4095 
4096  // Todo: dedup the following comparison code with the integer/timestamp path, it is
4097  // slightly tricky due to do cleanly as we do not have rowid on this path
4098  switch (comp_expr->get_optype()) {
4099  case kGE:
4100  if (chunk_max < rhs_val) {
4102  }
4103  break;
4104  case kGT:
4105  if (chunk_max <= rhs_val) {
4107  }
4108  break;
4109  case kLE:
4110  if (chunk_min > rhs_val) {
4112  }
4113  break;
4114  case kLT:
4115  if (chunk_min >= rhs_val) {
4117  }
4118  break;
4119  case kEQ:
4120  if (chunk_min > rhs_val || chunk_max < rhs_val) {
4122  }
4123  break;
4124  default:
4125  break;
4126  }
4128 }
4129 
4130 std::pair<bool, int64_t> Executor::skipFragment(
4131  const InputDescriptor& table_desc,
4132  const Fragmenter_Namespace::FragmentInfo& fragment,
4133  const std::list<std::shared_ptr<Analyzer::Expr>>& simple_quals,
4134  const std::vector<uint64_t>& frag_offsets,
4135  const size_t frag_idx) {
4136  const int table_id = table_desc.getTableId();
4137 
4138  // First check to see if all of fragment is deleted, in which case we know we can skip
4139  if (isFragmentFullyDeleted(table_id, fragment)) {
4140  VLOG(2) << "Skipping deleted fragment with table id: " << fragment.physicalTableId
4141  << ", fragment id: " << frag_idx;
4142  return {true, -1};
4143  }
4144 
4145  for (const auto& simple_qual : simple_quals) {
4146  const auto comp_expr =
4147  std::dynamic_pointer_cast<const Analyzer::BinOper>(simple_qual);
4148  if (!comp_expr) {
4149  // is this possible?
4150  return {false, -1};
4151  }
4152  const auto lhs = comp_expr->get_left_operand();
4153  auto lhs_col = dynamic_cast<const Analyzer::ColumnVar*>(lhs);
4154  if (!lhs_col || !lhs_col->get_table_id() || lhs_col->get_rte_idx()) {
4155  // See if lhs is a simple cast that was allowed through normalize_simple_predicate
4156  auto lhs_uexpr = dynamic_cast<const Analyzer::UOper*>(lhs);
4157  if (lhs_uexpr) {
4158  CHECK(lhs_uexpr->get_optype() ==
4159  kCAST); // We should have only been passed a cast expression
4160  lhs_col = dynamic_cast<const Analyzer::ColumnVar*>(lhs_uexpr->get_operand());
4161  if (!lhs_col || !lhs_col->get_table_id() || lhs_col->get_rte_idx()) {
4162  continue;
4163  }
4164  } else {
4165  continue;
4166  }
4167  }
4168  const auto rhs = comp_expr->get_right_operand();
4169  const auto rhs_const = dynamic_cast<const Analyzer::Constant*>(rhs);
4170  if (!rhs_const) {
4171  // is this possible?
4172  return {false, -1};
4173  }
4174  if (!lhs->get_type_info().is_integer() && !lhs->get_type_info().is_time() &&
4175  !lhs->get_type_info().is_fp()) {
4176  continue;
4177  }
4178  if (lhs->get_type_info().is_fp()) {
4179  const auto fragment_skip_status =
4180  canSkipFragmentForFpQual(comp_expr.get(), lhs_col, fragment, rhs_const);
4181  switch (fragment_skip_status) {
4183  return {true, -1};
4185  return {false, -1};
4187  continue;
4188  default:
4189  UNREACHABLE();
4190  }
4191  }
4192 
4193  // Everything below is logic for integer and integer-backed timestamps
4194  // TODO: Factor out into separate function per canSkipFragmentForFpQual above
4195 
4196  if (lhs_col->get_type_info().is_timestamp() &&
4197  rhs_const->get_type_info().is_any(kTIME)) {
4198  // when casting from a timestamp to time
4199  // is not possible to get a valid range
4200  // so we can't skip any fragment
4201  continue;
4202  }
4203 
4204  const int col_id = lhs_col->get_column_id();
4205  auto chunk_meta_it = fragment.getChunkMetadataMap().find(col_id);
4206  int64_t chunk_min{0};
4207  int64_t chunk_max{0};
4208  bool is_rowid{false};
4209  size_t start_rowid{0};
4210  if (chunk_meta_it == fragment.getChunkMetadataMap().end()) {
4211  auto cd = get_column_descriptor(col_id, table_id, *catalog_);
4212  if (cd->isVirtualCol) {
4213  CHECK(cd->columnName == "rowid");
4214  const auto& table_generation = getTableGeneration(table_id);
4215  start_rowid = table_generation.start_rowid;
4216  chunk_min = frag_offsets[frag_idx] + start_rowid;
4217  chunk_max = frag_offsets[frag_idx + 1] - 1 + start_rowid;
4218  is_rowid = true;
4219  }
4220  } else {
4221  const auto& chunk_type = lhs_col->get_type_info();
4222  chunk_min =
4223  extract_min_stat_int_type(chunk_meta_it->second->chunkStats, chunk_type);
4224  chunk_max =
4225  extract_max_stat_int_type(chunk_meta_it->second->chunkStats, chunk_type);
4226  }
4227  if (chunk_min > chunk_max) {
4228  // invalid metadata range, do not skip fragment
4229  return {false, -1};
4230  }
4231  if (lhs->get_type_info().is_timestamp() &&
4232  (lhs_col->get_type_info().get_dimension() !=
4233  rhs_const->get_type_info().get_dimension()) &&
4234  (lhs_col->get_type_info().is_high_precision_timestamp() ||
4235  rhs_const->get_type_info().is_high_precision_timestamp())) {
4236  // If original timestamp lhs col has different precision,
4237  // column metadata holds value in original precision
4238  // therefore adjust rhs value to match lhs precision
4239 
4240  // Note(Wamsi): We adjust rhs const value instead of lhs value to not
4241  // artificially limit the lhs column range. RHS overflow/underflow is already
4242  // been validated in `TimeGM::get_overflow_underflow_safe_epoch`.
4243  bool is_valid;
4244  std::tie(is_valid, chunk_min, chunk_max) =
4246  chunk_min, chunk_max, lhs_col->get_type_info(), rhs_const->get_type_info());
4247  if (!is_valid) {
4248  VLOG(4) << "Overflow/Underflow detecting in fragments skipping logic.\nChunk min "
4249  "value: "
4250  << std::to_string(chunk_min)
4251  << "\nChunk max value: " << std::to_string(chunk_max)
4252  << "\nLHS col precision is: "
4253  << std::to_string(lhs_col->get_type_info().get_dimension())
4254  << "\nRHS precision is: "
4255  << std::to_string(rhs_const->get_type_info().get_dimension()) << ".";
4256  return {false, -1};
4257  }
4258  }
4259  if (lhs_col->get_type_info().is_timestamp() && rhs_const->get_type_info().is_date()) {
4260  // It is obvious that a cast from timestamp to date is happening here,
4261  // so we have to correct the chunk min and max values to lower the precision as of
4262  // the date
4263  chunk_min = DateTruncateHighPrecisionToDate(
4264  chunk_min, pow(10, lhs_col->get_type_info().get_dimension()));
4265  chunk_max = DateTruncateHighPrecisionToDate(
4266  chunk_max, pow(10, lhs_col->get_type_info().get_dimension()));
4267  }
4268  llvm::LLVMContext local_context;
4269  CgenState local_cgen_state(local_context);
4270  CodeGenerator code_generator(&local_cgen_state, nullptr);
4271 
4272  const auto rhs_val =
4273  CodeGenerator::codegenIntConst(rhs_const, &local_cgen_state)->getSExtValue();
4274 
4275  switch (comp_expr->get_optype()) {
4276  case kGE:
4277  if (chunk_max < rhs_val) {
4278  return {true, -1};
4279  }
4280  break;
4281  case kGT:
4282  if (chunk_max <= rhs_val) {
4283  return {true, -1};
4284  }
4285  break;
4286  case kLE:
4287  if (chunk_min > rhs_val) {
4288  return {true, -1};
4289  }
4290  break;
4291  case kLT:
4292  if (chunk_min >= rhs_val) {
4293  return {true, -1};
4294  }
4295  break;
4296  case kEQ:
4297  if (chunk_min > rhs_val || chunk_max < rhs_val) {
4298  return {true, -1};
4299  } else if (is_rowid) {
4300  return {false, rhs_val - start_rowid};
4301  }
4302  break;
4303  default:
4304  break;
4305  }
4306  }
4307  return {false, -1};
4308 }
4309 
4310 /*
4311  * The skipFragmentInnerJoins process all quals stored in the execution unit's
4312  * join_quals and gather all the ones that meet the "simple_qual" characteristics
4313  * (logical expressions with AND operations, etc.). It then uses the skipFragment function
4314  * to decide whether the fragment should be skipped or not. The fragment will be skipped
4315  * if at least one of these skipFragment calls return a true statment in its first value.
4316  * - The code depends on skipFragment's output to have a meaningful (anything but -1)
4317  * second value only if its first value is "false".
4318  * - It is assumed that {false, n > -1} has higher priority than {true, -1},
4319  * i.e., we only skip if none of the quals trigger the code to update the
4320  * rowid_lookup_key
4321  * - Only AND operations are valid and considered:
4322  * - `select * from t1,t2 where A and B and C`: A, B, and C are considered for causing
4323  * the skip
4324  * - `select * from t1,t2 where (A or B) and C`: only C is considered
4325  * - `select * from t1,t2 where A or B`: none are considered (no skipping).
4326  * - NOTE: (re: intermediate projections) the following two queries are fundamentally
4327  * implemented differently, which cause the first one to skip correctly, but the second
4328  * one will not skip.
4329  * - e.g. #1, select * from t1 join t2 on (t1.i=t2.i) where (A and B); -- skips if
4330  * possible
4331  * - e.g. #2, select * from t1 join t2 on (t1.i=t2.i and A and B); -- intermediate
4332  * projection, no skipping
4333  */
4334 std::pair<bool, int64_t> Executor::skipFragmentInnerJoins(
4335  const InputDescriptor& table_desc,
4336  const RelAlgExecutionUnit& ra_exe_unit,
4337  const Fragmenter_Namespace::FragmentInfo& fragment,
4338  const std::vector<uint64_t>& frag_offsets,
4339  const size_t frag_idx) {
4340  std::pair<bool, int64_t> skip_frag{false, -1};
4341  for (auto& inner_join : ra_exe_unit.join_quals) {
4342  if (inner_join.type != JoinType::INNER) {
4343  continue;
4344  }
4345 
4346  // extracting all the conjunctive simple_quals from the quals stored for the inner
4347  // join
4348  std::list<std::shared_ptr<Analyzer::Expr>> inner_join_simple_quals;
4349  for (auto& qual : inner_join.quals) {
4350  auto temp_qual = qual_to_conjunctive_form(qual);
4351  inner_join_simple_quals.insert(inner_join_simple_quals.begin(),
4352  temp_qual.simple_quals.begin(),
4353  temp_qual.simple_quals.end());
4354  }
4355  auto temp_skip_frag = skipFragment(
4356  table_desc, fragment, inner_join_simple_quals, frag_offsets, frag_idx);
4357  if (temp_skip_frag.second != -1) {
4358  skip_frag.second = temp_skip_frag.second;
4359  return skip_frag;
4360  } else {
4361  skip_frag.first = skip_frag.first || temp_skip_frag.first;
4362  }
4363  }
4364  return skip_frag;
4365 }
4366 
4368  const std::unordered_set<PhysicalInput>& phys_inputs) {
4369  AggregatedColRange agg_col_range_cache;
4370  CHECK(catalog_);
4371  std::unordered_set<int> phys_table_ids;
4372  for (const auto& phys_input : phys_inputs) {
4373  phys_table_ids.insert(phys_input.table_id);
4374  }
4375  std::vector<InputTableInfo> query_infos;
4376  for (const int table_id : phys_table_ids) {
4377  query_infos.emplace_back(InputTableInfo{table_id, getTableInfo(table_id)});
4378  }
4379  for (const auto& phys_input : phys_inputs) {
4380  const auto cd =
4381  catalog_->getMetadataForColumn(phys_input.table_id, phys_input.col_id);
4382  CHECK(cd);
4383  if (ExpressionRange::typeSupportsRange(cd->columnType)) {
4384  const auto col_var = boost::make_unique<Analyzer::ColumnVar>(
4385  cd->columnType, phys_input.table_id, phys_input.col_id, 0);
4386  const auto col_range = getLeafColumnRange(col_var.get(), query_infos, this, false);
4387  agg_col_range_cache.setColRange(phys_input, col_range);
4388  }
4389  }
4390  return agg_col_range_cache;
4391 }
4392 
4394  const std::unordered_set<PhysicalInput>& phys_inputs) {
4395  StringDictionaryGenerations string_dictionary_generations;
4396  CHECK(catalog_);
4397  // Foreign tables may have not populated dictionaries for encoded columns. If this is
4398  // the case then we need to populate them here to make sure that the generations are set
4399  // correctly.
4400  prepare_string_dictionaries(phys_inputs, *catalog_);
4401  for (const auto& phys_input : phys_inputs) {
4402  const auto cd =
4403  catalog_->getMetadataForColumn(phys_input.table_id, phys_input.col_id);
4404  CHECK(cd);
4405  const auto& col_ti =
4406  cd->columnType.is_array() ? cd->columnType.get_elem_type() : cd->columnType;
4407  if (col_ti.is_string() && col_ti.get_compression() == kENCODING_DICT) {
4408  const int dict_id = col_ti.get_comp_param();
4409  const auto dd = catalog_->getMetadataForDict(dict_id);
4410  CHECK(dd && dd->stringDict);
4411  string_dictionary_generations.setGeneration(dict_id,
4412  dd->stringDict->storageEntryCount());
4413  }
4414  }
4415  return string_dictionary_generations;
4416 }
4417 
4419  std::unordered_set<int> phys_table_ids) {
4420  TableGenerations table_generations;
4421  for (const int table_id : phys_table_ids) {
4422  const auto table_info = getTableInfo(table_id);
4423  table_generations.setGeneration(
4424  table_id,
4425  TableGeneration{static_cast<int64_t>(table_info.getPhysicalNumTuples()), 0});
4426  }
4427  return table_generations;
4428 }
4429 
4430 void Executor::setupCaching(const std::unordered_set<PhysicalInput>& phys_inputs,
4431  const std::unordered_set<int>& phys_table_ids) {
4432  CHECK(catalog_);
4434  std::make_shared<RowSetMemoryOwner>(Executor::getArenaBlockSize(), cpu_threads());
4435  row_set_mem_owner_->setDictionaryGenerations(
4436  computeStringDictionaryGenerations(phys_inputs));
4438  table_generations_ = computeTableGenerations(phys_table_ids);
4439 }
4440 
4442  return recycler_mutex_;
4443 }
4444 
4446  return query_plan_dag_cache_;
4447 }
4448 
4451 }
4452 
4454  return executor_session_mutex_;
4455 }
4456 
4459  return current_query_session_;
4460 }
4461 
4463  const QuerySessionId& candidate_query_session,
4465  // if current_query_session is equal to the candidate_query_session,
4466  // or it is empty session we consider
4467  return !candidate_query_session.empty() &&
4468  (current_query_session_ == candidate_query_session);
4469 }
4470 
4471 // used only for testing
4473  const QuerySessionId& candidate_query_session,
4475  if (queries_session_map_.count(candidate_query_session) &&
4476  !queries_session_map_.at(candidate_query_session).empty()) {
4477  return queries_session_map_.at(candidate_query_session)
4478  .begin()
4479  ->second.getQueryStatus();
4480  }
4481  return QuerySessionStatus::QueryStatus::UNDEFINED;
4482 }
4483 
4487 }
4488 
4490  const QuerySessionId& query_session_id,
4491  const std::string& query_str,
4492  const std::string& query_submitted_time) {
4493  if (!query_session_id.empty()) {
4494  // if session is valid, do update 1) the exact executor id and 2) query status
4497  query_session_id, query_submitted_time, executor_id_, write_lock);
4498  updateQuerySessionStatusWithLock(query_session_id,
4499  query_submitted_time,
4500  QuerySessionStatus::QueryStatus::PENDING_EXECUTOR,
4501  write_lock);
4502  }
4503  return {query_session_id, query_str};
4504 }
4505 
4507  // check whether we are okay to execute the "pending" query
4508  // i.e., before running the query check if this query session is "ALREADY" interrupted
4510  if (query_session.empty()) {
4511  return;
4512  }
4513  if (queries_interrupt_flag_.find(query_session) == queries_interrupt_flag_.end()) {
4514  // something goes wrong since we assume this is caller's responsibility
4515  // (call this function only for enrolled query session)
4516  if (!queries_session_map_.count(query_session)) {
4517  VLOG(1) << "Interrupting pending query is not available since the query session is "
4518  "not enrolled";
4519  } else {
4520  // here the query session is enrolled but the interrupt flag is not registered
4521  VLOG(1)
4522  << "Interrupting pending query is not available since its interrupt flag is "
4523  "not registered";
4524  }
4525  return;
4526  }
4527  if (queries_interrupt_flag_[query_session]) {
4529  }
4530 }
4531 
4533  const std::string& submitted_time_str) {
4535  // clear the interrupt-related info for a finished query
4536  if (query_session.empty()) {
4537  return;
4538  }
4539  removeFromQuerySessionList(query_session, submitted_time_str, session_write_lock);
4540  if (query_session.compare(current_query_session_) == 0) {
4541  invalidateRunningQuerySession(session_write_lock);
4542  resetInterrupt();
4543  }
4544 }
4545 
4547  const QuerySessionId& query_session,
4548  const std::string& submitted_time_str,
4549  const QuerySessionStatus::QueryStatus new_query_status) {
4550  // update the running query session's the current status
4552  if (query_session.empty()) {
4553  return;
4554  }
4555  if (new_query_status == QuerySessionStatus::QueryStatus::RUNNING_QUERY_KERNEL) {
4556  current_query_session_ = query_session;
4557  }
4559  query_session, submitted_time_str, new_query_status, session_write_lock);
4560 }
4561 
4563  const QuerySessionId& query_session,
4564  const std::string& query_str,
4565  const std::string& submitted_time_str,
4566  const size_t executor_id,
4567  const QuerySessionStatus::QueryStatus query_session_status) {
4568  // enroll the query session into the Executor's session map
4570  if (query_session.empty()) {
4571  return;
4572  }
4573 
4574  addToQuerySessionList(query_session,
4575  query_str,
4576  submitted_time_str,
4577  executor_id,
4578  query_session_status,
4579  session_write_lock);
4580 
4581  if (query_session_status == QuerySessionStatus::QueryStatus::RUNNING_QUERY_KERNEL) {
4582  current_query_session_ = query_session;
4583  }
4584 }
4585 
4588  return queries_session_map_.size();
4589 }
4590 
4592  const QuerySessionId& query_session,
4593  const std::string& query_str,
4594  const std::string& submitted_time_str,
4595  const size_t executor_id,
4596  const QuerySessionStatus::QueryStatus query_status,
4598  // an internal API that enrolls the query session into the Executor's session map
4599  if (queries_session_map_.count(query_session)) {
4600  if (queries_session_map_.at(query_session).count(submitted_time_str)) {
4601  queries_session_map_.at(query_session).erase(submitted_time_str);
4602  queries_session_map_.at(query_session)
4603  .emplace(submitted_time_str,
4604  QuerySessionStatus(query_session,
4605  executor_id,
4606  query_str,
4607  submitted_time_str,
4608  query_status));
4609  } else {
4610  queries_session_map_.at(query_session)
4611  .emplace(submitted_time_str,
4612  QuerySessionStatus(query_session,
4613  executor_id,
4614  query_str,
4615  submitted_time_str,
4616  query_status));
4617  }
4618  } else {
4619  std::map<std::string, QuerySessionStatus> executor_per_query_map;
4620  executor_per_query_map.emplace(
4621  submitted_time_str,
4623  query_session, executor_id, query_str, submitted_time_str, query_status));
4624  queries_session_map_.emplace(query_session, executor_per_query_map);
4625  }
4626  return queries_interrupt_flag_.emplace(query_session, false).second;
4627 }
4628 
4630  const QuerySessionId& query_session,
4631  const std::string& submitted_time_str,
4632  const QuerySessionStatus::QueryStatus updated_query_status,
4634  // an internal API that updates query session status
4635  if (query_session.empty()) {
4636  return false;
4637  }
4638  if (queries_session_map_.count(query_session)) {
4639  for (auto& query_status : queries_session_map_.at(query_session)) {
4640  auto target_submitted_t_str = query_status.second.getQuerySubmittedTime();
4641  // no time difference --> found the target query status
4642  if (submitted_time_str.compare(target_submitted_t_str) == 0) {
4643  auto prev_status = query_status.second.getQueryStatus();
4644  if (prev_status == updated_query_status) {
4645  return false;
4646  }
4647  query_status.second.setQueryStatus(updated_query_status);
4648  return true;
4649  }
4650  }
4651  }
4652  return false;
4653 }
4654 
4656  const QuerySessionId& query_session,
4657  const std::string& submitted_time_str,
4658  const size_t executor_id,
4660  // update the executor id of the query session
4661  if (query_session.empty()) {
4662  return false;
4663  }
4664  if (queries_session_map_.count(query_session)) {
4665  auto storage = queries_session_map_.at(query_session);
4666  for (auto it = storage.begin(); it != storage.end(); it++) {
4667  auto target_submitted_t_str = it->second.getQuerySubmittedTime();
4668  // no time difference --> found the target query status
4669  if (submitted_time_str.compare(target_submitted_t_str) == 0) {
4670  queries_session_map_.at(query_session)
4671  .at(submitted_time_str)
4672  .setExecutorId(executor_id);
4673  return true;
4674  }
4675  }
4676  }
4677  return false;
4678 }
4679 
4681  const QuerySessionId& query_session,
4682  const std::string& submitted_time_str,
4684  if (query_session.empty()) {
4685  return false;
4686  }
4687  if (queries_session_map_.count(query_session)) {
4688  auto& storage = queries_session_map_.at(query_session);
4689  if (storage.size() > 1) {
4690  // in this case we only remove query executor info
4691  for (auto it = storage.begin(); it != storage.end(); it++) {
4692  auto target_submitted_t_str = it->second.getQuerySubmittedTime();
4693  // no time difference && have the same executor id--> found the target query
4694  if (it->second.getExecutorId() == executor_id_ &&
4695  submitted_time_str.compare(target_submitted_t_str) == 0) {
4696  storage.erase(it);
4697  return true;
4698  }
4699  }
4700  } else if (storage.size() == 1) {
4701  // here this session only has a single query executor
4702  // so we clear both executor info and its interrupt flag
4703  queries_session_map_.erase(query_session);
4704  queries_interrupt_flag_.erase(query_session);
4705  if (interrupted_.load()) {
4706  interrupted_.store(false);
4707  }
4708  return true;
4709  }
4710  }
4711  return false;
4712 }
4713 
4715  const QuerySessionId& query_session,
4717  if (query_session.empty()) {
4718  return;
4719  }
4720  if (queries_interrupt_flag_.find(query_session) != queries_interrupt_flag_.end()) {
4721  queries_interrupt_flag_[query_session] = true;
4722  }
4723 }
4724 
4726  const QuerySessionId& query_session,
4728  if (query_session.empty()) {
4729  return false;
4730  }
4731  auto flag_it = queries_interrupt_flag_.find(query_session);
4732  return !query_session.empty() && flag_it != queries_interrupt_flag_.end() &&
4733  flag_it->second;
4734 }
4735 
4737  const QuerySessionId& query_session,
4739  if (query_session.empty()) {
4740  return false;
4741  }
4742  return !query_session.empty() && queries_session_map_.count(query_session);
4743 }
4744 
4746  const double runtime_query_check_freq,
4747  const unsigned pending_query_check_freq) const {
4748  // The only one scenario that we intentionally call this function is
4749  // to allow runtime query interrupt in QueryRunner for test cases.
4750  // Because test machine's default setting does not allow runtime query interrupt,
4751  // so we have to turn it on within test code if necessary.
4753  g_pending_query_interrupt_freq = pending_query_check_freq;
4754  g_running_query_interrupt_freq = runtime_query_check_freq;
4757  }
4758 }
4759 
4760 void Executor::addToCardinalityCache(const std::string& cache_key,
4761  const size_t cache_value) {
4764  cardinality_cache_[cache_key] = cache_value;
4765  VLOG(1) << "Put estimated cardinality to the cache";
4766  }
4767 }
4768 
4772  cardinality_cache_.find(cache_key) != cardinality_cache_.end()) {
4773  VLOG(1) << "Reuse cached cardinality";
4774  return {true, cardinality_cache_[cache_key]};
4775  }
4776  return {false, -1};
4777 }
4778 
4779 std::vector<QuerySessionStatus> Executor::getQuerySessionInfo(
4780  const QuerySessionId& query_session,
4782  if (!queries_session_map_.empty() && queries_session_map_.count(query_session)) {
4783  auto& query_infos = queries_session_map_.at(query_session);
4784  std::vector<QuerySessionStatus> ret;
4785  for (auto& info : query_infos) {
4786  ret.push_back(QuerySessionStatus(query_session,
4787  info.second.getExecutorId(),
4788  info.second.getQueryStr(),
4789  info.second.getQuerySubmittedTime(),
4790  info.second.getQueryStatus()));
4791  }
4792  return ret;
4793  }
4794  return {};
4795 }
4796 
4797 const std::vector<size_t> Executor::getExecutorIdsRunningQuery(
4798  const QuerySessionId& interrupt_session) const {
4799  std::vector<size_t> res;
4801  auto it = queries_session_map_.find(interrupt_session);
4802  if (it != queries_session_map_.end()) {
4803  for (auto& kv : it->second) {
4804  if (kv.second.getQueryStatus() ==
4805  QuerySessionStatus::QueryStatus::RUNNING_QUERY_KERNEL) {
4806  res.push_back(kv.second.getExecutorId());
4807  }
4808  }
4809  }
4810  return res;
4811 }
4812 
4814  // this function should be called within an executor which is assigned
4815  // to the specific query thread (that indicates we already enroll the session)
4816  // check whether this is called from non unitary executor
4818  return false;
4819  };
4821  auto flag_it = queries_interrupt_flag_.find(current_query_session_);
4822  return !current_query_session_.empty() && flag_it != queries_interrupt_flag_.end() &&
4823  flag_it->second;
4824 }
4825 
4827  // this function is called under the recycler lock
4828  // e.g., QueryPlanDagExtractor::extractQueryPlanDagImpl()
4829  latest_query_plan_extracted_ = query_plan_dag;
4830 }
4831 
4835 }
4836 
4837 std::map<int, std::shared_ptr<Executor>> Executor::executors_;
4838 
4839 // contain the interrupt flag's status per query session
4841 // contain a list of queries per query session
4843 // session lock
4845 
4848 
4852 
4854 std::mutex Executor::kernel_mutex_;
4855 
4858 std::unordered_map<std::string, size_t> Executor::cardinality_cache_;
4859 // Executor has a single global result set recycler holder
4860 // which contains two recyclers related to query resultset
4863 
4864 // Useful for debugging.
4865 std::string Executor::dumpCache() const {
4866  std::stringstream ss;
4867  ss << "colRangeCache: ";
4868  for (auto& [phys_input, exp_range] : agg_col_range_cache_.asMap()) {
4869  ss << "{" << phys_input.col_id << ", " << phys_input.table_id
4870  << "} = " << exp_range.toString() << ", ";
4871  }
4872  ss << "stringDictGenerations: ";
4873  for (auto& [key, val] : row_set_mem_owner_->getStringDictionaryGenerations().asMap()) {
4874  ss << "{" << key << "} = " << val << ", ";
4875  }
4876  ss << "tableGenerations: ";
4877  for (auto& [key, val] : table_generations_.asMap()) {
4878  ss << "{" << key << "} = {" << val.tuple_count << ", " << val.start_rowid << "}, ";
4879  }
4880  ss << "\n";
4881  return ss.str();
4882 }
int get_table_id() const
Definition: Analyzer.h:201
const TableGeneration & getGeneration(const uint32_t id) const
CudaMgr_Namespace::CudaMgr * getCudaMgr() const
Definition: DataMgr.h:224
void executeWorkUnitPerFragment(const RelAlgExecutionUnit &ra_exe_unit, const InputTableInfo &table_info, const CompilationOptions &co, const ExecutionOptions &eo, const Catalog_Namespace::Catalog &cat, PerFragmentCallBack &cb, const std::set< size_t > &fragment_indexes_param)
Compiles and dispatches a work unit per fragment processing results with the per fragment callback...
Definition: Execute.cpp:2001
bool is_agg(const Analyzer::Expr *expr)
catalog_(nullptr)
std::vector< Analyzer::Expr * > target_exprs
AggregatedColRange computeColRangesCache(const std::unordered_set< PhysicalInput > &phys_inputs)
Definition: Execute.cpp:4367
void enableRuntimeQueryInterrupt(const double runtime_query_check_freq, const unsigned pending_query_check_freq) const
Definition: Execute.cpp:4745
constexpr size_t kArenaBlockOverhead
SQLAgg
Definition: sqldefs.h:72
#define CHECK_EQ(x, y)
Definition: Logger.h:230
const QueryPlanDAG getLatestQueryPlanDagExtracted() const
Definition: Execute.cpp:4832
std::vector< std::unique_ptr< ExecutionKernel > > createKernels(SharedKernelContext &shared_context, const RelAlgExecutionUnit &ra_exe_unit, ColumnFetcher &column_fetcher, const std::vector< InputTableInfo > &table_infos, const ExecutionOptions &eo, const bool is_agg, const bool allow_single_frag_table_opt, const size_t context_count, const QueryCompilationDescriptor &query_comp_desc, const QueryMemoryDescriptor &query_mem_desc, RenderInfo *render_info, std::unordered_set< int > &available_gpus, int &available_cpus)
Definition: Execute.cpp:2538
std::vector< int > ChunkKey
Definition: types.h:36
double g_running_query_interrupt_freq
Definition: Execute.cpp:129
ExtModuleKinds
Definition: Execute.h:469
robin_hood::unordered_set< int64_t > CountDistinctSet
Definition: CountDistinct.h:35
void reduce(SpeculativeTopNMap &that)
static heavyai::shared_mutex execute_mutex_
Definition: Execute.h:1351
const ColumnDescriptor * try_get_column_descriptor(const InputColDescriptor *col_desc, const Catalog_Namespace::Catalog &cat)
Definition: Execute.cpp:2829
static QuerySessionMap queries_session_map_
Definition: Execute.h:1346
CudaMgr_Namespace::CudaMgr * cudaMgr() const
Definition: Execute.h:714
int32_t executePlanWithGroupBy(const RelAlgExecutionUnit &ra_exe_unit, const CompilationResult &, const bool hoist_literals, ResultSetPtr *results, const ExecutorDeviceType device_type, std::vector< std::vector< const int8_t * >> &col_buffers, const std::vector< size_t > outer_tab_frag_ids, QueryExecutionContext *, const std::vector< std::vector< int64_t >> &num_rows, const std::vector< std::vector< uint64_t >> &frag_offsets, Data_Namespace::DataMgr *, const int device_id, const int outer_table_id, const int64_t limit, const uint32_t start_rowid, const uint32_t num_tables, const bool allow_runtime_interrupt, RenderInfo *render_info, const int64_t rows_to_process=-1)
Definition: Execute.cpp:3550
bool checkIsQuerySessionInterrupted(const std::string &query_session, heavyai::shared_lock< heavyai::shared_mutex > &read_lock)
Definition: Execute.cpp:4725
int64_t kernel_queue_time_ms_
Definition: Execute.h:1328
JoinType
Definition: sqldefs.h:157
size_t maxGpuSlabSize() const
Definition: Execute.cpp:3876
HOST DEVICE int get_size() const
Definition: sqltypes.h:389
bool useCudaBuffers() const
Definition: RenderInfo.cpp:53
Fragmenter_Namespace::TableInfo info
Definition: InputMetadata.h:35
Data_Namespace::DataMgr * data_mgr_
Definition: Execute.h:1324
int32_t getErrorCode() const
Definition: ErrorHandling.h:55
ExecutorDeviceType getDeviceType() const
int64_t compilation_queue_time_ms_
Definition: Execute.h:1329
std::string cat(Ts &&...args)
size_t g_cpu_sub_task_size
Definition: Execute.cpp:83
ResultSetPtr get_merged_result(std::vector< std::pair< ResultSetPtr, std::vector< size_t >>> &results_per_device, std::vector< TargetInfo > const &targets)
Definition: Execute.cpp:1267
block_size_x_(block_size_x)
static void initialize_extension_module_sources()
Definition: Execute.cpp:268
const StringDictionaryProxy::IdMap * getOrAddStringProxyTranslationMap(const int source_dict_id_in, const int dest_dict_id_in, const bool with_generation, const StringTranslationType translation_map_type, const std::vector< StringOps_Namespace::StringOpInfo > &string_op_infos, const Catalog_Namespace::Catalog *catalog)
Definition: Execute.cpp:617
void checkPendingQueryStatus(const QuerySessionId &query_session)
Definition: Execute.cpp:4506
const StringDictionaryProxy::IdMap * 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_source_string_op_infos, std::shared_ptr< RowSetMemoryOwner > row_set_mem_owner) const
Definition: Execute.cpp:586
std::string ra_exec_unit_desc_for_caching(const RelAlgExecutionUnit &ra_exe_unit)
Definition: Execute.cpp:1640
static const int32_t ERR_INTERRUPTED
Definition: Execute.h:1388
class for a per-database catalog. also includes metadata for the current database and the current use...
Definition: Catalog.h:132
Definition: sqltypes.h:64
std::vector< int8_t * > getJoinHashTablePtrs(const ExecutorDeviceType device_type, const int device_id)
Definition: Execute.cpp:3738
void setEntryCount(const size_t val)
input_table_info_cache_(this)
bool is_trivial_loop_join(const std::vector< InputTableInfo > &query_infos, const RelAlgExecutionUnit &ra_exe_unit)
Definition: Execute.cpp:1578
heavyai::shared_lock< heavyai::shared_mutex > read_lock
grid_size_x_(grid_size_x)
void set_mod_range(std::vector< int8_t const * > &frag_col_buffers, int8_t const *const ptr, size_t const local_col_id, size_t const N)
Definition: Execute.cpp:3120
const std::vector< uint64_t > & getFragOffsets()
boost::multiprecision::number< boost::multiprecision::cpp_int_backend< 64, 64, boost::multiprecision::signed_magnitude, boost::multiprecision::checked, void >> checked_int64_t
const std::shared_ptr< RowSetMemoryOwner > getRowSetMemoryOwner() const
Definition: Execute.cpp:684
std::atomic< bool > interrupted_
Definition: Execute.h:1308
static ResultSetRecyclerHolder resultset_recycler_holder_
Definition: Execute.h:1373
std::vector< size_t > getTableFragmentIndices(const RelAlgExecutionUnit &ra_exe_unit, const ExecutorDeviceType device_type, const size_t table_idx, const size_t outer_frag_idx, std::map< int, const TableFragments * > &selected_tables_fragments, const std::unordered_map< int, const Analyzer::BinOper * > &inner_table_id_to_join_condition)
Definition: Execute.cpp:2724
std::tuple< bool, int64_t, int64_t > get_hpt_overflow_underflow_safe_scaled_values(const int64_t chunk_min, const int64_t chunk_max, const SQLTypeInfo &lhs_type, const SQLTypeInfo &rhs_type)
Definition: Execute.cpp:4002
ExecutorDeviceType
ResultSetPtr executeTableFunction(const TableFunctionExecutionUnit exe_unit, const std::vector< InputTableInfo > &table_infos, const CompilationOptions &co, const ExecutionOptions &eo, const Catalog_Namespace::Catalog &cat)
Compiles and dispatches a table function; that is, a function that takes as input one or more columns...
Definition: Execute.cpp:2081
std::string get_root_abs_path()
std::string toString() const
QueryPlanHash query_plan_dag_hash
Data_Namespace::DataMgr & getDataMgr() const
Definition: Catalog.h:243
double extract_max_stat_fp_type(const ChunkStats &stats, const SQLTypeInfo &ti)
static const int max_gpu_count
Definition: Execute.h:1301
GpuSharedMemoryContext gpu_smem_context
OutVecOwner(const std::vector< int64_t * > &out_vec)
Definition: Execute.cpp:3317
const std::optional< bool > union_all
unsigned g_pending_query_interrupt_freq
Definition: Execute.cpp:128
int64_t float_to_double_bin(int32_t val, bool nullable=false)
const table_functions::TableFunction table_func
std::map< const QuerySessionId, std::map< std::string, QuerySessionStatus >> QuerySessionMap
Definition: Execute.h:153
#define LOG(tag)
Definition: Logger.h:216
void freeLinearizedBuf()
std::string QueryPlanDAG
std::vector< size_t > outer_fragment_indices
bool isArchPascalOrLater(const ExecutorDeviceType dt) const
Definition: Execute.h:721
std::ostream & operator<<(std::ostream &os, const SessionInfo &session_info)
Definition: SessionInfo.cpp:57
static std::pair< std::vector< InnerOuter >, std::vector< InnerOuterStringOpInfos > > normalizeColumnPairs(const Analyzer::BinOper *condition, const Catalog_Namespace::Catalog &cat, const TemporaryTables *temporary_tables)
Definition: HashJoin.cpp:991
bool is_fp() const
Definition: sqltypes.h:579
HOST DEVICE int get_scale() const
Definition: sqltypes.h:384
Cache for physical column ranges. Set by the aggregator on the leaves.
std::pair< QuerySessionId, std::string > CurrentQueryStatus
Definition: Execute.h:85
Definition: sqldefs.h:34
const std::list< Analyzer::OrderEntry > order_entries
void prepare_string_dictionaries(const std::unordered_set< PhysicalInput > &phys_inputs, const Catalog_Namespace::Catalog &catalog)
Definition: Execute.cpp:188
size_t getSharedMemorySize() const
std::vector< ColumnLazyFetchInfo > getColLazyFetchInfo(const std::vector< Analyzer::Expr * > &target_exprs) const
Definition: Execute.cpp:747
void updateQuerySessionStatus(const QuerySessionId &query_session, const std::string &submitted_time_str, const QuerySessionStatus::QueryStatus new_query_status)
Definition: Execute.cpp:4546
void clearMemory(const MemoryLevel memLevel)
Definition: DataMgr.cpp:434
Definition: sqldefs.h:35
std::unordered_set< int > get_available_gpus(const Data_Namespace::DataMgr *data_mgr)
Definition: Execute.cpp:1456
std::vector< int64_t * > launchCpuCode(const RelAlgExecutionUnit &ra_exe_unit, const CpuCompilationContext *fn_ptrs, const bool hoist_literals, const std::vector< int8_t > &literal_buff, std::vector< std::vector< const int8_t * >> col_buffers, const std::vector< std::vector< int64_t >> &num_rows, const std::vector< std::vector< uint64_t >> &frag_row_offsets, const int32_t scan_limit, int32_t *error_code, const uint32_t num_tables, const std::vector< int8_t * > &join_hash_tables, const int64_t num_rows_to_process=-1)
std::string join(T const &container, std::string const &delim)
std::tuple< RelAlgExecutionUnit, PlanState::DeletedColumnsMap > addDeletedColumn(const RelAlgExecutionUnit &ra_exe_unit, const CompilationOptions &co)
Definition: Execute.cpp:3958
TableGenerations computeTableGenerations(std::unordered_set< int > phys_table_ids)
Definition: Execute.cpp:4418
void addDeviceResults(ResultSetPtr &&device_results, std::vector< size_t > outer_table_fragment_ids)
std::vector< InputDescriptor > input_descs
bool hasLazyFetchColumns(const std::vector< Analyzer::Expr * > &target_exprs) const
Definition: Execute.cpp:736
#define UNREACHABLE()
Definition: Logger.h:266
void setOutputColumnar(const bool val)
const SortAlgorithm algorithm
bool use_speculative_top_n(const RelAlgExecutionUnit &ra_exe_unit, const QueryMemoryDescriptor &query_mem_desc)
DEVICE void sort(ARGS &&...args)
Definition: gpu_enabled.h:105
std::unique_ptr< llvm::Module > read_llvm_module_from_ir_string(const std::string &udf_ir_string, llvm::LLVMContext &ctx, bool is_gpu=false)
bool is_empty_table(Fragmenter_Namespace::AbstractFragmenter *fragmenter)
Definition: Execute.cpp:195
std::optional< size_t > first_dict_encoded_idx(std::vector< TargetInfo > const &)
Definition: ResultSet.cpp:1475
ExpressionRange getColRange(const PhysicalInput &) const
debug_dir_(debug_dir)
#define CHECK_GE(x, y)
Definition: Logger.h:235
const int8_t * getResultSetColumn(const InputColDescriptor *col_desc, const Data_Namespace::MemoryLevel memory_level, const int device_id, DeviceAllocator *device_allocator, const size_t thread_idx) const
static std::pair< int64_t, int32_t > reduceResults(const SQLAgg agg, const SQLTypeInfo &ti, const int64_t agg_init_val, const int8_t out_byte_width, const int64_t *out_vec, const size_t out_vec_sz, const bool is_group_by, const bool float_argument_input)
Definition: Execute.cpp:1071
TypeR::rep timer_stop(Type clock_begin)
Definition: measure.h:48
Definition: sqldefs.h:48
Definition: sqldefs.h:29
Functions to support geospatial operations used by the executor.
const StringDictionaryProxy::TranslationMap< Datum > * getStringProxyNumericTranslationMap(const int source_dict_id, const std::vector< StringOps_Namespace::StringOpInfo > &string_op_infos, std::shared_ptr< RowSetMemoryOwner > row_set_mem_owner, const bool with_generation) const
Definition: Execute.cpp:605
QuerySessionId current_query_session_
Definition: Execute.h:1342
#define DEBUG_TIMER_NEW_THREAD(parent_thread_id)
Definition: Logger.h:376
int32_t executePlanWithoutGroupBy(const RelAlgExecutionUnit &ra_exe_unit, const CompilationResult &, const bool hoist_literals, ResultSetPtr *results, const std::vector< Analyzer::Expr * > &target_exprs, const ExecutorDeviceType device_type, std::vector< std::vector< const int8_t * >> &col_buffers, QueryExecutionContext *query_exe_context, const std::vector< std::vector< int64_t >> &num_rows, const std::vector< std::vector< uint64_t >> &frag_offsets, Data_Namespace::DataMgr *data_mgr, const int device_id, const uint32_t start_rowid, const uint32_t num_tables, const bool allow_runtime_interrupt, RenderInfo *render_info, const int64_t rows_to_process=-1)
Definition: Execute.cpp:3329
heavyai::shared_mutex & getSessionLock()
Definition: Execute.cpp:4453
static const int32_t ERR_GEOS
Definition: Execute.h:1394
const int8_t * linearizeColumnFragments(const int table_id, const int col_id, const std::map< int, const TableFragments * > &all_tables_fragments, std::list< std::shared_ptr< Chunk_NS::Chunk >> &chunk_holder, std::list< ChunkIter > &chunk_iter_holder, const Data_Namespace::MemoryLevel memory_level, const int device_id, DeviceAllocator *device_allocator, const size_t thread_idx) const
AggregatedColRange agg_col_range_cache_
Definition: Execute.h:1338
std::shared_ptr< ResultSet > ResultSetPtr
static void * gpu_active_modules_[max_gpu_count]
Definition: Execute.h:1306
heavyai::unique_lock< heavyai::shared_mutex > write_lock
std::vector< FragmentInfo > fragments
Definition: Fragmenter.h:171
std::unique_ptr< CgenState > cgen_state_
Definition: Execute.h:1268
void fill_entries_for_empty_input(std::vector< TargetInfo > &target_infos, std::vector< int64_t > &entry, const std::vector< Analyzer::Expr * > &target_exprs, const QueryMemoryDescriptor &query_mem_desc)
Definition: Execute.cpp:2250
std::string toString(const QueryDescriptionType &type)
Definition: Types.h:64
ExecutorOptLevel opt_level
bool g_enable_dynamic_watchdog
Definition: Execute.cpp:80
void enrollQuerySession(const QuerySessionId &query_session, const std::string &query_str, const std::string &submitted_time_str, const size_t executor_id, const QuerySessionStatus::QueryStatus query_session_status)
Definition: Execute.cpp:4562
size_t compute_buffer_entry_guess(const std::vector< InputTableInfo > &query_infos)
Definition: Execute.cpp:1482
T visit(const Analyzer::Expr *expr) const
const std::list< std::shared_ptr< Analyzer::Expr > > groupby_exprs
bool takes_float_argument(const TargetInfo &target_info)
Definition: TargetInfo.h:111
unsigned g_trivial_loop_join_threshold
Definition: Execute.cpp:89
static uint32_t gpu_active_modules_device_mask_
Definition: Execute.h:1305
void launchKernels(SharedKernelContext &shared_context, std::vector< std::unique_ptr< ExecutionKernel >> &&kernels, const ExecutorDeviceType device_type)
Definition: Execute.cpp:2672
HOST DEVICE SQLTypes get_type() const
Definition: sqltypes.h:379
FragmentSkipStatus canSkipFragmentForFpQual(const Analyzer::BinOper *comp_expr, const Analyzer::ColumnVar *lhs_col, const Fragmenter_Namespace::FragmentInfo &fragment, const Analyzer::Constant *rhs_const) const
Definition: Execute.cpp:4070
static void invalidateCaches()
int deviceCount(const ExecutorDeviceType) const
Definition: Execute.cpp:1056
quantile::TDigest * nullTDigest(double const q)
Definition: Execute.cpp:646
llvm::Value * castToIntPtrTyIn(llvm::Value *val, const size_t bit_width)
Definition: Execute.cpp:3912
size_t getNumBytesForFetchedRow(const std::set< int > &table_ids_to_fetch) const
Definition: Execute.cpp:704
void reset(bool discard_runtime_modules_only=false)
Definition: Execute.cpp:297
QualsConjunctiveForm qual_to_conjunctive_form(const std::shared_ptr< Analyzer::Expr > qual_expr)
static std::mutex kernel_mutex_
Definition: Execute.h:1415
bool g_is_test_env
Definition: Execute.cpp:141
unsigned numBlocksPerMP() const
Definition: Execute.cpp:3845
llvm::Type * get_int_type(const int width, llvm::LLVMContext &context)
bool is_number() const
Definition: sqltypes.h:580
#define CHECK_GT(x, y)
Definition: Logger.h:234
Container for compilation results and assorted options for a single execution unit.
bool isCPUOnly() const
Definition: Execute.cpp:654
void resetGridSize()
Definition: Execute.cpp:3864
bool checkCurrentQuerySession(const std::string &candidate_query_session, heavyai::shared_lock< heavyai::shared_mutex > &read_lock)
Definition: Execute.cpp:4462
double inline_fp_null_val(const SQL_TYPE_INFO &ti)
void addTransientStringLiterals(const RelAlgExecutionUnit &ra_exe_unit, const std::shared_ptr< RowSetMemoryOwner > &row_set_mem_owner)
Definition: Execute.cpp:2163
size_t permute_storage_row_wise(const ResultSetStorage *input_storage, const ResultSetStorage *output_storage, size_t output_row_index, const QueryMemoryDescriptor &output_query_mem_desc, const std::vector< uint32_t > &top_permutation)
Definition: Execute.cpp:2441
std::vector< FragmentsPerTable > FragmentsList
int64_t extract_max_stat_int_type(const ChunkStats &stats, const SQLTypeInfo &ti)
bool is_time() const
Definition: sqltypes.h:581
bool needFetchAllFragments(const InputColDescriptor &col_desc, const RelAlgExecutionUnit &ra_exe_unit, const FragmentsList &selected_fragments) const
Definition: Execute.cpp:2906
TargetInfo get_target_info(const Analyzer::Expr *target_expr, const bool bigint_count)
Definition: TargetInfo.h:97
RUNTIME_EXPORT void agg_sum_float_skip_val(int32_t *agg, const float val, const float skip_val)
std::string to_string(char const *&&v)
static size_t literalBytes(const CgenState::LiteralValue &lit)
Definition: CgenState.h:474
bool updateQuerySessionStatusWithLock(const QuerySessionId &query_session, const std::string &submitted_time_str, const QuerySessionStatus::QueryStatus updated_query_status, heavyai::unique_lock< heavyai::shared_mutex > &write_lock)
Definition: Execute.cpp:4629
const StringDictionaryProxy::IdMap * getStringProxyTranslationMap(const int source_dict_id, const int dest_dict_id, 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
Definition: Execute.cpp:567
bool g_enable_overlaps_hashjoin
Definition: Execute.cpp:102
bool checkNonKernelTimeInterrupted() const
Definition: Execute.cpp:4813
static void clearMemory(const Data_Namespace::MemoryLevel memory_level)
Definition: Execute.cpp:501
int8_t * getUnderlyingBuffer() const
bool g_inner_join_fragment_skipping
Definition: Execute.cpp:91
bool removeFromQuerySessionList(const QuerySessionId &query_session, const std::string &submitted_time_str, heavyai::unique_lock< heavyai::shared_mutex > &write_lock)
Definition: Execute.cpp:4680
std::vector< Analyzer::Expr * > target_exprs_union
void populate_string_dictionary(const int32_t table_id, const int32_t col_id, const Catalog_Namespace::Catalog &catalog)
Definition: Execute.cpp:205
const int8_t * getOneTableColumnFragment(const int table_id, const int frag_id, const int col_id, const std::map< int, const TableFragments * > &all_tables_fragments, std::list< std::shared_ptr< Chunk_NS::Chunk >> &chunk_holder, std::list< ChunkIter > &chunk_iter_holder, const Data_Namespace::MemoryLevel memory_level, const int device_id, DeviceAllocator *device_allocator) const
Fragmenter_Namespace::TableInfo getTableInfo(const int table_id) const
Definition: Execute.cpp:692
constexpr double a
Definition: Utm.h:32
bool g_enable_string_functions
static const size_t high_scan_limit
Definition: Execute.h:608
Definition: sqldefs.h:74
std::shared_lock< T > shared_lock
std::unique_ptr< QueryMemoryInitializer > query_buffers_
size_t g_watchdog_none_encoded_string_translation_limit
Definition: Execute.cpp:81
static std::shared_ptr< Executor > getExecutor(const ExecutorId id, const std::string &debug_dir="", const std::string &debug_file="", const SystemParameters &system_parameters=SystemParameters())
Definition: Execute.cpp:477
void preloadFragOffsets(const std::vector< InputDescriptor > &input_descs, const std::vector< InputTableInfo > &query_infos)
Definition: Execute.cpp:3773
std::map< int, std::shared_ptr< ChunkMetadata >> ChunkMetadataMap
bool isFragmentFullyDeleted(const int table_id, const Fragmenter_Namespace::FragmentInfo &fragment)
Definition: Execute.cpp:4037
SQLOps get_optype() const
Definition: Analyzer.h:447
std::unordered_map< int, const ResultSetPtr & > TemporaryTables
Definition: InputMetadata.h:31
FetchResult fetchUnionChunks(const ColumnFetcher &, const RelAlgExecutionUnit &ra_exe_unit, const int device_id, const Data_Namespace::MemoryLevel, const std::map< int, const TableFragments * > &, const FragmentsList &selected_fragments, const Catalog_Namespace::Catalog &, std::list< ChunkIter > &, std::list< std::shared_ptr< Chunk_NS::Chunk >> &, DeviceAllocator *device_allocator, const size_t thread_idx, const bool allow_runtime_interrupt)
Definition: Execute.cpp:3135
This file contains the class specification and related data structures for Catalog.
static const int32_t ERR_STREAMING_TOP_N_NOT_SUPPORTED_IN_RENDER_QUERY
Definition: Execute.h:1392
const ExecutorId executor_id_
Definition: Execute.h:1242
Data_Namespace::DataMgr & getDataMgr() const
Definition: SysCatalog.h:232
bool updateQuerySessionExecutorAssignment(const QuerySessionId &query_session, const std::string &submitted_time_str, const size_t executor_id, heavyai::unique_lock< heavyai::shared_mutex > &write_lock)
Definition: Execute.cpp:4655
int8_t warpSize() const
Definition: Execute.cpp:3828
RUNTIME_EXPORT void agg_sum_double_skip_val(int64_t *agg, const double val, const double skip_val)
std::map< QuerySessionId, bool > InterruptFlagMap
Definition: Execute.h:86
const size_t limit
const size_t max_gpu_slab_size_
Definition: Execute.h:1319
TargetInfo operator()(Analyzer::Expr const *const target_expr) const
Definition: Execute.cpp:1288
ResultSetPtr reduceSpeculativeTopN(const RelAlgExecutionUnit &, std::vector< std::pair< ResultSetPtr, std::vector< size_t >>> &all_fragment_results, std::shared_ptr< RowSetMemoryOwner >, const QueryMemoryDescriptor &) const
Definition: Execute.cpp:1429
std::string get_cuda_home(void)
Definition: CudaMgr.cpp:465
ResultSetPtr collectAllDeviceResults(SharedKernelContext &shared_context, const RelAlgExecutionUnit &ra_exe_unit, const QueryMemoryDescriptor &query_mem_desc, const ExecutorDeviceType device_type, std::shared_ptr< RowSetMemoryOwner > row_set_mem_owner)
Definition: Execute.cpp:2347
const ColumnDescriptor * getPhysicalColumnDescriptor(const Analyzer::ColumnVar *, int) const
Definition: Execute.cpp:665
int8_t groupColWidth(const size_t key_idx) const