forked from apache/doris
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsorter.cpp
More file actions
346 lines (302 loc) · 13.5 KB
/
Copy pathsorter.cpp
File metadata and controls
346 lines (302 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "vec/common/sort/sorter.h"
#include <glog/logging.h>
#include <algorithm>
#include <cstddef>
#include <functional>
#include <ostream>
#include <string>
#include <utility>
#include "common/object_pool.h"
#include "runtime/exec_env.h"
#include "runtime/thread_context.h"
#include "util/runtime_profile.h"
#include "vec/columns/column.h"
#include "vec/columns/column_nullable.h"
#include "vec/core/block.h"
#include "vec/core/column_with_type_and_name.h"
#include "vec/core/sort_block.h"
#include "vec/data_types/data_type.h"
#include "vec/data_types/data_type_nullable.h"
#include "vec/exprs/vexpr_context.h"
#include "vec/utils/util.hpp"
namespace doris {
class RowDescriptor;
} // namespace doris
namespace doris::vectorized {
// When doing spillable sorting, each sorted block is spilled into a single file.
//
// In order to decrease memory pressure when merging
// multiple spilled blocks into one bigger sorted block, only part
// of each spilled blocks are read back into memory at a time.
//
// Currently the spilled blocks are splitted into small sub blocks,
// each sub block is serialized in PBlock format and appended
// to the spill file.
//
void MergeSorterState::reset() {
std::vector<std::shared_ptr<MergeSortCursorImpl>> empty_cursors(0);
std::vector<std::shared_ptr<Block>> empty_blocks(0);
_sorted_blocks.swap(empty_blocks);
unsorted_block() = Block::create_unique(unsorted_block()->clone_empty());
_in_mem_sorted_bocks_size = 0;
}
void MergeSorterState::add_sorted_block(std::shared_ptr<Block> block) {
auto rows = block->rows();
if (0 == rows) {
return;
}
_in_mem_sorted_bocks_size += block->bytes();
_sorted_blocks.emplace_back(block);
_num_rows += rows;
}
Status MergeSorterState::build_merge_tree(const SortDescription& sort_description) {
std::vector<MergeSortCursor> cursors;
for (auto& block : _sorted_blocks) {
cursors.emplace_back(
MergeSortCursorImpl::create_shared(std::move(block), sort_description));
}
_queue = MergeSorterQueue(cursors);
_sorted_blocks.clear();
return Status::OK();
}
Status MergeSorterState::merge_sort_read(doris::vectorized::Block* block, int batch_size,
bool* eos) {
DCHECK(_sorted_blocks.empty());
DCHECK(unsorted_block()->empty());
RETURN_IF_ERROR(_merge_sort_read_impl(batch_size, block, eos));
return Status::OK();
}
Status MergeSorterState::_merge_sort_read_impl(int batch_size, doris::vectorized::Block* block,
bool* eos) {
size_t num_columns = unsorted_block()->columns();
MutableBlock m_block = VectorizedUtils::build_mutable_mem_reuse_block(block, *unsorted_block());
MutableColumns& merged_columns = m_block.mutable_columns();
/// Take rows from queue in right order and push to 'merged'.
size_t merged_rows = 0;
// process single element queue on merge_sort_read()
while (_queue.is_valid() && merged_rows < batch_size) {
auto [current, current_rows] = _queue.current();
current_rows = std::min(current_rows, batch_size - merged_rows);
size_t step = std::min(_offset, current_rows);
_offset -= step;
current_rows -= step;
if (current->impl->is_last(current_rows + step) && current->impl->pos == 0 && step == 0) {
if (merged_rows != 0) {
// return directly for next time's read swap whole block
return Status::OK();
}
// swap and return block directly when we should get all data from cursor
block->swap(*current->impl->block);
_queue.remove_top();
return Status::OK();
}
if (current_rows) {
for (size_t i = 0; i < num_columns; ++i) {
merged_columns[i]->insert_range_from(*current->impl->columns[i],
current->impl->pos + step, current_rows);
}
merged_rows += current_rows;
}
if (!current->impl->is_last(current_rows + step)) {
_queue.next(current_rows + step);
} else {
_queue.remove_top();
}
}
block->set_columns(std::move(merged_columns));
if (merged_rows == 0) {
*eos = true;
}
return Status::OK();
}
Status Sorter::merge_sort_read_for_spill(RuntimeState* state, doris::vectorized::Block* block,
int batch_size, bool* eos) {
return get_next(state, block, eos);
}
Status Sorter::partial_sort(Block& src_block, Block& dest_block) {
size_t num_cols = src_block.columns();
if (_materialize_sort_exprs) {
auto output_tuple_expr_ctxs = _vsort_exec_exprs.sort_tuple_slot_expr_ctxs();
std::vector<int> valid_column_ids(output_tuple_expr_ctxs.size());
for (int i = 0; i < output_tuple_expr_ctxs.size(); ++i) {
RETURN_IF_ERROR(output_tuple_expr_ctxs[i]->execute(&src_block, &valid_column_ids[i]));
}
Block new_block;
int i = 0;
const auto& convert_nullable_flags = _vsort_exec_exprs.get_convert_nullable_flags();
for (auto column_id : valid_column_ids) {
if (column_id < 0) {
continue;
}
if (i < convert_nullable_flags.size() && convert_nullable_flags[i]) {
auto column_ptr = make_nullable(src_block.get_by_position(column_id).column);
new_block.insert(
{column_ptr, make_nullable(src_block.get_by_position(column_id).type), ""});
} else {
new_block.insert(src_block.get_by_position(column_id));
}
i++;
}
dest_block.swap(new_block);
}
_sort_description.resize(_vsort_exec_exprs.ordering_expr_ctxs().size());
Block* result_block = _materialize_sort_exprs ? &dest_block : &src_block;
for (int i = 0; i < _sort_description.size(); i++) {
const auto& ordering_expr = _vsort_exec_exprs.ordering_expr_ctxs()[i];
RETURN_IF_ERROR(ordering_expr->execute(result_block, &_sort_description[i].column_number));
_sort_description[i].direction = _is_asc_order[i] ? 1 : -1;
_sort_description[i].nulls_direction =
_nulls_first[i] ? -_sort_description[i].direction : _sort_description[i].direction;
}
{
SCOPED_TIMER(_partial_sort_timer);
if (_materialize_sort_exprs) {
sort_block(dest_block, dest_block, _sort_description, _offset + _limit);
} else {
sort_block(src_block, dest_block, _sort_description, _offset + _limit);
}
src_block.clear_column_data(num_cols);
}
return Status::OK();
}
FullSorter::FullSorter(VSortExecExprs& vsort_exec_exprs, int64_t limit, int64_t offset,
ObjectPool* pool, std::vector<bool>& is_asc_order,
std::vector<bool>& nulls_first, const RowDescriptor& row_desc,
RuntimeState* state, RuntimeProfile* profile)
: Sorter(vsort_exec_exprs, limit, offset, pool, is_asc_order, nulls_first),
_state(MergeSorterState::create_unique(row_desc, offset, limit, state, profile)) {}
// check whether the unsorted block can hold more data from input block and no need to alloc new memory
bool FullSorter::has_enough_capacity(Block* input_block, Block* unsorted_block) const {
DCHECK_EQ(input_block->columns(), unsorted_block->columns());
for (auto i = 0; i < input_block->columns(); ++i) {
if (!unsorted_block->get_by_position(i).column->has_enough_capacity(
*input_block->get_by_position(i).column)) {
return false;
}
}
return true;
}
size_t FullSorter::get_reserve_mem_size(RuntimeState* state, bool eos) const {
size_t size_to_reserve = 0;
const auto rows = _state->unsorted_block()->rows();
if (rows != 0) {
const auto bytes = _state->unsorted_block()->bytes();
const auto allocated_bytes = _state->unsorted_block()->allocated_bytes();
const auto bytes_per_row = bytes / rows;
const auto estimated_size_of_next_block = bytes_per_row * state->batch_size();
auto new_block_bytes = estimated_size_of_next_block + bytes;
auto new_rows = rows + state->batch_size();
// If the new size is greater than 85% of allocalted bytes, it maybe need to realloc.
if ((new_block_bytes * 100 / allocated_bytes) >= 85) {
size_to_reserve += (size_t)(allocated_bytes * 1.15);
}
auto sort = new_rows > _buffered_block_size || new_block_bytes > _buffered_block_bytes;
if (sort) {
// new column is created when doing sort, reserve average size of one column
// for estimation
size_to_reserve += new_block_bytes / _state->unsorted_block()->columns();
// helping data structures used during sorting
size_to_reserve += new_rows * sizeof(IColumn::Permutation::value_type);
auto sort_columns_count = _vsort_exec_exprs.ordering_expr_ctxs().size();
if (1 != sort_columns_count) {
size_to_reserve += new_rows * sizeof(EqualRangeIterator);
}
}
}
return size_to_reserve;
}
Status FullSorter::append_block(Block* block) {
DCHECK(block->rows() > 0);
// iff have reach limit and the unsorted block capacity can't hold the block data size
if (_reach_limit() && !has_enough_capacity(block, _state->unsorted_block().get())) {
RETURN_IF_ERROR(_do_sort());
}
{
SCOPED_TIMER(_merge_block_timer);
const auto& data = _state->unsorted_block()->get_columns_with_type_and_name();
const auto& arrival_data = block->get_columns_with_type_and_name();
auto sz = block->rows();
for (int i = 0; i < data.size(); ++i) {
DCHECK(data[i].type->equals(*(arrival_data[i].type)))
<< " type1: " << data[i].type->get_name()
<< " type2: " << arrival_data[i].type->get_name() << " i: " << i;
if (is_column_const(*arrival_data[i].column)) {
data[i].column->assume_mutable()->insert_many_from(
assert_cast<const ColumnConst*>(arrival_data[i].column.get())
->get_data_column(),
0, sz);
} else {
data[i].column->assume_mutable()->insert_range_from(*arrival_data[i].column, 0, sz);
}
}
block->clear_column_data();
}
return Status::OK();
}
Status FullSorter::prepare_for_read() {
if (_state->unsorted_block()->rows() > 0) {
RETURN_IF_ERROR(_do_sort());
}
return _state->build_merge_tree(_sort_description);
}
Status FullSorter::get_next(RuntimeState* state, Block* block, bool* eos) {
return _state->merge_sort_read(block, state->batch_size(), eos);
}
Status FullSorter::merge_sort_read_for_spill(RuntimeState* state, doris::vectorized::Block* block,
int batch_size, bool* eos) {
return _state->merge_sort_read(block, batch_size, eos);
}
Status FullSorter::_do_sort() {
Block* src_block = _state->unsorted_block().get();
Block desc_block = src_block->clone_without_columns();
COUNTER_UPDATE(_partial_sort_counter, 1);
RETURN_IF_ERROR(partial_sort(*src_block, desc_block));
// dispose TOP-N logic
if (_limit != -1 && !_enable_spill) {
// Here is a little opt to reduce the mem usage, we build a max heap
// to order the block in _block_priority_queue.
// if one block totally greater the heap top of _block_priority_queue
// we can throw the block data directly.
if (_state->num_rows() < _offset + _limit) {
_state->add_sorted_block(Block::create_shared(std::move(desc_block)));
_block_priority_queue.emplace(MergeSortCursorImpl::create_shared(
_state->last_sorted_block(), _sort_description));
} else {
auto tmp_cursor_impl = MergeSortCursorImpl::create_shared(
Block::create_shared(std::move(desc_block)), _sort_description);
MergeSortBlockCursor block_cursor(tmp_cursor_impl);
if (!block_cursor.totally_greater(_block_priority_queue.top())) {
_state->add_sorted_block(tmp_cursor_impl->block);
_block_priority_queue.emplace(MergeSortCursorImpl::create_shared(
_state->last_sorted_block(), _sort_description));
}
}
} else {
// dispose normal sort logic
_state->add_sorted_block(Block::create_shared(std::move(desc_block)));
}
return Status::OK();
}
size_t FullSorter::data_size() const {
return _state->data_size();
}
void FullSorter::reset() {
_state->reset();
}
} // namespace doris::vectorized