OmniSciDB  2c44a3935d
QueryMemoryDescriptor.h
Go to the documentation of this file.
1 /*
2  * Copyright 2017 MapD Technologies, 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 
25 #ifndef QUERYENGINE_QUERYMEMORYDESCRIPTOR_H
26 #define QUERYENGINE_QUERYMEMORYDESCRIPTOR_H
27 
28 #include "../CompilationOptions.h"
29 #include "../CountDistinct.h"
30 #include "ColSlotContext.h"
31 #include "Types.h"
32 
33 #include <boost/optional.hpp>
34 #include "Shared/Logger.h"
35 
36 #include <algorithm>
37 #include <cstddef>
38 #include <cstdint>
39 #include <memory>
40 #include <numeric>
41 #include <unordered_map>
42 #include <vector>
43 
44 #include <Shared/SqlTypesLayout.h>
45 #include <Shared/TargetInfo.h>
46 
47 extern bool g_cluster;
48 
49 class Executor;
51 class RenderInfo;
52 class RowSetMemoryOwner;
53 struct InputTableInfo;
54 struct RelAlgExecutionUnit;
55 class TResultSetBufferDescriptor;
57 struct ColRangeInfo;
58 struct KeylessInfo;
59 
60 class StreamingTopNOOM : public std::runtime_error {
61  public:
62  StreamingTopNOOM(const size_t heap_size_bytes)
63  : std::runtime_error("Unable to use streaming top N due to required heap size of " +
64  std::to_string(heap_size_bytes) +
65  " bytes exceeding maximum slab size.") {}
66 };
67 
69  public:
71 
72  // constructor for init call
73  QueryMemoryDescriptor(const Executor* executor,
74  const RelAlgExecutionUnit& ra_exe_unit,
75  const std::vector<InputTableInfo>& query_infos,
76  const bool allow_multifrag,
77  const bool keyless_hash,
78  const bool interleaved_bins_on_gpu,
79  const int32_t idx_target_as_key,
80  const ColRangeInfo& col_range_info,
81  const ColSlotContext& col_slot_context,
82  const std::vector<int8_t>& group_col_widths,
83  const int8_t group_col_compact_width,
84  const std::vector<ssize_t>& target_groupby_indices,
85  const size_t entry_count,
86  const CountDistinctDescriptors count_distinct_descriptors,
87  const bool sort_on_gpu_hint,
88  const bool output_columnar,
89  const bool render_output,
90  const bool must_use_baseline_sort,
91  const bool use_streaming_top_n);
92 
93  QueryMemoryDescriptor(const Executor* executor,
94  const size_t entry_count,
95  const QueryDescriptionType query_desc_type,
96  const bool is_table_function);
97 
98  QueryMemoryDescriptor(const QueryDescriptionType query_desc_type,
99  const int64_t min_val,
100  const int64_t max_val,
101  const bool has_nulls,
102  const std::vector<int8_t>& group_col_widths);
103 
104  // Serialization
105  QueryMemoryDescriptor(const TResultSetBufferDescriptor& thrift_query_memory_descriptor);
106  static TResultSetBufferDescriptor toThrift(const QueryMemoryDescriptor&);
107 
108  bool operator==(const QueryMemoryDescriptor& other) const;
109 
110  static std::unique_ptr<QueryMemoryDescriptor> init(
111  const Executor* executor,
112  const RelAlgExecutionUnit& ra_exe_unit,
113  const std::vector<InputTableInfo>& query_infos,
114  const ColRangeInfo& col_range_info,
115  const KeylessInfo& keyless_info,
116  const bool allow_multifrag,
117  const ExecutorDeviceType device_type,
118  const int8_t crt_min_byte_width,
119  const bool sort_on_gpu_hint,
120  const size_t shard_count,
121  const size_t max_groups_buffer_entry_count,
122  RenderInfo* render_info,
123  const CountDistinctDescriptors count_distinct_descriptors,
124  const bool must_use_baseline_sort,
125  const bool output_columnar_hint,
126  const bool streaming_top_n_hint);
127 
128  std::unique_ptr<QueryExecutionContext> getQueryExecutionContext(
129  const RelAlgExecutionUnit&,
130  const Executor* executor,
131  const ExecutorDeviceType device_type,
132  const ExecutorDispatchMode dispatch_mode,
133  const int device_id,
134  const int64_t num_rows,
135  const std::vector<std::vector<const int8_t*>>& col_buffers,
136  const std::vector<std::vector<uint64_t>>& frag_offsets,
137  std::shared_ptr<RowSetMemoryOwner>,
138  const bool output_columnar,
139  const bool sort_on_gpu,
140  RenderInfo*) const;
141 
142  static bool many_entries(const int64_t max_val,
143  const int64_t min_val,
144  const int64_t bucket) {
145  return max_val - min_val > 10000 * std::max(bucket, int64_t(1));
146  }
147 
149  const CountDistinctDescriptors& count_distinct_descriptors) {
150  return std::all_of(count_distinct_descriptors.begin(),
151  count_distinct_descriptors.end(),
152  [](const CountDistinctDescriptor& desc) {
153  return desc.impl_type_ == CountDistinctImplType::Invalid;
154  });
155  }
156 
158  return countDescriptorsLogicallyEmpty(count_distinct_descriptors_);
159  }
160 
161  static int8_t pick_target_compact_width(const RelAlgExecutionUnit& ra_exe_unit,
162  const std::vector<InputTableInfo>& query_infos,
163  const int8_t crt_min_byte_width);
164 
165  // Getters and Setters
166  const Executor* getExecutor() const { return executor_; }
167 
168  QueryDescriptionType getQueryDescriptionType() const { return query_desc_type_; }
169  void setQueryDescriptionType(const QueryDescriptionType val) { query_desc_type_ = val; }
171  return getQueryDescriptionType() == QueryDescriptionType::GroupByPerfectHash &&
172  getGroupbyColCount() == 1;
173  }
174 
175  bool hasKeylessHash() const { return keyless_hash_; }
176  void setHasKeylessHash(const bool val) { keyless_hash_ = val; }
177 
178  bool hasInterleavedBinsOnGpu() const { return interleaved_bins_on_gpu_; }
179  void setHasInterleavedBinsOnGpu(const bool val) { interleaved_bins_on_gpu_ = val; }
180 
181  int32_t getTargetIdxForKey() const { return idx_target_as_key_; }
182  void setTargetIdxForKey(const int32_t val) { idx_target_as_key_ = val; }
183 
184  int8_t groupColWidth(const size_t key_idx) const {
185  CHECK_LT(key_idx, group_col_widths_.size());
186  return group_col_widths_[key_idx];
187  }
188  size_t getPrependedGroupColOffInBytes(const size_t group_idx) const;
189  size_t getPrependedGroupBufferSizeInBytes() const;
190 
191  const auto groupColWidthsBegin() const { return group_col_widths_.begin(); }
192  const auto groupColWidthsEnd() const { return group_col_widths_.end(); }
193  void clearGroupColWidths() { group_col_widths_.clear(); }
194 
195  bool isGroupBy() const { return !group_col_widths_.empty(); }
196 
197  void setGroupColCompactWidth(const int8_t val) { group_col_compact_width_ = val; }
198 
199  size_t getColCount() const;
200  size_t getSlotCount() const;
201 
202  const int8_t getPaddedSlotWidthBytes(const size_t slot_idx) const;
203  const int8_t getLogicalSlotWidthBytes(const size_t slot_idx) const;
204 
205  const int8_t getSlotIndexForSingleSlotCol(const size_t col_idx) const;
206 
207  size_t getPaddedColWidthForRange(const size_t offset, const size_t range) const {
208  size_t ret = 0;
209  for (size_t i = offset; i < offset + range; i++) {
210  ret += static_cast<size_t>(getPaddedSlotWidthBytes(i));
211  }
212  return ret;
213  }
214 
215  void useConsistentSlotWidthSize(const int8_t slot_width_size);
216  size_t getRowWidth() const;
217 
218  int8_t updateActualMinByteWidth(const int8_t actual_min_byte_width) const;
219 
220  void addColSlotInfo(const std::vector<std::tuple<int8_t, int8_t>>& slots_for_col);
221 
222  void clearSlotInfo();
223 
224  void alignPaddedSlots();
225 
226  ssize_t getTargetGroupbyIndex(const size_t target_idx) const {
227  CHECK_LT(target_idx, target_groupby_indices_.size());
228  return target_groupby_indices_[target_idx];
229  }
230 
231  void setAllTargetGroupbyIndices(std::vector<ssize_t> group_by_indices) {
232  target_groupby_indices_ = group_by_indices;
233  }
234 
235  size_t targetGroupbyIndicesSize() const { return target_groupby_indices_.size(); }
237  return std::count_if(
238  target_groupby_indices_.begin(),
239  target_groupby_indices_.end(),
240  [](const ssize_t& target_group_by_index) { return target_group_by_index < 0; });
241  }
242  void clearTargetGroupbyIndices() { target_groupby_indices_.clear(); }
243 
244  size_t getEntryCount() const { return entry_count_; }
245  void setEntryCount(const size_t val) { entry_count_ = val; }
246 
247  int64_t getMinVal() const { return min_val_; }
248  int64_t getMaxVal() const { return max_val_; }
249  int64_t getBucket() const { return bucket_; }
250 
251  bool hasNulls() const { return has_nulls_; }
252 
253  const CountDistinctDescriptor& getCountDistinctDescriptor(const size_t idx) const {
254  CHECK_LT(idx, count_distinct_descriptors_.size());
255  return count_distinct_descriptors_[idx];
256  }
258  return count_distinct_descriptors_.size();
259  }
260 
261  bool sortOnGpu() const { return sort_on_gpu_; }
262 
263  bool canOutputColumnar() const;
264  bool didOutputColumnar() const { return output_columnar_; }
265  void setOutputColumnar(const bool val);
266 
267  bool useStreamingTopN() const { return use_streaming_top_n_; }
268 
269  bool isLogicalSizedColumnsAllowed() const;
270 
271  bool mustUseBaselineSort() const { return must_use_baseline_sort_; }
272 
273  // TODO(adb): remove and store this info more naturally in another
274  // member
275  bool forceFourByteFloat() const { return force_4byte_float_; }
276  void setForceFourByteFloat(const bool val) { force_4byte_float_ = val; }
277 
278  // Getters derived from state
279  size_t getGroupbyColCount() const { return group_col_widths_.size(); }
280  size_t getKeyCount() const { return keyless_hash_ ? 0 : getGroupbyColCount(); }
281  size_t getBufferColSlotCount() const;
282 
283  size_t getBufferSizeBytes(const RelAlgExecutionUnit& ra_exe_unit,
284  const unsigned thread_count,
285  const ExecutorDeviceType device_type) const;
286  size_t getBufferSizeBytes(const ExecutorDeviceType device_type) const;
287  size_t getBufferSizeBytes(const ExecutorDeviceType device_type,
288  const size_t override_entry_count) const;
289 
290  const ColSlotContext& getColSlotContext() const { return col_slot_context_; }
291 
292  // TODO(alex): remove
293  bool usesGetGroupValueFast() const;
294 
295  bool blocksShareMemory() const;
296  bool threadsShareMemory() const;
297 
298  bool lazyInitGroups(const ExecutorDeviceType) const;
299 
300  bool interleavedBins(const ExecutorDeviceType) const;
301 
302  size_t getColOffInBytes(const size_t col_idx) const;
303  size_t getColOffInBytesInNextBin(const size_t col_idx) const;
304  size_t getNextColOffInBytes(const int8_t* col_ptr,
305  const size_t bin,
306  const size_t col_idx) const;
307  size_t getColOnlyOffInBytes(const size_t col_idx) const;
308  size_t getRowSize() const;
309  size_t getColsSize() const;
310  size_t getWarpCount() const;
311 
312  size_t getCompactByteWidth() const;
313 
314  inline size_t getEffectiveKeyWidth() const {
315  return group_col_compact_width_ ? group_col_compact_width_ : sizeof(int64_t);
316  }
317 
318  bool isWarpSyncRequired(const ExecutorDeviceType) const;
319 
320  std::string queryDescTypeToString() const;
321  std::string toString() const;
322 
323  std::string reductionKey() const;
324 
325  protected:
326  void resetGroupColWidths(const std::vector<int8_t>& new_group_col_widths) {
327  group_col_widths_ = new_group_col_widths;
328  }
329 
330  private:
336  int32_t idx_target_as_key_; // If keyless_hash_ enabled, then represents what target
337  // expression should be used to identify the key (e.g., in
338  // locating empty entries). Currently only valid with
339  // keyless_hash_ and single-column GroupByPerfectHash
340  std::vector<int8_t> group_col_widths_;
341  int8_t group_col_compact_width_; // compact width for all group
342  // cols if able to be consistent
343  // otherwise 0
344  std::vector<ssize_t> target_groupby_indices_;
345  size_t entry_count_; // the number of entries in the main buffer
346  int64_t min_val_; // meaningful for OneColKnownRange,
347  // MultiColPerfectHash only
348  int64_t max_val_;
349  int64_t bucket_;
358 
360 
362 
363  size_t getTotalBytesOfColumnarBuffers() const;
364  size_t getTotalBytesOfColumnarBuffers(const size_t num_entries_per_column) const;
365  size_t getTotalBytesOfColumnarProjections(const size_t projection_count) const;
366 
367  friend class ResultSet;
368  friend class QueryExecutionContext;
369 };
370 
371 inline void set_notnull(TargetInfo& target, const bool not_null) {
372  target.skip_null_val = !not_null;
373  auto new_type = get_compact_type(target);
374  new_type.set_notnull(not_null);
375  set_compact_type(target, new_type);
376 }
377 
378 std::vector<TargetInfo> target_exprs_to_infos(
379  const std::vector<Analyzer::Expr*>& targets,
380  const QueryMemoryDescriptor& query_mem_desc);
381 
382 #endif // QUERYENGINE_QUERYMEMORYDESCRIPTOR_H
void set_compact_type(TargetInfo &target, const SQLTypeInfo &new_type)
static bool many_entries(const int64_t max_val, const int64_t min_val, const int64_t bucket)
const int8_t const int64_t * num_rows
ssize_t getTargetGroupbyIndex(const size_t target_idx) const
void setEntryCount(const size_t val)
ExecutorDeviceType
void setHasKeylessHash(const bool val)
void setGroupColCompactWidth(const int8_t val)
size_t getCountDistinctDescriptorsSize() const
void setAllTargetGroupbyIndices(std::vector< ssize_t > group_by_indices)
bool use_streaming_top_n(const RelAlgExecutionUnit &ra_exe_unit, const bool output_columnar)
bool skip_null_val
Definition: TargetInfo.h:44
void setQueryDescriptionType(const QueryDescriptionType val)
const auto groupColWidthsEnd() const
std::string to_string(char const *&&v)
const Executor * getExecutor() const
ExecutorDispatchMode
const SQLTypeInfo get_compact_type(const TargetInfo &target)
size_t targetGroupbyNegativeIndicesSize() const
void setTargetIdxForKey(const int32_t val)
std::vector< CountDistinctDescriptor > CountDistinctDescriptors
Definition: CountDistinct.h:35
Provides column info and slot info for the output buffer and some metadata helpers.
void init(LogOptions const &log_opts)
Definition: Logger.cpp:276
bool countDistinctDescriptorsLogicallyEmpty() const
CountDistinctDescriptors count_distinct_descriptors_
size_t getPaddedColWidthForRange(const size_t offset, const size_t range) const
size_t targetGroupbyIndicesSize() const
int8_t groupColWidth(const size_t key_idx) const
int32_t getTargetIdxForKey() const
#define CHECK_LT(x, y)
Definition: Logger.h:207
const auto groupColWidthsBegin() const
StreamingTopNOOM(const size_t heap_size_bytes)
QueryDescriptionType query_desc_type_
bool operator==(const SlotSize &lhs, const SlotSize &rhs)
void setForceFourByteFloat(const bool val)
const ColSlotContext & getColSlotContext() const
std::vector< int8_t > group_col_widths_
std::vector< TargetInfo > target_exprs_to_infos(const std::vector< Analyzer::Expr *> &targets, const QueryMemoryDescriptor &query_mem_desc)
QueryDescriptionType
Definition: Types.h:26
bool g_cluster
void resetGroupColWidths(const std::vector< int8_t > &new_group_col_widths)
const CountDistinctDescriptor & getCountDistinctDescriptor(const size_t idx) const
void setHasInterleavedBinsOnGpu(const bool val)
static bool countDescriptorsLogicallyEmpty(const CountDistinctDescriptors &count_distinct_descriptors)
QueryDescriptionType getQueryDescriptionType() const
bool isSingleColumnGroupByWithPerfectHash() const
std::vector< ssize_t > target_groupby_indices_
void set_notnull(TargetInfo &target, const bool not_null)
size_t getEffectiveKeyWidth() const
void sort_on_gpu(int64_t *val_buff, int32_t *key_buff, const uint64_t entry_count, const bool desc, const uint32_t chosen_bytes, ThrustAllocator &alloc)