OmniSciDB  c0231cc57d
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
PerfectJoinHashTable.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 
18 
19 #include <atomic>
20 #include <future>
21 #include <numeric>
22 #include <thread>
23 
24 #include "Logger/Logger.h"
27 #include "QueryEngine/Execute.h"
32 
33 // let's only consider CPU hahstable recycler at this moment
34 std::unique_ptr<HashtableRecycler> PerfectJoinHashTable::hash_table_cache_ =
35  std::make_unique<HashtableRecycler>(CacheItemType::PERFECT_HT,
37 std::unique_ptr<HashingSchemeRecycler> PerfectJoinHashTable::hash_table_layout_cache_ =
38  std::make_unique<HashingSchemeRecycler>();
39 
40 namespace {
41 std::pair<InnerOuter, InnerOuterStringOpInfos> get_cols(
42  const Analyzer::BinOper* qual_bin_oper,
44  const TemporaryTables* temporary_tables) {
45  const auto lhs = qual_bin_oper->get_left_operand();
46  const auto rhs = qual_bin_oper->get_right_operand();
47  return HashJoin::normalizeColumnPair(lhs, rhs, cat, temporary_tables);
48 }
49 
51  ExpressionRange const& col_range,
52  bool const is_bw_eq) {
53  using EmptyRangeSize = boost::optional<size_t>;
54  auto empty_range_check = [](ExpressionRange const& col_range,
55  bool const is_bw_eq) -> EmptyRangeSize {
56  if (col_range.getIntMin() > col_range.getIntMax()) {
57  CHECK_EQ(col_range.getIntMin(), int64_t(0));
58  CHECK_EQ(col_range.getIntMax(), int64_t(-1));
59  if (is_bw_eq) {
60  return size_t(1);
61  }
62  return size_t(0);
63  }
64  return EmptyRangeSize{};
65  };
66 
67  auto empty_range = empty_range_check(col_range, is_bw_eq);
68  if (empty_range) {
69  return {size_t(*empty_range), 1};
70  }
71 
72  int64_t bucket_normalization =
73  context_ti.get_type() == kDATE ? col_range.getBucket() : 1;
74  CHECK_GT(bucket_normalization, 0);
75  return {size_t(col_range.getIntMax() - col_range.getIntMin() + 1 + (is_bw_eq ? 1 : 0)),
76  bucket_normalization};
77 }
78 
79 size_t get_hash_entry_count(const ExpressionRange& col_range, const bool is_bw_eq) {
80  if (col_range.getIntMin() > col_range.getIntMax()) {
81  CHECK_EQ(col_range.getIntMin(), int64_t(0));
82  CHECK_EQ(col_range.getIntMax(), int64_t(-1));
83  return is_bw_eq ? 1 : 0;
84  }
85  return col_range.getIntMax() - col_range.getIntMin() + 1 + (is_bw_eq ? 1 : 0);
86 }
87 
88 } // namespace
89 
90 namespace {
91 
92 bool shard_count_less_or_equal_device_count(const int inner_table_id,
93  const Executor* executor) {
94  const auto inner_table_info = executor->getTableInfo(inner_table_id);
95  std::unordered_set<int> device_holding_fragments;
96  auto cuda_mgr = executor->getDataMgr()->getCudaMgr();
97  const int device_count = cuda_mgr ? cuda_mgr->getDeviceCount() : 1;
98  for (const auto& fragment : inner_table_info.fragments) {
99  if (fragment.shard != -1) {
100  const auto it_ok = device_holding_fragments.emplace(fragment.shard % device_count);
101  if (!it_ok.second) {
102  return false;
103  }
104  }
105  }
106  return true;
107 }
108 
109 } // namespace
110 
112  std::pair<const Analyzer::ColumnVar*, const Analyzer::Expr*> equi_pair,
113  const Executor* executor) {
114  const auto inner_col = equi_pair.first;
115  const auto outer_col = dynamic_cast<const Analyzer::ColumnVar*>(equi_pair.second);
116  if (!outer_col || inner_col->get_table_id() < 0 || outer_col->get_table_id() < 0) {
117  return 0;
118  }
119  if (outer_col->get_rte_idx()) {
120  return 0;
121  }
122  if (inner_col->get_type_info() != outer_col->get_type_info()) {
123  return 0;
124  }
125  const auto catalog = executor->getCatalog();
126  const auto inner_td = catalog->getMetadataForTable(inner_col->get_table_id());
127  CHECK(inner_td);
128  const auto outer_td = catalog->getMetadataForTable(outer_col->get_table_id());
129  CHECK(outer_td);
130  if (inner_td->shardedColumnId == 0 || outer_td->shardedColumnId == 0 ||
131  inner_td->nShards != outer_td->nShards) {
132  return 0;
133  }
134  if (!shard_count_less_or_equal_device_count(inner_td->tableId, executor)) {
135  return 0;
136  }
137  // The two columns involved must be the ones on which the tables have been sharded on.
138  return (inner_td->shardedColumnId == inner_col->get_column_id() &&
139  outer_td->shardedColumnId == outer_col->get_column_id()) ||
140  (outer_td->shardedColumnId == inner_col->get_column_id() &&
141  inner_td->shardedColumnId == inner_col->get_column_id())
142  ? inner_td->nShards
143  : 0;
144 }
145 
147 std::shared_ptr<PerfectJoinHashTable> PerfectJoinHashTable::getInstance(
148  const std::shared_ptr<Analyzer::BinOper> qual_bin_oper,
149  const std::vector<InputTableInfo>& query_infos,
150  const Data_Namespace::MemoryLevel memory_level,
151  const JoinType join_type,
152  const HashType preferred_hash_type,
153  const int device_count,
154  ColumnCacheMap& column_cache,
155  Executor* executor,
156  const HashTableBuildDagMap& hashtable_build_dag_map,
157  const TableIdToNodeMap& table_id_to_node_map) {
158  CHECK(IS_EQUIVALENCE(qual_bin_oper->get_optype()));
159  const auto cols_and_string_op_infos =
160  get_cols(qual_bin_oper.get(), *executor->getCatalog(), executor->temporary_tables_);
161  const auto& cols = cols_and_string_op_infos.first;
162  const auto& inner_outer_string_op_infos = cols_and_string_op_infos.second;
163  const auto inner_col = cols.first;
164  CHECK(inner_col);
165  const auto& ti = inner_col->get_type_info();
166  auto col_range =
167  getExpressionRange(ti.is_string() ? cols.second : inner_col, query_infos, executor);
168  if (col_range.getType() == ExpressionRangeType::Invalid) {
169  throw HashJoinFail(
170  "Could not compute range for the expressions involved in the equijoin");
171  }
172  const auto rhs_source_col_range =
173  ti.is_string() ? getExpressionRange(inner_col, query_infos, executor) : col_range;
174  if (ti.is_string()) {
175  // The nullable info must be the same as the source column.
176  if (rhs_source_col_range.getType() == ExpressionRangeType::Invalid) {
177  throw HashJoinFail(
178  "Could not compute range for the expressions involved in the equijoin");
179  }
180  if (rhs_source_col_range.getIntMin() > rhs_source_col_range.getIntMax()) {
181  // If the inner column expression range is empty, use the inner col range
182  CHECK_EQ(rhs_source_col_range.getIntMin(), int64_t(0));
183  CHECK_EQ(rhs_source_col_range.getIntMax(), int64_t(-1));
184  col_range = rhs_source_col_range;
185  } else {
186  col_range = ExpressionRange::makeIntRange(
187  std::min(rhs_source_col_range.getIntMin(), col_range.getIntMin()),
188  std::max(rhs_source_col_range.getIntMax(), col_range.getIntMax()),
189  0,
190  rhs_source_col_range.hasNulls());
191  }
192  }
193 
194  // We can't allocate more than 2GB contiguous memory on GPU and each entry is 4 bytes.
195  const auto max_hash_entry_count =
197  ? static_cast<size_t>(std::numeric_limits<int32_t>::max() / sizeof(int32_t))
198  : static_cast<size_t>(std::numeric_limits<int32_t>::max());
199 
200  auto bucketized_entry_count_info = get_bucketized_hash_entry_info(
201  ti, col_range, qual_bin_oper->get_optype() == kBW_EQ);
202  auto bucketized_entry_count = bucketized_entry_count_info.getNormalizedHashEntryCount();
203 
204  if (bucketized_entry_count > max_hash_entry_count) {
205  throw TooManyHashEntries();
206  }
207 
208  if (qual_bin_oper->get_optype() == kBW_EQ &&
209  col_range.getIntMax() >= std::numeric_limits<int64_t>::max()) {
210  throw HashJoinFail("Cannot translate null value for kBW_EQ");
211  }
212  decltype(std::chrono::steady_clock::now()) ts1, ts2;
213  if (VLOGGING(1)) {
214  ts1 = std::chrono::steady_clock::now();
215  }
216 
217  auto join_hash_table = std::shared_ptr<PerfectJoinHashTable>(
218  new PerfectJoinHashTable(qual_bin_oper,
219  inner_col,
220  query_infos,
221  memory_level,
222  join_type,
223  preferred_hash_type,
224  col_range,
225  rhs_source_col_range,
226  column_cache,
227  executor,
228  device_count,
229  hashtable_build_dag_map,
230  table_id_to_node_map,
231  inner_outer_string_op_infos));
232  try {
233  join_hash_table->reify();
234  } catch (const TableMustBeReplicated& e) {
235  // Throw a runtime error to abort the query
236  join_hash_table->freeHashBufferMemory();
237  throw std::runtime_error(e.what());
238  } catch (const HashJoinFail& e) {
239  // HashJoinFail exceptions log an error and trigger a retry with a join loop (if
240  // possible)
241  join_hash_table->freeHashBufferMemory();
242  throw HashJoinFail(std::string("Could not build a 1-to-1 correspondence for columns "
243  "involved in equijoin | ") +
244  e.what());
245  } catch (const ColumnarConversionNotSupported& e) {
246  throw HashJoinFail(std::string("Could not build hash tables for equijoin | ") +
247  e.what());
248  } catch (const OutOfMemory& e) {
249  throw HashJoinFail(
250  std::string("Ran out of memory while building hash tables for equijoin | ") +
251  e.what());
252  } catch (const std::exception& e) {
253  throw std::runtime_error(
254  std::string("Fatal error while attempting to build hash tables for join: ") +
255  e.what());
256  }
257  if (VLOGGING(1)) {
258  ts2 = std::chrono::steady_clock::now();
259  VLOG(1) << "Built perfect hash table "
260  << getHashTypeString(join_hash_table->getHashType()) << " in "
261  << std::chrono::duration_cast<std::chrono::milliseconds>(ts2 - ts1).count()
262  << " ms";
263  }
264  return join_hash_table;
265 }
266 
268  const InnerOuter& inner_outer_col_pair,
269  const InnerOuterStringOpInfos& inner_outer_string_op_infos,
270  const Executor* executor) {
271  if (inner_outer_string_op_infos.first.size() ||
272  inner_outer_string_op_infos.second.size()) {
273  return true;
274  }
275  auto inner_col = inner_outer_col_pair.first;
276  auto outer_col_expr = inner_outer_col_pair.second;
277  const auto catalog = executor->getCatalog();
278  CHECK(catalog);
279  const auto inner_cd = get_column_descriptor_maybe(
280  inner_col->get_column_id(), inner_col->get_table_id(), *catalog);
281  const auto& inner_ti = get_column_type(inner_col->get_column_id(),
282  inner_col->get_table_id(),
283  inner_cd,
284  executor->getTemporaryTables());
285  // Only strings may need dictionary translation.
286  if (!inner_ti.is_string()) {
287  return false;
288  }
289  const auto outer_col = dynamic_cast<const Analyzer::ColumnVar*>(outer_col_expr);
290  CHECK(outer_col);
291  const auto outer_cd = get_column_descriptor_maybe(
292  outer_col->get_column_id(), outer_col->get_table_id(), *catalog);
293  // Don't want to deal with temporary tables for now, require translation.
294  if (!inner_cd || !outer_cd) {
295  return true;
296  }
297  const auto& outer_ti = get_column_type(outer_col->get_column_id(),
298  outer_col->get_table_id(),
299  outer_cd,
300  executor->getTemporaryTables());
301  CHECK_EQ(inner_ti.is_string(), outer_ti.is_string());
302  // If the two columns don't share the dictionary, translation is needed.
303  if (outer_ti.get_comp_param() != inner_ti.get_comp_param()) {
304  return true;
305  }
306  const auto inner_str_dict_proxy =
307  executor->getStringDictionaryProxy(inner_col->get_comp_param(), true);
308  CHECK(inner_str_dict_proxy);
309  const auto outer_str_dict_proxy =
310  executor->getStringDictionaryProxy(inner_col->get_comp_param(), true);
311  CHECK(outer_str_dict_proxy);
312 
313  return *inner_str_dict_proxy != *outer_str_dict_proxy;
314 }
315 
316 std::vector<Fragmenter_Namespace::FragmentInfo> only_shards_for_device(
317  const std::vector<Fragmenter_Namespace::FragmentInfo>& fragments,
318  const int device_id,
319  const int device_count) {
320  std::vector<Fragmenter_Namespace::FragmentInfo> shards_for_device;
321  for (const auto& fragment : fragments) {
322  CHECK_GE(fragment.shard, 0);
323  if (fragment.shard % device_count == device_id) {
324  shards_for_device.push_back(fragment);
325  }
326  }
327  return shards_for_device;
328 }
329 
331  const std::vector<ColumnsForDevice>& columns_per_device) const {
332  CHECK(!inner_outer_pairs_.empty());
333  const auto& rhs_col_ti = inner_outer_pairs_.front().first->get_type_info();
334  const auto max_unique_hash_input_entries =
336  rhs_col_ti, rhs_source_col_range_, qual_bin_oper_->get_optype() == kBW_EQ)
337  .getNormalizedHashEntryCount() +
339  for (const auto& device_columns : columns_per_device) {
340  CHECK(!device_columns.join_columns.empty());
341  const auto rhs_join_col_num_entries = device_columns.join_columns.front().num_elems;
342  if (rhs_join_col_num_entries > max_unique_hash_input_entries) {
343  VLOG(1) << "Skipping attempt to build perfect hash one-to-one table as number of "
344  "rhs column entries ("
345  << rhs_join_col_num_entries << ") exceeds range for rhs join column ("
346  << max_unique_hash_input_entries << ").";
347  return false;
348  }
349  }
350  return true;
351 }
352 
354  auto timer = DEBUG_TIMER(__func__);
356  auto catalog = const_cast<Catalog_Namespace::Catalog*>(executor_->getCatalog());
357  const auto cols =
358  get_cols(qual_bin_oper_.get(), *catalog, executor_->temporary_tables_).first;
359  const auto inner_col = cols.first;
361  inner_col->get_table_id(),
363  executor_);
364  const auto& query_info = getInnerQueryInfo(inner_col).info;
365  if (query_info.fragments.empty()) {
366  return;
367  }
368  if (query_info.getNumTuplesUpperBound() >
369  static_cast<size_t>(std::numeric_limits<int32_t>::max())) {
370  throw TooManyHashEntries();
371  }
372  std::vector<std::future<void>> init_threads;
373  const int shard_count = shardCount();
374 
375  inner_outer_pairs_.push_back(cols);
376  CHECK_EQ(inner_outer_pairs_.size(), size_t(1));
377  // Todo(todd): Clean up the fact that we store the inner outer column pairs as a vector,
378  // even though only one is ever valid for perfect hash layout. Either move to 1 or keep
379  // the vector but move it to the HashTable parent class
382 
383  std::vector<std::vector<Fragmenter_Namespace::FragmentInfo>> fragments_per_device;
384  std::vector<ColumnsForDevice> columns_per_device;
385  std::vector<std::unique_ptr<CudaAllocator>> dev_buff_owners;
386 
387  auto data_mgr = executor_->getDataMgr();
388  // check the existence of cached hash table here before fetching columns
389  // if available, skip the rest of logic and copy it to GPU if necessary
390  // there are few considerable things:
391  // 1. if table is sharded? --> deploy per-device logic
392  // here, each device may load different set of fragments, so their cache keys are
393  // different accordingly
394  // 2. otherwise, each device has the same hash table built from "all" fragments
395  // and their cache keys are the same (but we stick to per-device cache key vector)
396  // here, for CPU, we consider its # device to be one
397  // for GPU, each device builds its own hash table, or we build a single hash table on
398  // CPU and then copy it to each device
399  // 3. if cache key is not available? --> use alternative cache key
400 
401  // retrieve fragment lists and chunk key per device
402  std::vector<ChunkKey> chunk_key_per_device;
403  auto outer_col =
404  dynamic_cast<const Analyzer::ColumnVar*>(inner_outer_pairs_.front().second);
405  for (int device_id = 0; device_id < device_count_; ++device_id) {
406  fragments_per_device.emplace_back(
407  shard_count
408  ? only_shards_for_device(query_info.fragments, device_id, device_count_)
409  : query_info.fragments);
411  dev_buff_owners.emplace_back(std::make_unique<CudaAllocator>(
412  data_mgr, device_id, getQueryEngineCudaStreamForDevice(device_id)));
413  }
414  const auto chunk_key =
415  genChunkKey(fragments_per_device[device_id], outer_col, inner_col);
416  chunk_key_per_device.emplace_back(std::move(chunk_key));
417  }
418 
419  // try to extract cache key for hash table and its relevant info
420  auto hashtable_access_path_info =
423  qual_bin_oper_->get_optype(),
424  join_type_,
427  shard_count,
428  fragments_per_device,
429  executor_);
430  hashtable_cache_key_ = hashtable_access_path_info.hashed_query_plan_dag;
431  hashtable_cache_meta_info_ = hashtable_access_path_info.meta_info;
432  table_keys_ = hashtable_access_path_info.table_keys;
433 
434  if (table_keys_.empty()) {
435  // the actual chunks fetched per device can be different but they constitute the same
436  // table in the same db, so we can exploit this to create an alternative table key
438  chunk_key_per_device,
439  executor_->getCatalog()->getDatabaseId(),
440  getInnerTableId());
441  }
442  CHECK(!table_keys_.empty());
443 
444  if (HashtableRecycler::isInvalidHashTableCacheKey(hashtable_cache_key_) &&
445  getInnerTableId() > 0) {
446  // sometimes we cannot retrieve query plan dag, so try to recycler cache
447  // with the old-fashioned cache key if we deal with hashtable of non-temporary table
448  for (int device_id = 0; device_id < device_count_; ++device_id) {
449  const auto num_tuples = std::accumulate(
450  fragments_per_device[device_id].begin(),
451  fragments_per_device[device_id].end(),
452  size_t(0),
453  [](size_t sum, const auto& fragment) { return sum + fragment.getNumTuples(); });
455  inner_col,
456  outer_col ? outer_col : inner_col,
458  chunk_key_per_device[device_id],
459  num_tuples,
460  qual_bin_oper_->get_optype(),
461  join_type_};
462  hashtable_cache_key_[device_id] = getAlternativeCacheKey(cache_key);
463  }
464  }
465 
466  // register a mapping between cache key and its input table info for per-table cache
467  // invalidation if we have valid cache key for "all" devices (otherwise, we skip to use
468  // cached hash table for safety)
469  const bool invalid_cache_key =
470  HashtableRecycler::isInvalidHashTableCacheKey(hashtable_cache_key_);
471  if (!invalid_cache_key) {
472  if (!shard_count) {
473  hash_table_cache_->addQueryPlanDagForTableKeys(hashtable_cache_key_.front(),
474  table_keys_);
475  } else {
476  std::for_each(hashtable_cache_key_.cbegin(),
477  hashtable_cache_key_.cend(),
478  [this](QueryPlanHash key) {
479  hash_table_cache_->addQueryPlanDagForTableKeys(key, table_keys_);
480  });
481  }
482  }
483 
484  const auto effective_memory_level = getEffectiveMemoryLevel(inner_outer_pairs_);
485 
486  // Assume we will need one-to-many if we have a string operation, as these tend
487  // to be cardinality-reducting operations, i.e. |S(t)| < |t|
488  // Todo(todd): Ostensibly only string ops on the rhs/inner expression cause rhs dups and
489  // so we may be too conservative here, but validate
490 
491  const bool has_string_ops = inner_outer_string_op_infos_.first.size() ||
492  inner_outer_string_op_infos_.second.size();
493 
494  // Also check if on the number of entries per column exceeds the rhs join hash table
495  // range, and skip trying to build a One-to-One hash table if so. There is a slight edge
496  // case where this can be overly pessimistic, and that is if the non-null values are all
497  // unique, but there are multiple null values, but we currently don't have the metadata
498  // to track null counts (only column nullability from the ddl and null existence from
499  // the encoded data), and this is probably too much of an edge case to worry about for
500  // now given the general performance benfits of skipping 1:1 if we are fairly confident
501  // it is doomed up front
502 
503  // Now check if on the number of entries per column exceeds the rhs join hash table
504  // range, and skip trying to build a One-to-One hash table if so
506  (has_string_ops || !isOneToOneHashPossible(columns_per_device))) {
508  }
509 
510  // todo (yoonmin) : support dictionary proxy cache for join including string op(s)
511  if (effective_memory_level == Data_Namespace::CPU_LEVEL) {
512  // construct string dictionary proxies if necessary
513  std::unique_lock<std::mutex> str_proxy_translation_lock(str_proxy_translation_mutex_);
514  if (needs_dict_translation_ && !str_proxy_translation_map_) {
515  CHECK_GE(inner_outer_pairs_.size(), 1UL);
519  col_range_,
520  executor_);
521  }
522  }
523 
524  auto allow_hashtable_recycling =
526  needs_dict_translation_,
528  inner_col->get_table_id());
529  bool has_invalid_cached_hash_table = false;
530  if (effective_memory_level == Data_Namespace::CPU_LEVEL &&
532  allow_hashtable_recycling, invalid_cache_key, join_type_)) {
533  // build a hash table on CPU, and we have a chance to recycle the cached one if
534  // available
535  for (int device_id = 0; device_id < device_count_; ++device_id) {
536  auto hash_table =
537  initHashTableOnCpuFromCache(hashtable_cache_key_[device_id],
540  if (hash_table) {
541  hash_tables_for_device_[device_id] = hash_table;
542  hash_type_ = hash_table->getLayout();
543  } else {
544  has_invalid_cached_hash_table = true;
545  break;
546  }
547  }
548 
549  if (has_invalid_cached_hash_table) {
550  hash_tables_for_device_.clear();
551  hash_tables_for_device_.resize(device_count_);
552  } else {
554 #ifdef HAVE_CUDA
555  for (int device_id = 0; device_id < device_count_; ++device_id) {
556  auto cpu_hash_table = std::dynamic_pointer_cast<PerfectHashTable>(
557  hash_tables_for_device_[device_id]);
558  copyCpuHashTableToGpu(cpu_hash_table, device_id, data_mgr);
559  }
560 #else
561  UNREACHABLE();
562 #endif
563  }
564  return;
565  }
566  }
567 
568  // we have no cached hash table for this qual
569  // so, start building the hash table by fetching columns for devices
570  for (int device_id = 0; device_id < device_count_; ++device_id) {
571  columns_per_device.emplace_back(
572  fetchColumnsForDevice(fragments_per_device[device_id],
573  device_id,
575  ? dev_buff_owners[device_id].get()
576  : nullptr,
577  *catalog));
578  }
579 
580  try {
581  for (int device_id = 0; device_id < device_count_; ++device_id) {
582  const auto chunk_key = genChunkKey(fragments_per_device[device_id],
583  inner_outer_pairs_.front().second,
584  inner_outer_pairs_.front().first);
585  init_threads.push_back(std::async(std::launch::async,
587  this,
588  chunk_key,
589  columns_per_device[device_id],
590  hash_type_,
591  device_id,
592  logger::thread_id()));
593  }
594  for (auto& init_thread : init_threads) {
595  init_thread.wait();
596  }
597  for (auto& init_thread : init_threads) {
598  init_thread.get();
599  }
600  } catch (const NeedsOneToManyHash& e) {
601  VLOG(1) << "RHS/Inner hash join values detected to not be unique, falling back to "
602  "One-to-Many hash layout.";
606  init_threads.clear();
608  CHECK_EQ(dev_buff_owners.size(), size_t(device_count_));
609  }
610  CHECK_EQ(columns_per_device.size(), size_t(device_count_));
611  for (int device_id = 0; device_id < device_count_; ++device_id) {
612  const auto chunk_key = genChunkKey(fragments_per_device[device_id],
613  inner_outer_pairs_.front().second,
614  inner_outer_pairs_.front().first);
615  init_threads.push_back(std::async(std::launch::async,
617  this,
618  chunk_key,
619  columns_per_device[device_id],
620  hash_type_,
621  device_id,
622  logger::thread_id()));
623  }
624  for (auto& init_thread : init_threads) {
625  init_thread.wait();
626  }
627  for (auto& init_thread : init_threads) {
628  init_thread.get();
629  }
630  }
631 }
632 
634  const std::vector<InnerOuter>& inner_outer_pairs) const {
636  inner_outer_pairs.front(), inner_outer_string_op_infos_, executor_)) {
639  }
640  return memory_level_;
641 }
642 
644  const std::vector<Fragmenter_Namespace::FragmentInfo>& fragments,
645  const int device_id,
646  DeviceAllocator* dev_buff_owner,
647  const Catalog_Namespace::Catalog& catalog) {
648  std::vector<JoinColumn> join_columns;
649  std::vector<std::shared_ptr<Chunk_NS::Chunk>> chunks_owner;
650  std::vector<JoinColumnTypeInfo> join_column_types;
651  std::vector<JoinBucketInfo> join_bucket_info;
652  std::vector<std::shared_ptr<void>> malloc_owner;
653  const auto effective_memory_level =
655  for (const auto& inner_outer_pair : inner_outer_pairs_) {
656  const auto inner_col = inner_outer_pair.first;
657  const auto inner_cd = get_column_descriptor_maybe(
658  inner_col->get_column_id(), inner_col->get_table_id(), catalog);
659  if (inner_cd && inner_cd->isVirtualCol) {
661  }
662  join_columns.emplace_back(fetchJoinColumn(inner_col,
663  fragments,
664  effective_memory_level,
665  device_id,
666  chunks_owner,
667  dev_buff_owner,
668  malloc_owner,
669  executor_,
670  &column_cache_));
671  const auto& ti = inner_col->get_type_info();
672  join_column_types.emplace_back(JoinColumnTypeInfo{static_cast<size_t>(ti.get_size()),
673  0,
674  0,
676  isBitwiseEq(),
677  0,
679  }
680  return {join_columns, join_column_types, chunks_owner, join_bucket_info, malloc_owner};
681 }
682 
684  const ColumnsForDevice& columns_for_device,
685  const HashType layout,
686  const int device_id,
687  const logger::ThreadId parent_thread_id) {
688  DEBUG_TIMER_NEW_THREAD(parent_thread_id);
689  const auto effective_memory_level =
691 
692  CHECK_EQ(columns_for_device.join_columns.size(), size_t(1));
693  CHECK_EQ(inner_outer_pairs_.size(), size_t(1));
694  auto& join_column = columns_for_device.join_columns.front();
695  if (layout == HashType::OneToOne) {
696  const auto err = initHashTableForDevice(chunk_key,
697  join_column,
698  inner_outer_pairs_.front(),
699  layout,
700 
701  effective_memory_level,
702  device_id);
703  if (err) {
704  throw NeedsOneToManyHash();
705  }
706  } else {
707  const auto err = initHashTableForDevice(chunk_key,
708  join_column,
709  inner_outer_pairs_.front(),
711  effective_memory_level,
712  device_id);
713  if (err) {
714  throw std::runtime_error("Unexpected error building one to many hash table: " +
715  std::to_string(err));
716  }
717  }
718 }
719 
721  const ChunkKey& chunk_key,
722  const JoinColumn& join_column,
723  const InnerOuter& cols,
724  const HashType layout,
725  const Data_Namespace::MemoryLevel effective_memory_level,
726  const int device_id) {
727  auto timer = DEBUG_TIMER(__func__);
728  const auto inner_col = cols.first;
729  CHECK(inner_col);
730 
731  auto hash_entry_info = get_bucketized_hash_entry_info(
732  inner_col->get_type_info(), col_range_, isBitwiseEq());
733  if (!hash_entry_info && layout == HashType::OneToOne) {
734  // TODO: what is this for?
735  return 0;
736  }
737 
738 #ifndef HAVE_CUDA
739  CHECK_EQ(Data_Namespace::CPU_LEVEL, effective_memory_level);
740 #endif
741  int err{0};
742  const int32_t hash_join_invalid_val{-1};
743  auto hashtable_layout = layout;
744  auto allow_hashtable_recycling =
748  inner_col->get_table_id());
749  if (allow_hashtable_recycling) {
750  auto cached_hashtable_layout_type = hash_table_layout_cache_->getItemFromCache(
751  hashtable_cache_key_[device_id],
754  {});
755  if (cached_hashtable_layout_type) {
756  hash_type_ = *cached_hashtable_layout_type;
757  hashtable_layout = hash_type_;
758  }
759  }
760  if (effective_memory_level == Data_Namespace::CPU_LEVEL) {
761  CHECK(!chunk_key.empty());
762  std::shared_ptr<PerfectHashTable> hash_table{nullptr};
763  decltype(std::chrono::steady_clock::now()) ts1, ts2;
764  ts1 = std::chrono::steady_clock::now();
765  {
766  std::lock_guard<std::mutex> cpu_hash_table_buff_lock(cpu_hash_table_buff_mutex_);
768  if (hashtable_layout == HashType::OneToOne) {
769  builder.initOneToOneHashTableOnCpu(join_column,
770  col_range_,
771  isBitwiseEq(),
772  cols,
774  join_type_,
775  hashtable_layout,
776  hash_entry_info,
777  hash_join_invalid_val,
778  executor_);
779  hash_table = builder.getHashTable();
780  } else {
781  builder.initOneToManyHashTableOnCpu(join_column,
782  col_range_,
783  isBitwiseEq(),
784  cols,
786  hash_entry_info,
787  hash_join_invalid_val,
788  executor_);
789  hash_table = builder.getHashTable();
790  }
791  ts2 = std::chrono::steady_clock::now();
792  auto build_time =
793  std::chrono::duration_cast<std::chrono::milliseconds>(ts2 - ts1).count();
794  hash_table->setHashEntryInfo(hash_entry_info);
795  hash_table->setColumnNumElems(join_column.num_elems);
796  if (allow_hashtable_recycling && hash_table) {
797  // add ht-related items to cache iff we have a valid hashtable
798  hash_table_layout_cache_->putItemToCache(hashtable_cache_key_[device_id],
799  hashtable_layout,
802  0,
803  0,
804  {});
807  hash_table,
809  build_time);
810  }
811  }
812  // Transfer the hash table on the GPU if we've only built it on CPU
813  // but the query runs on GPU (join on dictionary encoded columns).
815 #ifdef HAVE_CUDA
816  const auto& ti = inner_col->get_type_info();
817  CHECK(ti.is_string());
818  auto data_mgr = executor_->getDataMgr();
819  copyCpuHashTableToGpu(hash_table, device_id, data_mgr);
820 #else
821  UNREACHABLE();
822 #endif
823  } else {
824  CHECK(hash_table);
825  CHECK_LT(static_cast<size_t>(device_id), hash_tables_for_device_.size());
826  hash_tables_for_device_[device_id] = hash_table;
827  }
828  } else {
829 #ifdef HAVE_CUDA
831  CHECK_EQ(Data_Namespace::GPU_LEVEL, effective_memory_level);
832  builder.allocateDeviceMemory(join_column,
833  hashtable_layout,
834  hash_entry_info,
835  shardCount(),
836  device_id,
838  executor_);
839  builder.initHashTableOnGpu(chunk_key,
840  join_column,
841  col_range_,
842  isBitwiseEq(),
843  cols,
844  join_type_,
845  hashtable_layout,
846  hash_entry_info,
847  shardCount(),
848  hash_join_invalid_val,
849  device_id,
851  executor_);
852  CHECK_LT(static_cast<size_t>(device_id), hash_tables_for_device_.size());
853  hash_tables_for_device_[device_id] = builder.getHashTable();
854  if (!err && allow_hashtable_recycling && hash_tables_for_device_[device_id]) {
855  // add layout to cache iff we have a valid hashtable
856  hash_table_layout_cache_->putItemToCache(
857  hashtable_cache_key_[device_id],
858  hash_tables_for_device_[device_id]->getLayout(),
861  0,
862  0,
863  {});
864  }
865 #else
866  UNREACHABLE();
867 #endif
868  }
869  return err;
870 }
871 
873  const std::vector<Fragmenter_Namespace::FragmentInfo>& fragments,
874  const Analyzer::Expr* outer_col_expr,
875  const Analyzer::ColumnVar* inner_col) const {
876  ChunkKey chunk_key{executor_->getCatalog()->getCurrentDB().dbId,
877  inner_col->get_table_id(),
878  inner_col->get_column_id()};
879  const auto& ti = inner_col->get_type_info();
880  std::for_each(fragments.cbegin(), fragments.cend(), [&chunk_key](const auto& fragment) {
881  // collect all frag ids to correctly generated cache key for a cached hash table
882  chunk_key.push_back(fragment.fragmentId);
883  });
884  if (ti.is_string()) {
885  CHECK_EQ(kENCODING_DICT, ti.get_compression());
886  const auto outer_col = dynamic_cast<const Analyzer::ColumnVar*>(outer_col_expr);
887  CHECK(outer_col);
888  const auto& outer_query_info = getInnerQueryInfo(outer_col).info;
889  size_t outer_elem_count =
890  std::accumulate(outer_query_info.fragments.begin(),
891  outer_query_info.fragments.end(),
892  size_t(0),
893  [&chunk_key](size_t sum, const auto& fragment) {
894  chunk_key.push_back(fragment.fragmentId);
895  return sum + fragment.getNumTuples();
896  });
897  chunk_key.push_back(outer_elem_count);
898  }
899 
900  return chunk_key;
901 }
902 
903 std::shared_ptr<PerfectHashTable> PerfectJoinHashTable::initHashTableOnCpuFromCache(
904  QueryPlanHash key,
905  CacheItemType item_type,
906  DeviceIdentifier device_identifier) {
908  auto timer = DEBUG_TIMER(__func__);
909  VLOG(1) << "Checking CPU hash table cache.";
910  auto hashtable_ptr =
911  hash_table_cache_->getItemFromCache(key, item_type, device_identifier);
912  if (hashtable_ptr) {
913  return std::dynamic_pointer_cast<PerfectHashTable>(hashtable_ptr);
914  }
915  return nullptr;
916 }
917 
919  QueryPlanHash key,
920  CacheItemType item_type,
921  std::shared_ptr<PerfectHashTable> hashtable_ptr,
922  DeviceIdentifier device_identifier,
923  size_t hashtable_building_time) {
925  CHECK(hashtable_ptr && !hashtable_ptr->getGpuBuffer());
926  hash_table_cache_->putItemToCache(
927  key,
928  hashtable_ptr,
929  item_type,
930  device_identifier,
931  hashtable_ptr->getHashTableBufferSize(ExecutorDeviceType::CPU),
932  hashtable_building_time);
933 }
934 
935 llvm::Value* PerfectJoinHashTable::codegenHashTableLoad(const size_t table_idx) {
936  AUTOMATIC_IR_METADATA(executor_->cgen_state_.get());
937  const auto hash_ptr = HashJoin::codegenHashTableLoad(table_idx, executor_);
938  if (hash_ptr->getType()->isIntegerTy(64)) {
939  return hash_ptr;
940  }
941  CHECK(hash_ptr->getType()->isPointerTy());
942  return executor_->cgen_state_->ir_builder_.CreatePtrToInt(
943  get_arg_by_name(executor_->cgen_state_->row_func_, "join_hash_tables"),
944  llvm::Type::getInt64Ty(executor_->cgen_state_->context_));
945 }
946 
947 std::vector<llvm::Value*> PerfectJoinHashTable::getHashJoinArgs(
948  llvm::Value* hash_ptr,
949  llvm::Value* key_lv,
950  const Analyzer::Expr* key_col,
951  const int shard_count,
952  const CompilationOptions& co) {
953  AUTOMATIC_IR_METADATA(executor_->cgen_state_.get());
954  CodeGenerator code_generator(executor_);
955  CHECK(key_lv);
956  // Todo(todd): Fix below, it's gross (but didn't want to redo the plumbing yet)
957  // const auto key_lv = key_lvs.size() && key_lvs[0]
958  // ? key_lvs[0]
959  // : code_generator.codegen(key_col, true, co)[0];
960  auto const& key_col_ti = key_col->get_type_info();
961  auto hash_entry_info =
963 
964  std::vector<llvm::Value*> hash_join_idx_args{
965  hash_ptr,
966  executor_->cgen_state_->castToTypeIn(key_lv, 64),
967  executor_->cgen_state_->llInt(col_range_.getIntMin()),
968  executor_->cgen_state_->llInt(col_range_.getIntMax())};
969  if (shard_count) {
970  const auto expected_hash_entry_count =
972  const auto entry_count_per_shard =
973  (expected_hash_entry_count + shard_count - 1) / shard_count;
974  hash_join_idx_args.push_back(
975  executor_->cgen_state_->llInt<uint32_t>(entry_count_per_shard));
976  hash_join_idx_args.push_back(executor_->cgen_state_->llInt<uint32_t>(shard_count));
977  hash_join_idx_args.push_back(executor_->cgen_state_->llInt<uint32_t>(device_count_));
978  }
979  auto key_col_logical_ti = get_logical_type_info(key_col->get_type_info());
980  if (!key_col_logical_ti.get_notnull() || isBitwiseEq()) {
981  hash_join_idx_args.push_back(executor_->cgen_state_->llInt(
982  inline_fixed_encoding_null_val(key_col_logical_ti)));
983  }
984  auto special_date_bucketization_case = key_col_ti.get_type() == kDATE;
985  if (isBitwiseEq()) {
986  if (special_date_bucketization_case) {
987  hash_join_idx_args.push_back(executor_->cgen_state_->llInt(
988  col_range_.getIntMax() / hash_entry_info.bucket_normalization + 1));
989  } else {
990  hash_join_idx_args.push_back(
991  executor_->cgen_state_->llInt(col_range_.getIntMax() + 1));
992  }
993  }
994 
995  if (special_date_bucketization_case) {
996  hash_join_idx_args.emplace_back(
997  executor_->cgen_state_->llInt(hash_entry_info.bucket_normalization));
998  }
999 
1000  return hash_join_idx_args;
1001 }
1002 
1004  const size_t index) {
1005  AUTOMATIC_IR_METADATA(executor_->cgen_state_.get());
1006  const auto cols =
1007  get_cols(
1008  qual_bin_oper_.get(), *executor_->getCatalog(), executor_->temporary_tables_)
1009  .first;
1010  auto key_col = cols.second;
1011  CHECK(key_col);
1012  auto val_col = cols.first;
1013  CHECK(val_col);
1014  auto pos_ptr = codegenHashTableLoad(index);
1015  CHECK(pos_ptr);
1016  const int shard_count = shardCount();
1017  const auto key_col_var = dynamic_cast<const Analyzer::ColumnVar*>(key_col);
1018  const auto val_col_var = dynamic_cast<const Analyzer::ColumnVar*>(val_col);
1019  if (key_col_var && val_col_var &&
1021  key_col_var,
1022  val_col_var,
1023  get_max_rte_scan_table(executor_->cgen_state_->scan_idx_to_hash_pos_))) {
1024  throw std::runtime_error(
1025  "Query execution fails because the query contains not supported self-join "
1026  "pattern. We suspect the query requires multiple left-deep join tree due to "
1027  "the "
1028  "join condition of the self-join and is not supported for now. Please consider "
1029  "rewriting table order in "
1030  "FROM clause.");
1031  }
1032  CodeGenerator code_generator(executor_);
1033 
1034  auto key_lv = HashJoin::codegenColOrStringOper(
1035  key_col, inner_outer_string_op_infos_.second, code_generator, co);
1036 
1037  auto hash_join_idx_args = getHashJoinArgs(pos_ptr, key_lv, key_col, shard_count, co);
1038  const int64_t sub_buff_size = getComponentBufferSize();
1039  const auto& key_col_ti = key_col->get_type_info();
1040 
1041  auto bucketize = (key_col_ti.get_type() == kDATE);
1042  return HashJoin::codegenMatchingSet(hash_join_idx_args,
1043  shard_count,
1044  !key_col_ti.get_notnull(),
1045  isBitwiseEq(),
1046  sub_buff_size,
1047  executor_,
1048  bucketize);
1049 }
1050 
1051 size_t PerfectJoinHashTable::offsetBufferOff() const noexcept {
1052  return 0;
1053 }
1054 
1055 size_t PerfectJoinHashTable::countBufferOff() const noexcept {
1056  return getComponentBufferSize();
1057 }
1058 
1060  return 2 * getComponentBufferSize();
1061 }
1062 
1064  if (hash_tables_for_device_.empty()) {
1065  return 0;
1066  }
1067  auto hash_table = hash_tables_for_device_.front();
1068  if (hash_table && hash_table->getLayout() == HashType::OneToMany) {
1069  return hash_table->getEntryCount() * sizeof(int32_t);
1070  } else {
1071  return 0;
1072  }
1073 }
1074 
1076  CHECK_LT(device_id, hash_tables_for_device_.size());
1077  return hash_tables_for_device_[device_id].get();
1078 }
1079 
1081  std::shared_ptr<PerfectHashTable>& cpu_hash_table,
1082  const int device_id,
1083  Data_Namespace::DataMgr* data_mgr) {
1085  CHECK(data_mgr);
1086  CHECK(cpu_hash_table);
1087 
1088  std::lock_guard<std::mutex> cpu_hash_table_buff_lock(cpu_hash_table_buff_mutex_);
1089  PerfectJoinHashTableBuilder gpu_builder;
1090  gpu_builder.allocateDeviceMemory(cpu_hash_table->getColumnNumElems(),
1091  cpu_hash_table->getLayout(),
1092  cpu_hash_table->getHashEntryInfo(),
1093  shardCount(),
1094  device_id,
1095  device_count_,
1096  executor_);
1097 
1098  std::shared_ptr<PerfectHashTable> gpu_hash_table = gpu_builder.getHashTable();
1099  CHECK(gpu_hash_table);
1100  auto gpu_buffer_ptr = gpu_hash_table->getGpuBuffer();
1101  CHECK(gpu_buffer_ptr);
1102 
1103  CHECK_LE(cpu_hash_table->getHashTableBufferSize(ExecutorDeviceType::CPU),
1104  gpu_hash_table->getHashTableBufferSize(ExecutorDeviceType::GPU));
1105 
1106  auto device_allocator = std::make_unique<CudaAllocator>(
1107  data_mgr, device_id, getQueryEngineCudaStreamForDevice(device_id));
1108  device_allocator->copyToDevice(
1109  gpu_buffer_ptr,
1110  cpu_hash_table->getCpuBuffer(),
1111  cpu_hash_table->getHashTableBufferSize(ExecutorDeviceType::CPU));
1112  CHECK_LT(static_cast<size_t>(device_id), hash_tables_for_device_.size());
1113  hash_tables_for_device_[device_id] = std::move(gpu_hash_table);
1114 }
1115 
1117  const int device_id,
1118  bool raw) const {
1119  auto buffer = getJoinHashBuffer(device_type, device_id);
1120  auto buffer_size = getJoinHashBufferSize(device_type, device_id);
1121  auto hash_table = getHashTableForDevice(device_id);
1122 #ifdef HAVE_CUDA
1123  std::unique_ptr<int8_t[]> buffer_copy;
1124  if (device_type == ExecutorDeviceType::GPU) {
1125  buffer_copy = std::make_unique<int8_t[]>(buffer_size);
1126 
1127  auto data_mgr = executor_->getDataMgr();
1128  auto device_allocator = std::make_unique<CudaAllocator>(
1129  data_mgr, device_id, getQueryEngineCudaStreamForDevice(device_id));
1130  device_allocator->copyFromDevice(buffer_copy.get(), buffer, buffer_size);
1131  }
1132  auto ptr1 = buffer_copy ? buffer_copy.get() : reinterpret_cast<const int8_t*>(buffer);
1133 #else
1134  auto ptr1 = reinterpret_cast<const int8_t*>(buffer);
1135 #endif // HAVE_CUDA
1136  auto ptr2 = ptr1 + offsetBufferOff();
1137  auto ptr3 = ptr1 + countBufferOff();
1138  auto ptr4 = ptr1 + payloadBufferOff();
1139  return HashTable::toString("perfect",
1141  0,
1142  0,
1143  hash_table ? hash_table->getEntryCount() : 0,
1144  ptr1,
1145  ptr2,
1146  ptr3,
1147  ptr4,
1148  buffer_size,
1149  raw);
1150 }
1151 
1152 std::set<DecodedJoinHashBufferEntry> PerfectJoinHashTable::toSet(
1153  const ExecutorDeviceType device_type,
1154  const int device_id) const {
1155  auto buffer = getJoinHashBuffer(device_type, device_id);
1156  auto buffer_size = getJoinHashBufferSize(device_type, device_id);
1157  auto hash_table = getHashTableForDevice(device_id);
1158 #ifdef HAVE_CUDA
1159  std::unique_ptr<int8_t[]> buffer_copy;
1160  if (device_type == ExecutorDeviceType::GPU) {
1161  buffer_copy = std::make_unique<int8_t[]>(buffer_size);
1162 
1163  auto data_mgr = executor_->getDataMgr();
1164  auto device_allocator = std::make_unique<CudaAllocator>(
1165  data_mgr, device_id, getQueryEngineCudaStreamForDevice(device_id));
1166  device_allocator->copyFromDevice(buffer_copy.get(), buffer, buffer_size);
1167  }
1168  auto ptr1 = buffer_copy ? buffer_copy.get() : reinterpret_cast<const int8_t*>(buffer);
1169 #else
1170  auto ptr1 = reinterpret_cast<const int8_t*>(buffer);
1171 #endif // HAVE_CUDA
1172  auto ptr2 = ptr1 + offsetBufferOff();
1173  auto ptr3 = ptr1 + countBufferOff();
1174  auto ptr4 = ptr1 + payloadBufferOff();
1175  return HashTable::toSet(0,
1176  0,
1177  hash_table ? hash_table->getEntryCount() : 0,
1178  ptr1,
1179  ptr2,
1180  ptr3,
1181  ptr4,
1182  buffer_size);
1183 }
1184 
1186  const size_t index) {
1187  AUTOMATIC_IR_METADATA(executor_->cgen_state_.get());
1188  using namespace std::string_literals;
1189 
1191  const auto cols_and_string_op_infos = get_cols(
1192  qual_bin_oper_.get(), *executor_->getCatalog(), executor_->temporary_tables_);
1193  const auto& cols = cols_and_string_op_infos.first;
1194  const auto& inner_outer_string_op_infos = cols_and_string_op_infos.second;
1195  auto key_col = cols.second;
1196  CHECK(key_col);
1197  auto val_col = cols.first;
1198  CHECK(val_col);
1199  CodeGenerator code_generator(executor_);
1200  const auto key_col_var = dynamic_cast<const Analyzer::ColumnVar*>(key_col);
1201  const auto val_col_var = dynamic_cast<const Analyzer::ColumnVar*>(val_col);
1202  if (key_col_var && val_col_var &&
1204  key_col_var,
1205  val_col_var,
1206  get_max_rte_scan_table(executor_->cgen_state_->scan_idx_to_hash_pos_))) {
1207  throw std::runtime_error(
1208  "Query execution failed because the query contains not supported self-join "
1209  "pattern. We suspect the query requires multiple left-deep join tree due to "
1210  "the join condition of the self-join and is not supported for now. Please "
1211  "consider chaning the table order in the FROM clause.");
1212  }
1213 
1214  auto key_lv = HashJoin::codegenColOrStringOper(
1215  key_col, inner_outer_string_op_infos.second, code_generator, co);
1216 
1217  // CHECK_EQ(size_t(1), key_lvs.size());
1218  auto hash_ptr = codegenHashTableLoad(index);
1219  CHECK(hash_ptr);
1220  const int shard_count = shardCount();
1221  const auto hash_join_idx_args =
1222  getHashJoinArgs(hash_ptr, key_lv, key_col, shard_count, co);
1223 
1224  const auto& key_col_ti = key_col->get_type_info();
1225  std::string fname((key_col_ti.get_type() == kDATE) ? "bucketized_hash_join_idx"s
1226  : "hash_join_idx"s);
1227 
1228  if (isBitwiseEq()) {
1229  fname += "_bitwise";
1230  }
1231  if (shard_count) {
1232  fname += "_sharded";
1233  }
1234 
1235  if (!isBitwiseEq() && !key_col_ti.get_notnull()) {
1236  fname += "_nullable";
1237  }
1238  return executor_->cgen_state_->emitCall(fname, hash_join_idx_args);
1239 }
1240 
1242  const Analyzer::ColumnVar* inner_col) const {
1243  return get_inner_query_info(inner_col->get_table_id(), query_infos_);
1244 }
1245 
1247  const int inner_table_id,
1248  const std::vector<InputTableInfo>& query_infos) {
1249  std::optional<size_t> ti_idx;
1250  for (size_t i = 0; i < query_infos.size(); ++i) {
1251  if (inner_table_id == query_infos[i].table_id) {
1252  ti_idx = i;
1253  break;
1254  }
1255  }
1256  CHECK(ti_idx);
1257  return query_infos[*ti_idx];
1258 }
1259 
1260 size_t get_entries_per_device(const size_t total_entries,
1261  const size_t shard_count,
1262  const size_t device_count,
1263  const Data_Namespace::MemoryLevel memory_level) {
1264  const auto entries_per_shard =
1265  shard_count ? (total_entries + shard_count - 1) / shard_count : total_entries;
1266  size_t entries_per_device = entries_per_shard;
1267  if (memory_level == Data_Namespace::GPU_LEVEL && shard_count) {
1268  const auto shards_per_device = (shard_count + device_count - 1) / device_count;
1269  CHECK_GT(shards_per_device, 0u);
1270  entries_per_device = entries_per_shard * shards_per_device;
1271  }
1272  return entries_per_device;
1273 }
1274 
1278  : 0;
1279 }
1280 
1282  return qual_bin_oper_->get_optype() == kBW_EQ;
1283 }
int get_table_id() const
Definition: Analyzer.h:201
llvm::Value * codegenHashTableLoad(const size_t table_idx)
void reifyForDevice(const ChunkKey &hash_table_key, const ColumnsForDevice &columns_for_device, const HashType layout, const int device_id, const logger::ThreadId parent_thread_id)
int64_t getIntMin() const
#define CHECK_EQ(x, y)
Definition: Logger.h:230
std::vector< int > ChunkKey
Definition: types.h:36
size_t DeviceIdentifier
Definition: DataRecycler.h:129
size_t get_hash_entry_count(const ExpressionRange &col_range, const bool is_bw_eq)
virtual HashJoinMatchingSet codegenMatchingSet(const CompilationOptions &, const size_t)=0
JoinType
Definition: sqldefs.h:156
Fragmenter_Namespace::TableInfo info
Definition: InputMetadata.h:35
std::string cat(Ts &&...args)
Data_Namespace::MemoryLevel getEffectiveMemoryLevel(const std::vector< InnerOuter > &inner_outer_pairs) const
ExpressionRange rhs_source_col_range_
static llvm::Value * codegenHashTableLoad(const size_t table_idx, Executor *executor)
Definition: HashJoin.cpp:257
class for a per-database catalog. also includes metadata for the current database and the current use...
Definition: Catalog.h:132
bool self_join_not_covered_by_left_deep_tree(const Analyzer::ColumnVar *key_side, const Analyzer::ColumnVar *val_side, const int max_rte_covered)
static bool isInvalidHashTableCacheKey(const std::vector< QueryPlanHash > &cache_keys)
std::pair< const Analyzer::ColumnVar *, const Analyzer::Expr * > InnerOuter
Definition: HashJoin.h:95
HashEntryInfo get_bucketized_hash_entry_info(SQLTypeInfo const &context_ti, ExpressionRange const &col_range, bool const is_bw_eq)
#define IS_EQUIVALENCE(X)
Definition: sqldefs.h:68
static bool canAccessHashTable(bool allow_hash_table_recycling, bool invalid_cache_key, JoinType join_type)
Definition: HashJoin.cpp:1026
const Data_Namespace::MemoryLevel memory_level_
size_t getComponentBufferSize() const noexceptoverride
ExecutorDeviceType
std::shared_ptr< Analyzer::BinOper > qual_bin_oper_
size_t num_elems
std::mutex str_proxy_translation_mutex_
ChunkKey genChunkKey(const std::vector< Fragmenter_Namespace::FragmentInfo > &fragments, const Analyzer::Expr *outer_col, const Analyzer::ColumnVar *inner_col) const
const TableIdToNodeMap table_id_to_node_map_
const Expr * get_right_operand() const
Definition: Analyzer.h:451
size_t offsetBufferOff() const noexceptoverride
JoinColumn fetchJoinColumn(const Analyzer::ColumnVar *hash_col, const std::vector< Fragmenter_Namespace::FragmentInfo > &fragment_info, const Data_Namespace::MemoryLevel effective_memory_level, const int device_id, std::vector< std::shared_ptr< Chunk_NS::Chunk >> &chunks_owner, DeviceAllocator *dev_buff_owner, std::vector< std::shared_ptr< void >> &malloc_owner, Executor *executor, ColumnCacheMap *column_cache)
Definition: HashJoin.cpp:58
std::vector< std::shared_ptr< HashTable > > hash_tables_for_device_
Definition: HashJoin.h:351
#define UNREACHABLE()
Definition: Logger.h:266
const SQLTypeInfo get_column_type(const int col_id, const int table_id, const ColumnDescriptor *cd, const TemporaryTables *temporary_tables)
Definition: Execute.h:236
#define CHECK_GE(x, y)
Definition: Logger.h:235
HashTableBuildDagMap hashtable_build_dag_map_
Data_Namespace::MemoryLevel get_effective_memory_level(const Data_Namespace::MemoryLevel memory_level, const bool needs_dict_translation)
SQLTypeInfo get_logical_type_info(const SQLTypeInfo &type_info)
Definition: sqltypes.h:1221
const InputTableInfo & getInnerQueryInfo(const Analyzer::ColumnVar *inner_col) const
#define DEBUG_TIMER_NEW_THREAD(parent_thread_id)
Definition: Logger.h:376
size_t payloadBufferOff() const noexceptoverride
std::shared_ptr< PerfectHashTable > initHashTableOnCpuFromCache(QueryPlanHash key, CacheItemType item_type, DeviceIdentifier device_identifier)
HOST DEVICE SQLTypes get_type() const
Definition: sqltypes.h:404
bool needs_dictionary_translation(const std::vector< InnerOuter > &inner_outer_pairs, const std::vector< InnerOuterStringOpInfos > &inner_outer_string_op_infos_pairs, const Executor *executor)
static llvm::Value * codegenColOrStringOper(const Analyzer::Expr *col_or_string_oper, const std::vector< StringOps_Namespace::StringOpInfo > &string_op_infos, CodeGenerator &code_generator, const CompilationOptions &co)
Definition: HashJoin.cpp:539
void freeHashBufferMemory()
Definition: HashJoin.h:311
#define CHECK_GT(x, y)
Definition: Logger.h:234
const int get_max_rte_scan_table(std::unordered_map< int, llvm::Value * > &scan_idx_to_hash_pos)
HashType getHashType() const noexceptoverride
std::string to_string(char const *&&v)
void copyCpuHashTableToGpu(std::shared_ptr< PerfectHashTable > &cpu_hash_table, const int device_id, Data_Namespace::DataMgr *data_mgr)
HashtableCacheMetaInfo hashtable_cache_meta_info_
std::unordered_map< int, const ResultSetPtr & > TemporaryTables
Definition: InputMetadata.h:31
static std::unique_ptr< HashtableRecycler > hash_table_cache_
ColumnsForDevice fetchColumnsForDevice(const std::vector< Fragmenter_Namespace::FragmentInfo > &fragments, const int device_id, DeviceAllocator *dev_buff_owner, const Catalog_Namespace::Catalog &catalog)
future< Result > async(Fn &&fn, Args &&...args)
static std::pair< InnerOuter, InnerOuterStringOpInfos > normalizeColumnPair(const Analyzer::Expr *lhs, const Analyzer::Expr *rhs, const Catalog_Namespace::Catalog &cat, const TemporaryTables *temporary_tables, const bool is_overlaps_join=false)
Definition: HashJoin.cpp:797
std::unordered_map< size_t, HashTableBuildDag > HashTableBuildDagMap
llvm::Value * get_arg_by_name(llvm::Function *func, const std::string &name)
Definition: Execute.h:166
const ColumnDescriptor * get_column_descriptor_maybe(const int col_id, const int table_id, const Catalog_Namespace::Catalog &cat)
Definition: Execute.h:220
CacheItemType
Definition: DataRecycler.h:38
std::unordered_map< int, const RelAlgNode * > TableIdToNodeMap
std::vector< Fragmenter_Namespace::FragmentInfo > only_shards_for_device(const std::vector< Fragmenter_Namespace::FragmentInfo > &fragments, const int device_id, const int device_count)
bool isOneToOneHashPossible(const std::vector< ColumnsForDevice > &columns_per_device) const
int8_t * getJoinHashBuffer(const ExecutorDeviceType device_type, const int device_id) const
Definition: HashJoin.h:288
DEVICE auto accumulate(ARGS &&...args)
Definition: gpu_enabled.h:42
ExpressionRange getExpressionRange(const Analyzer::BinOper *expr, const std::vector< InputTableInfo > &query_infos, const Executor *, boost::optional< std::list< std::shared_ptr< Analyzer::Expr >>> simple_quals)
bool hasNulls() const
#define AUTOMATIC_IR_METADATA(CGENSTATE)
static void checkHashJoinReplicationConstraint(const int table_id, const size_t shard_count, const Executor *executor)
Definition: HashJoin.cpp:771
const SQLTypeInfo & get_type_info() const
Definition: Analyzer.h:82
std::vector< llvm::Value * > getHashJoinArgs(llvm::Value *hash_ptr, llvm::Value *key_lvs, const Analyzer::Expr *key_col, const int shard_count, const CompilationOptions &co)
void initOneToManyHashTableOnCpu(const JoinColumn &join_column, const ExpressionRange &col_range, const bool is_bitwise_eq, const std::pair< const Analyzer::ColumnVar *, const Analyzer::Expr * > &cols, const StringDictionaryProxy::IdMap *str_proxy_translation_map, const HashEntryInfo hash_entry_info, const int32_t hash_join_invalid_val, const Executor *executor)
std::vector< InnerOuter > inner_outer_pairs_
static ExpressionRange makeIntRange(const int64_t int_min, const int64_t int_max, const int64_t bucket, const bool has_nulls)
static const StringDictionaryProxy::IdMap * translateInnerToOuterStrDictProxies(const InnerOuter &cols, const InnerOuterStringOpInfos &inner_outer_string_op_infos, ExpressionRange &old_col_range, const Executor *executor)
Definition: HashJoin.cpp:408
PerfectJoinHashTable(const std::shared_ptr< Analyzer::BinOper > qual_bin_oper, const Analyzer::ColumnVar *col_var, const std::vector< InputTableInfo > &query_infos, const Data_Namespace::MemoryLevel memory_level, const JoinType join_type, const HashType preferred_hash_type, const ExpressionRange &col_range, const ExpressionRange &rhs_source_col_range, ColumnCacheMap &column_cache, Executor *executor, const int device_count, const HashTableBuildDagMap &hashtable_build_dag_map, const TableIdToNodeMap &table_id_to_node_map, const InnerOuterStringOpInfos &inner_outer_string_op_infos={})
void initOneToOneHashTableOnCpu(const JoinColumn &join_column, const ExpressionRange &col_range, const bool is_bitwise_eq, const InnerOuter &cols, const StringDictionaryProxy::IdMap *str_proxy_translation_map, const JoinType join_type, const HashType hash_type, const HashEntryInfo hash_entry_info, const int32_t hash_join_invalid_val, const Executor *executor)
std::unordered_map< int, std::unordered_map< int, std::shared_ptr< const ColumnarResults >>> ColumnCacheMap
static std::unique_ptr< HashingSchemeRecycler > hash_table_layout_cache_
std::unique_ptr< PerfectHashTable > getHashTable()
#define VLOGGING(n)
Definition: Logger.h:220
const InputTableInfo & get_inner_query_info(const int inner_table_id, const std::vector< InputTableInfo > &query_infos)
#define CHECK_LT(x, y)
Definition: Logger.h:232
static QueryPlanHash getAlternativeCacheKey(AlternativeCacheKeyForPerfectHashJoin &info)
Definition: sqltypes.h:67
const std::vector< InputTableInfo > & query_infos_
static std::shared_ptr< PerfectJoinHashTable > getInstance(const std::shared_ptr< Analyzer::BinOper > qual_bin_oper, const std::vector< InputTableInfo > &query_infos, const Data_Namespace::MemoryLevel memory_level, const JoinType join_type, const HashType preferred_hash_type, const int device_count, ColumnCacheMap &column_cache, Executor *executor, const HashTableBuildDagMap &hashtable_build_dag_map, const TableIdToNodeMap &table_id_to_node_map)
Make hash table from an in-flight SQL query&#39;s parse tree etc.
void allocateDeviceMemory(const size_t num_column_elems, const HashType layout, HashEntryInfo hash_entry_info, const size_t shard_count, const int device_id, const int device_count, const Executor *executor)
#define CHECK_LE(x, y)
Definition: Logger.h:233
int getInnerTableId() const noexceptoverride
void putHashTableOnCpuToCache(QueryPlanHash key, CacheItemType item_type, std::shared_ptr< PerfectHashTable > hashtable_ptr, DeviceIdentifier device_identifier, size_t hashtable_building_time)
static std::string getHashTypeString(HashType ht) noexcept
Definition: HashJoin.h:154
static std::unordered_set< size_t > getAlternativeTableKeys(const std::vector< ChunkKey > &chunk_keys, int db_id, int inner_table_id)
Definition: DataRecycler.h:154
std::string toString(const ExecutorDeviceType device_type, const int device_id=0, bool raw=false) const override
size_t getJoinHashBufferSize(const ExecutorDeviceType device_type)
Definition: HashJoin.h:274
static std::string toString(const std::string &type, const std::string &layout_type, size_t key_component_count, size_t key_component_width, size_t entry_count, const int8_t *ptr1, const int8_t *ptr2, const int8_t *ptr3, const int8_t *ptr4, size_t buffer_size, bool raw=false)
Decode hash table into a human-readable string.
Definition: HashTable.cpp:226
ColumnCacheMap & column_cache_
size_t get_entries_per_device(const size_t total_entries, const size_t shard_count, const size_t device_count, const Data_Namespace::MemoryLevel memory_level)
uint64_t ThreadId
Definition: Logger.h:364
size_t QueryPlanHash
CUstream getQueryEngineCudaStreamForDevice(int device_num)
Definition: QueryEngine.cpp:7
const InnerOuterStringOpInfos inner_outer_string_op_infos_
llvm::Value * codegenSlot(const CompilationOptions &, const size_t) override
bool shard_count_less_or_equal_device_count(const int inner_table_id, const Executor *executor)
ThreadId thread_id()
Definition: Logger.cpp:820
size_t getNormalizedHashEntryCount() const
int64_t getIntMax() const
ColumnType get_join_column_type_kind(const SQLTypeInfo &ti)
int64_t getBucket() const
std::pair< std::vector< StringOps_Namespace::StringOpInfo >, std::vector< StringOps_Namespace::StringOpInfo >> InnerOuterStringOpInfos
Definition: HashJoin.h:97
#define CHECK(condition)
Definition: Logger.h:222
#define DEBUG_TIMER(name)
Definition: Logger.h:371
Definition: sqldefs.h:30
int64_t inline_fixed_encoding_null_val(const SQL_TYPE_INFO &ti)
size_t countBufferOff() const noexceptoverride
const Expr * get_left_operand() const
Definition: Analyzer.h:450
static DecodedJoinHashBufferSet toSet(size_t key_component_count, size_t key_component_width, size_t entry_count, const int8_t *ptr1, const int8_t *ptr2, const int8_t *ptr3, const int8_t *ptr4, size_t buffer_size)
Decode hash table into a std::set for easy inspection and validation.
Definition: HashTable.cpp:139
int initHashTableForDevice(const ChunkKey &chunk_key, const JoinColumn &join_column, const InnerOuter &cols, const HashType layout, const Data_Namespace::MemoryLevel effective_memory_level, const int device_id)
int get_column_id() const
Definition: Analyzer.h:202
std::vector< QueryPlanHash > hashtable_cache_key_
HashTable * getHashTableForDevice(const size_t device_id) const
static constexpr DeviceIdentifier CPU_DEVICE_IDENTIFIER
Definition: DataRecycler.h:136
size_t get_shard_count(const Analyzer::BinOper *join_condition, const Executor *executor)
Definition: HashJoin.cpp:1045
static HashtableAccessPathInfo getHashtableAccessPathInfo(const std::vector< InnerOuter > &inner_outer_pairs, const std::vector< InnerOuterStringOpInfos > &inner_outer_string_op_infos_pairs, const SQLOps op_type, const JoinType join_type, const HashTableBuildDagMap &hashtable_build_dag_map, int device_count, int shard_count, const std::vector< std::vector< Fragmenter_Namespace::FragmentInfo >> &frags_for_device, Executor *executor)
std::set< DecodedJoinHashBufferEntry > toSet(const ExecutorDeviceType device_type, const int device_id) const override
HashType
Definition: HashTable.h:19
InnerOuter get_cols(const Analyzer::BinOper *qual_bin_oper, const Catalog_Namespace::Catalog &cat, const TemporaryTables *temporary_tables)
Definition: HashJoin.cpp:1035
const StringDictionaryProxy::IdMap * str_proxy_translation_map_
const std::vector< JoinColumn > join_columns
Definition: HashJoin.h:100
std::unordered_set< size_t > table_keys_
#define VLOG(n)
Definition: Logger.h:316
HashJoinMatchingSet codegenMatchingSet(const CompilationOptions &, const size_t) override
static bool isSafeToCacheHashtable(const TableIdToNodeMap &table_id_to_node_map, bool need_dict_translation, const std::vector< InnerOuterStringOpInfos > &inner_outer_string_op_info_pairs, const int table_id)
bool isBitwiseEq() const override