-
Notifications
You must be signed in to change notification settings - Fork 185
/
Copy pathsparse_global_order_reader.cc
2233 lines (1934 loc) · 76.6 KB
/
sparse_global_order_reader.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file sparse_global_order_reader.cc
*
* @section LICENSE
*
* The MIT License
*
* @copyright Copyright (c) 2017-2024 TileDB, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @section DESCRIPTION
*
* This file implements class SparseGlobalOrderReader.
*/
#include "tiledb/sm/query/readers/sparse_global_order_reader.h"
#include "tiledb/common/logger.h"
#include "tiledb/common/memory_tracker.h"
#include "tiledb/sm/array/array.h"
#include "tiledb/sm/array_schema/array_schema.h"
#include "tiledb/sm/array_schema/dimension.h"
#include "tiledb/sm/fragment/fragment_metadata.h"
#include "tiledb/sm/misc/comparators.h"
#include "tiledb/sm/misc/hash.h"
#include "tiledb/sm/misc/hilbert.h"
#include "tiledb/sm/misc/parallel_functions.h"
#include "tiledb/sm/query/hilbert_order.h"
#include "tiledb/sm/query/query_macros.h"
#include "tiledb/sm/query/readers/result_tile.h"
#include "tiledb/sm/stats/global_stats.h"
#include "tiledb/sm/subarray/subarray.h"
using namespace tiledb;
using namespace tiledb::common;
using namespace tiledb::sm::stats;
namespace tiledb::sm {
class SparseGlobalOrderReaderException : public StatusException {
public:
explicit SparseGlobalOrderReaderException(const std::string& message)
: StatusException("SparseGlobalOrderReader", message) {
}
};
/* ****************************** */
/* CONSTRUCTORS */
/* ****************************** */
template <class BitmapType>
SparseGlobalOrderReader<BitmapType>::SparseGlobalOrderReader(
stats::Stats* stats,
shared_ptr<Logger> logger,
StrategyParams& params,
bool consolidation_with_timestamps)
: SparseIndexReaderBase(
"sparse_global_order",
stats,
logger->clone("SparseUnorderedWithDupsReader", ++logger_id_),
params,
true)
, result_tiles_leftover_(array_->fragment_metadata().size())
, memory_used_for_coords_(array_->fragment_metadata().size())
, consolidation_with_timestamps_(consolidation_with_timestamps)
, last_cells_(array_->fragment_metadata().size())
, tile_offsets_loaded_(false) {
// Initialize memory budget variables.
refresh_config();
}
/* ****************************** */
/* API */
/* ****************************** */
template <class BitmapType>
bool SparseGlobalOrderReader<BitmapType>::incomplete() const {
return !read_state_.done_adding_result_tiles() ||
memory_used_for_coords_total_ != 0;
}
template <class BitmapType>
QueryStatusDetailsReason
SparseGlobalOrderReader<BitmapType>::status_incomplete_reason() const {
if (array_->is_remote()) {
return QueryStatusDetailsReason::REASON_USER_BUFFER_SIZE;
}
return incomplete() ? QueryStatusDetailsReason::REASON_USER_BUFFER_SIZE :
QueryStatusDetailsReason::REASON_NONE;
}
template <class BitmapType>
void SparseGlobalOrderReader<BitmapType>::refresh_config() {
memory_budget_.refresh_config(config_, "sparse_global_order");
}
template <class BitmapType>
Status SparseGlobalOrderReader<BitmapType>::dowork() {
auto timer_se = stats_->start_timer("dowork");
stats_->add_counter("loop_num", 1);
// Check that the query condition is valid.
if (condition_.has_value()) {
throw_if_not_ok(condition_->check(array_schema_));
}
get_dim_attr_stats();
// Start with out buffer sizes as zero.
zero_out_buffer_sizes();
// Handle empty array.
if (fragment_metadata_.empty()) {
read_state_.set_done_adding_result_tiles(true);
return Status::Ok();
}
subarray_.reset_default_ranges();
// Load initial data, if not loaded already.
throw_if_not_ok(load_initial_data());
purge_deletes_consolidation_ = !deletes_consolidation_no_purge_ &&
consolidation_with_timestamps_ &&
!delete_and_update_conditions_.empty();
purge_deletes_no_dups_mode_ =
!array_schema_.allows_dups() && purge_deletes_consolidation_;
// Load tile offsets, if required.
load_all_tile_offsets();
// Field names to process.
std::vector<std::string> names = field_names_to_process();
bool user_buffers_full = false;
std::vector<ResultTilesList> result_tiles = std::move(result_tiles_leftover_);
do {
stats_->add_counter("internal_loop_num", 1);
// Create the result tiles we are going to process.
auto created_tiles = create_result_tiles(result_tiles);
if (created_tiles.size() > 0) {
// Read and unfilter coords.
throw_if_not_ok(read_and_unfilter_coords(created_tiles));
// Compute the tile bitmaps.
compute_tile_bitmaps<BitmapType>(created_tiles);
// Apply query condition.
apply_query_condition<GlobalOrderResultTile<BitmapType>, BitmapType>(
created_tiles);
// Run deduplication for tiles with timestamps, if required.
dedup_tiles_with_timestamps(created_tiles);
// Compute hilbert values.
if (array_schema_.cell_order() == Layout::HILBERT) {
compute_hilbert_values(created_tiles);
}
// Clear result tiles that are not necessary anymore.
clean_tile_list(result_tiles);
}
// For fragments with timestamps, check first and last cell of every tiles
// and if they have the same coordinates, only keep the cell with the
// greater timestamp.
dedup_fragments_with_timestamps(result_tiles);
// Compute RCS.
std::vector<ResultCellSlab> result_cell_slabs;
if (array_schema_.cell_order() == Layout::HILBERT) {
auto&& [user_buffs_full, rcs] =
merge_result_cell_slabs<HilbertCmpReverse>(
max_num_cells_to_copy(), result_tiles);
user_buffers_full = user_buffs_full;
result_cell_slabs = std::move(rcs);
} else {
auto&& [user_buffs_full, rcs] = merge_result_cell_slabs<GlobalCmpReverse>(
max_num_cells_to_copy(), result_tiles);
user_buffers_full = user_buffs_full;
result_cell_slabs = std::move(rcs);
}
// No more tiles to process, done.
if (!result_cell_slabs.empty()) {
// Copy cell slabs.
if (offsets_bitsize_ == 64) {
process_slabs<uint64_t>(names, result_cell_slabs, user_buffers_full);
} else {
process_slabs<uint32_t>(names, result_cell_slabs, user_buffers_full);
}
}
// End the iteration.
end_iteration(result_tiles);
} while (!user_buffers_full && incomplete());
result_tiles_leftover_ = std::move(result_tiles);
// Fix the output buffer sizes.
const auto cells = cells_copied(names);
stats_->add_counter("result_num", cells);
resize_output_buffers(cells);
if (offsets_extra_element_) {
add_extra_offset();
}
stats_->add_counter("ignored_tiles", tmp_read_state_.num_ignored_tiles());
return Status::Ok();
}
template <class BitmapType>
void SparseGlobalOrderReader<BitmapType>::reset() {
}
template <class BitmapType>
std::string SparseGlobalOrderReader<BitmapType>::name() {
return "SparseGlobalOrderReader<" + std::string(typeid(BitmapType).name()) +
">";
}
template <class BitmapType>
void SparseGlobalOrderReader<BitmapType>::load_all_tile_offsets() {
if (!tile_offsets_loaded_) {
// Make sure we have enough space for tile offsets data.
uint64_t total_tile_offset_usage =
tile_offsets_size(subarray_.relevant_fragments());
uint64_t available_memory = array_memory_tracker_->get_memory_available();
if (total_tile_offset_usage > available_memory) {
throw SparseGlobalOrderReaderException(
"Cannot load tile offsets, computed size (" +
std::to_string(total_tile_offset_usage) +
") is larger than available memory (" +
std::to_string(available_memory) +
"), increase memory budget. Total budget for array data (" +
std::to_string(array_memory_tracker_->get_memory_budget()) + ").");
}
tile_offsets_loaded_ = true;
load_tile_offsets_for_fragments(subarray_.relevant_fragments());
}
}
template <class BitmapType>
uint64_t SparseGlobalOrderReader<BitmapType>::get_coord_tiles_size(
unsigned dim_num, unsigned f, uint64_t t) {
auto tiles_size =
SparseIndexReaderBase::get_coord_tiles_size<BitmapType>(dim_num, f, t);
auto frag_meta = fragment_metadata_[f];
// Add the result tile structure size.
tiles_size += sizeof(GlobalOrderResultTile<BitmapType>);
// Account for hilbert data.
if (array_schema_.cell_order() == Layout::HILBERT) {
tiles_size += fragment_metadata_[f]->cell_num(t) * sizeof(uint64_t);
}
// Add the tile bitmap size if there is a subarray or pre query condition to
// be processed.
const bool dups = array_schema_.allows_dups();
if (subarray_.is_set() || process_partial_timestamps(*frag_meta) ||
(dups && has_post_deduplication_conditions(*frag_meta))) {
tiles_size += frag_meta->cell_num(t) * sizeof(BitmapType);
}
// Add the extra bitmap size if there is a condition to process and no dups.
// We will also create the bitmap as a temporay bitmap to compute delete
// condition results.
if ((!dups && has_post_deduplication_conditions(*frag_meta)) ||
deletes_consolidation_no_purge_) {
tiles_size += frag_meta->cell_num(t) * sizeof(BitmapType);
}
return tiles_size;
}
template <class BitmapType>
bool SparseGlobalOrderReader<BitmapType>::add_result_tile(
const unsigned dim_num,
const uint64_t memory_budget_coords_tiles,
const unsigned f,
const uint64_t t,
const FragmentMetadata& frag_md,
std::vector<ResultTilesList>& result_tiles) {
if (tmp_read_state_.is_ignored_tile(f, t)) {
return false;
}
// Calculate memory consumption for this tile.
auto tiles_size = get_coord_tiles_size(dim_num, f, t);
// Don't load more tiles than the memory budget.
if (memory_used_for_coords_[f] + tiles_size > memory_budget_coords_tiles) {
return true;
}
// Adjust total memory used.
memory_used_for_coords_total_ += tiles_size;
// Adjust per fragment memory used.
memory_used_for_coords_[f] += tiles_size;
// Add the tile.
result_tiles[f].emplace_back(
f,
t,
array_schema_.allows_dups(),
deletes_consolidation_no_purge_,
frag_md,
query_memory_tracker_);
return false;
}
template <class BitmapType>
std::vector<ResultTile*>
SparseGlobalOrderReader<BitmapType>::create_result_tiles(
std::vector<ResultTilesList>& result_tiles) {
auto timer_se = stats_->start_timer("create_result_tiles");
// For easy reference.
auto fragment_num = fragment_metadata_.size();
auto dim_num = array_schema_.dim_num();
// Get the number of fragments to process and compute per fragment memory.
uint64_t num_fragments_to_process =
tmp_read_state_.num_fragments_to_process();
// Save which result tile list is empty.
std::vector<uint64_t> rt_list_num_tiles(result_tiles.size());
for (uint64_t i = 0; i < result_tiles.size(); i++) {
rt_list_num_tiles[i] = result_tiles[i].size();
}
if (num_fragments_to_process > 0) {
per_fragment_memory_ =
memory_budget_.coordinates_budget() / num_fragments_to_process;
// Create result tiles.
if (subarray_.is_set()) {
// Load as many tiles as the memory budget allows.
throw_if_not_ok(parallel_for(
&resources_.compute_tp(), 0, fragment_num, [&](uint64_t f) {
uint64_t t = 0;
auto& tile_ranges = tmp_read_state_.tile_ranges(f);
while (!tile_ranges.empty()) {
auto& range = tile_ranges.back();
for (t = range.first; t <= range.second; t++) {
auto budget_exceeded = add_result_tile(
dim_num,
per_fragment_memory_,
f,
t,
*fragment_metadata_[f],
result_tiles);
if (budget_exceeded) {
logger_->debug(
"Budget exceeded adding result tiles, fragment {0}, tile "
"{1}",
f,
t);
if (result_tiles[f].empty()) {
auto tiles_size = get_coord_tiles_size(dim_num, f, t);
throw SparseGlobalOrderReaderException(
"Cannot load a single tile for fragment, increase "
"memory "
"budget, tile size : " +
std::to_string(tiles_size) + ", per fragment memory " +
std::to_string(per_fragment_memory_) +
", total budget " +
std::to_string(memory_budget_.total_budget()) +
", processing fragment " + std::to_string(f) +
" out of " + std::to_string(num_fragments_to_process) +
" total fragments");
}
return Status::Ok();
}
range.first++;
}
tmp_read_state_.remove_tile_range(f);
}
tmp_read_state_.set_all_tiles_loaded(f);
return Status::Ok();
}));
} else {
// Load as many tiles as the memory budget allows.
throw_if_not_ok(parallel_for(
&resources_.compute_tp(), 0, fragment_num, [&](uint64_t f) {
uint64_t t = 0;
auto tile_num = fragment_metadata_[f]->tile_num();
// Figure out the start index.
auto start = read_state_.frag_idx()[f].tile_idx_;
if (!result_tiles[f].empty()) {
start = std::max(start, result_tiles[f].back().tile_idx() + 1);
}
for (t = start; t < tile_num; t++) {
auto budget_exceeded = add_result_tile(
dim_num,
per_fragment_memory_,
f,
t,
*fragment_metadata_[f],
result_tiles);
if (budget_exceeded) {
logger_->debug(
"Budget exceeded adding result tiles, fragment {0}, tile "
"{1}",
f,
t);
if (result_tiles[f].empty()) {
auto tiles_size = get_coord_tiles_size(dim_num, f, t);
return logger_->status(Status_SparseGlobalOrderReaderError(
"Cannot load a single tile for fragment, increase memory "
"budget, tile size : " +
std::to_string(tiles_size) + ", per fragment memory " +
std::to_string(per_fragment_memory_) + ", total budget " +
std::to_string(memory_budget_.total_budget()) +
", num fragments to process " +
std::to_string(num_fragments_to_process)));
}
return Status::Ok();
}
}
tmp_read_state_.set_all_tiles_loaded(f);
return Status::Ok();
}));
}
}
bool done_adding_result_tiles = tmp_read_state_.done_adding_result_tiles();
uint64_t num_rt = 0;
for (unsigned int f = 0; f < fragment_num; f++) {
num_rt += result_tiles[f].size();
}
logger_->debug("Done adding result tiles, num result tiles {0}", num_rt);
if (done_adding_result_tiles) {
logger_->debug("All result tiles loaded");
}
read_state_.set_done_adding_result_tiles(done_adding_result_tiles);
// Return the list of tiles added.
std::vector<ResultTile*> created_tiles;
for (uint64_t i = 0; i < result_tiles.size(); i++) {
TileListIt it = result_tiles[i].begin();
std::advance(it, rt_list_num_tiles[i]);
for (; it != result_tiles[i].end(); ++it) {
created_tiles.emplace_back(&*it);
}
}
return created_tiles;
}
template <class BitmapType>
void SparseGlobalOrderReader<BitmapType>::clean_tile_list(
std::vector<ResultTilesList>& result_tiles) {
// Clear result tiles that are not necessary anymore.
auto fragment_num = fragment_metadata_.size();
throw_if_not_ok(
parallel_for(&resources_.compute_tp(), 0, fragment_num, [&](uint64_t f) {
auto it = result_tiles[f].begin();
while (it != result_tiles[f].end()) {
if (it->result_num() == 0) {
tmp_read_state_.add_ignored_tile(*it);
remove_result_tile(f, it++, result_tiles);
} else {
it++;
}
}
return Status::Ok();
}));
}
template <class BitmapType>
void SparseGlobalOrderReader<BitmapType>::dedup_tiles_with_timestamps(
std::vector<ResultTile*>& result_tiles) {
// For consolidation with timestamps or arrays with duplicates, no need to
// do deduplication.
if (consolidation_with_timestamps_ || array_schema_.allows_dups()) {
return;
}
auto timer_se = stats_->start_timer("dedup_tiles_with_timestamps");
// Process all tiles in parallel.
throw_if_not_ok(parallel_for(
&resources_.compute_tp(), 0, result_tiles.size(), [&](uint64_t t) {
const auto f = result_tiles[t]->frag_idx();
if (fragment_metadata_[f]->has_timestamps()) {
// For easy reference.
auto rt =
static_cast<GlobalOrderResultTile<BitmapType>*>(result_tiles[t]);
auto cell_num =
fragment_metadata_[rt->frag_idx()]->cell_num(rt->tile_idx());
// Make a bitmap if necessary.
if (!rt->has_bmp()) {
rt->alloc_bitmap();
}
// Process all cells.
uint64_t c = 0;
while (c < cell_num - 1) {
// If the cell is in the bitmap.
if (rt->bitmap()[c]) {
// Save the current cell timestamp as max and move to the next.
uint64_t max_timestamp = rt->timestamp(c);
uint64_t max = c;
c++;
// Process all cells with the same coordinates and keep only the
// one with the biggest timestamp in the bitmap.
while (c < cell_num && rt->same_coords(max, c)) {
// If the cell is in the bitmap.
if (rt->bitmap()[c]) {
uint64_t current_timestamp = rt->timestamp(c);
// If the current cell has a bigger timestamp, clear the old
// max in the bitmap and save the new max.
if (current_timestamp > max_timestamp) {
rt->clear_cell(max);
max_timestamp = current_timestamp;
max = c;
} else {
// Clear this cell from the bitmap.
rt->clear_cell(c);
}
}
// Next cell.
c++;
}
} else {
// Cell not in bitmap, move to next.
c++;
}
}
// Count new number of cells in the bitmap.
rt->count_cells();
}
return Status::Ok();
}));
logger_->debug("Done processing fragments with timestamps");
}
template <class BitmapType>
void SparseGlobalOrderReader<BitmapType>::dedup_fragments_with_timestamps(
std::vector<ResultTilesList>& result_tiles) {
// For consolidation with timestamps or arrays with duplicates, no need to
// do deduplication.
if (consolidation_with_timestamps_ || array_schema_.allows_dups()) {
return;
}
auto timer_se = stats_->start_timer("dedup_fragments_with_timestamps");
// Run all fragments in parallel.
auto fragment_num = fragment_metadata_.size();
throw_if_not_ok(
parallel_for(&resources_.compute_tp(), 0, fragment_num, [&](uint64_t f) {
// Run only for fragments with timestamps.
if (fragment_metadata_[f]->has_timestamps()) {
// Process all tiles.
auto it = result_tiles[f].begin();
while (it != result_tiles[f].end()) {
// Compare the current tile to the next.
auto next_tile = it;
next_tile++;
if (next_tile == result_tiles[f].end()) {
// No more tiles, save the last cell for this fragment for later
// processing.
last_cells_[f] =
FragIdx(it->tile_idx(), it->last_cell_in_bitmap());
it++;
} else {
// Compare the last tile from current to the first from next.
auto last = it->last_cell_in_bitmap();
auto first = next_tile->first_cell_in_bitmap();
if (!it->same_coords(*next_tile, last, first)) {
// Not the same coords, move to the next tile.
it++;
} else {
// Same coords, compare timestamps.
if (it->timestamp(last) > next_tile->timestamp(first)) {
// Remove the cell in the next tile.
if (next_tile->result_num() == 1) {
// Only one cell in the bitmap, delete next tile.
// Stay on this tile as we will compare to the new next.
tmp_read_state_.add_ignored_tile(*next_tile);
remove_result_tile(f, next_tile, result_tiles);
} else {
// Remove the cell in the bitmap and move to the next tile.
next_tile->clear_cell(first);
it++;
}
} else {
// Remove the cell in the current tile.
if (next_tile->result_num() == 1) {
// Only one cell in the bitmap, delete current tile.
auto to_delete = it;
it++;
tmp_read_state_.add_ignored_tile(*to_delete);
remove_result_tile(f, to_delete, result_tiles);
} else {
// Remove the cell in the bitmap and move to the next tile.
it->clear_cell(last);
it++;
}
}
}
}
}
}
return Status::Ok();
}));
}
template <class BitmapType>
uint64_t SparseGlobalOrderReader<BitmapType>::max_num_cells_to_copy() {
auto timer_se = stats_->start_timer("max_num_cells_to_copy");
// First try to limit the maximum number of cells we copy using the size
// of the output buffers for fixed sized attributes. Later we will validate
// the memory budget. This is the first line of defence used to try to prevent
// overflows when copying data.
uint64_t num_cells = std::numeric_limits<uint64_t>::max();
for (const auto& it : buffers_) {
const auto& name = it.first;
const auto size = it.second.original_buffer_size_ - *it.second.buffer_size_;
if (array_schema_.var_size(name)) {
auto temp_num_cells = size / constants::cell_var_offset_size;
if (offsets_extra_element_ && temp_num_cells > 0)
temp_num_cells--;
num_cells = std::min(num_cells, temp_num_cells);
} else {
auto temp_num_cells = size / array_schema_.cell_size(name);
num_cells = std::min(num_cells, temp_num_cells);
}
}
return num_cells;
}
template <class BitmapType>
template <class CompType>
bool SparseGlobalOrderReader<BitmapType>::add_all_dups_to_queue(
GlobalOrderResultCoords<BitmapType>& rc,
std::vector<TileListIt>& result_tiles_it,
const std::vector<ResultTilesList>& result_tiles,
TileMinHeap<CompType>& tile_queue,
std::vector<TileListIt>& to_delete) {
auto frag_idx = rc.tile_->frag_idx();
auto dups = array_schema_.allows_dups();
uint64_t last_cell_pos;
if (rc.tile_->has_bmp()) {
last_cell_pos = rc.tile_->last_cell_in_bitmap();
} else {
last_cell_pos =
fragment_metadata_[frag_idx]->cell_num(rc.tile_->tile_idx()) - 1;
}
while (rc.next_cell_same_coords()) {
// Construct a new result coords that specifies it has no next cell.
// A cell will be added after this one so we don't want to process it
// twice.
tile_queue.emplace(rc.tile_, rc.pos_, false);
rc.advance_to_next_cell();
// For arrays with no duplicates, we cannot use the last cell of a
// fragment with timestamps if not all tiles are loaded.
if (!dups && last_in_memory_cell_of_consolidated_fragment(
frag_idx, rc, result_tiles)) {
return true;
}
// If we are at the last cell of this tile, check the next tile.
if (rc.pos_ == last_cell_pos) {
auto next_tile = result_tiles_it[frag_idx];
next_tile++;
if (next_tile != result_tiles[frag_idx].end()) {
GlobalOrderResultCoords rc2(&*next_tile, 0);
// All tiles should at least have one cell available.
if (!rc2.advance_to_next_cell()) {
throw std::logic_error("All tiles should have at least one cell.");
}
// Next tile starts with the same coords, switch to it.
if (rc.same_coords(rc2)) {
tile_queue.emplace(rc.tile_, rc.pos_, false);
// Remove the current tile if not used.
if (!rc.tile_->used()) {
tmp_read_state_.add_ignored_tile(*result_tiles_it[frag_idx]);
to_delete.emplace_back(result_tiles_it[frag_idx]);
}
result_tiles_it[frag_idx] = next_tile;
rc = rc2;
}
}
}
}
return false;
}
template <class BitmapType>
template <class CompType>
bool SparseGlobalOrderReader<BitmapType>::add_next_cell_to_queue(
GlobalOrderResultCoords<BitmapType>& rc,
std::vector<TileListIt>& result_tiles_it,
const std::vector<ResultTilesList>& result_tiles,
TileMinHeap<CompType>& tile_queue,
std::vector<TileListIt>& to_delete) {
auto frag_idx = rc.tile_->frag_idx();
auto dups = array_schema_.allows_dups();
// Exit early if the result coords specifies it has no next cell to process.
// This would be because a cell after this one in the fragment was added to
// the queue as it had the same coordinates as this one.
if (!rc.has_next_) {
return false;
}
// Try the next cell in the same tile.
if (!rc.advance_to_next_cell()) {
// Save the potential tile to delete and increment the tile iterator.
auto to_delete_it = result_tiles_it[frag_idx];
result_tiles_it[frag_idx]++;
// Remove the tile from result tiles if it wasn't used at all.
if (!rc.tile_->used()) {
tmp_read_state_.add_ignored_tile(*to_delete_it);
to_delete.push_back(to_delete_it);
}
// Try to find a new tile.
if (result_tiles_it[frag_idx] != result_tiles[frag_idx].end()) {
// Find a cell in the current result tile.
rc = GlobalOrderResultCoords(&*result_tiles_it[frag_idx], 0);
// All tiles should at least have one cell available.
if (!rc.advance_to_next_cell()) {
throw std::logic_error("All tiles should have at least one cell.");
}
} else {
// Increment the tile index, which should clear all tiles in
// end_iteration.
if (!result_tiles[frag_idx].empty()) {
uint64_t new_tile_idx = read_state_.frag_idx()[frag_idx].tile_idx_ + 1;
read_state_.set_frag_idx(frag_idx, FragIdx(new_tile_idx, 0));
}
// This fragment has more tiles potentially.
if (!tmp_read_state_.all_tiles_loaded(frag_idx)) {
// Return we need more tiles.
return true;
}
// All tiles processed, done.
return false;
}
}
// We have a cell, add it to the list.
{
// For arrays with no duplicates, we cannot use the last cell of a fragment
// with timestamps if not all tiles are loaded.
if (!dups && last_in_memory_cell_of_consolidated_fragment(
frag_idx, rc, result_tiles)) {
return true;
}
std::unique_lock<std::mutex> ul(tile_queue_mutex_);
// Add all the cells in this tile with the same coordinates as this cell
// for purge deletes with no dups mode.
if (purge_deletes_no_dups_mode_ &&
fragment_metadata_[frag_idx]->has_timestamps()) {
if (add_all_dups_to_queue(
rc, result_tiles_it, result_tiles, tile_queue, to_delete)) {
return true;
}
}
tile_queue.emplace(std::move(rc));
}
// We don't need more tiles as a tile was found.
return false;
}
template <class BitmapType>
void SparseGlobalOrderReader<BitmapType>::compute_hilbert_values(
std::vector<ResultTile*>& result_tiles) {
auto timer_se = stats_->start_timer("compute_hilbert_values");
// For easy reference.
auto dim_num = array_schema_.dim_num();
// Create a Hilbet class.
Hilbert h(dim_num);
auto bits = h.bits();
auto max_bucket_val = ((uint64_t)1 << bits) - 1;
// Parallelize on tiles.
throw_if_not_ok(parallel_for(
&resources_.compute_tp(), 0, result_tiles.size(), [&](uint64_t t) {
auto tile =
static_cast<GlobalOrderResultTile<BitmapType>*>(result_tiles[t]);
auto cell_num =
fragment_metadata_[tile->frag_idx()]->cell_num(tile->tile_idx());
auto rc = GlobalOrderResultCoords(tile, 0);
std::vector<uint64_t> coords(dim_num);
tile->allocate_hilbert_vector();
for (rc.pos_ = 0; rc.pos_ < cell_num; rc.pos_++) {
// Process only values in bitmap.
if (!tile->has_bmp() || tile->bitmap()[rc.pos_]) {
// Compute Hilbert number for all dimensions first.
for (uint32_t d = 0; d < dim_num; ++d) {
auto dim{array_schema_.dimension_ptr(d)};
coords[d] = hilbert_order::map_to_uint64(
*dim, rc, d, bits, max_bucket_val);
}
// Now we are ready to get the final number.
tile->set_hilbert_value(rc.pos_, h.coords_to_hilbert(&coords[0]));
}
}
return Status::Ok();
}));
}
template <class BitmapType>
void SparseGlobalOrderReader<BitmapType>::update_frag_idx(
GlobalOrderResultTile<BitmapType>* tile, uint64_t c) {
auto& frag_idx = read_state_.frag_idx()[tile->frag_idx()];
auto t = tile->tile_idx();
if ((t == frag_idx.tile_idx_ && c > frag_idx.cell_idx_) ||
t > frag_idx.tile_idx_) {
read_state_.set_frag_idx(tile->frag_idx(), FragIdx(t, c));
}
}
template <class BitmapType>
template <class CompType>
tuple<bool, std::vector<ResultCellSlab>>
SparseGlobalOrderReader<BitmapType>::merge_result_cell_slabs(
uint64_t num_cells, std::vector<ResultTilesList>& result_tiles) {
auto timer_se = stats_->start_timer("merge_result_cell_slabs");
// User gave us some empty buffers, exit.
if (num_cells == 0) {
return {true, std::vector<ResultCellSlab>()};
}
std::vector<ResultCellSlab> result_cell_slabs;
CompType cmp_max_slab_length(
array_schema_.domain(), false, false, &fragment_metadata_);
// TODO Parallelize.
// For easy reference.
const bool return_all_dups =
array_schema_.allows_dups() || consolidation_with_timestamps_;
// A tile min heap, contains one GlobalOrderResultCoords per fragment.
std::vector<GlobalOrderResultCoords<BitmapType>> container;
container.reserve(result_tiles.size());
CompType cmp(
array_schema_.domain(),
!array_schema_.allows_dups(),
true,
&fragment_metadata_);
TileMinHeap<CompType> tile_queue(cmp, std::move(container));
// If any fragments needs to load more tiles.
bool need_more_tiles = false;
// Tile iterators, per fragments.
std::vector<TileListIt> rt_it(result_tiles.size());
// For all fragments, get the first tile in the sorting queue.
std::vector<TileListIt> to_delete;
throw_if_not_ok(parallel_for(
&resources_.compute_tp(), 0, result_tiles.size(), [&](uint64_t f) {
if (result_tiles[f].size() > 0) {
// Initialize the iterator for this fragment.
rt_it[f] = result_tiles[f].begin();
// Add the tile to the queue.
uint64_t cell_idx =
read_state_.frag_idx()[f].tile_idx_ == rt_it[f]->tile_idx() ?
read_state_.frag_idx()[f].cell_idx_ :
0;
GlobalOrderResultCoords rc(&*(rt_it[f]), cell_idx);
bool res = add_next_cell_to_queue(
rc, rt_it, result_tiles, tile_queue, to_delete);
{
std::unique_lock<std::mutex> ul(tile_queue_mutex_);
need_more_tiles |= res;
}
}
return Status::Ok();
}));
const bool non_overlapping_ranges = std::is_same<BitmapType, uint8_t>::value;
// Process all elements.
bool user_buffers_full = false;
while (!tile_queue.empty() && !need_more_tiles && num_cells > 0) {
auto to_process = tile_queue.top();
auto tile = to_process.tile_;
tile_queue.pop();
// Used only for purge delete condolidation.
bool stop_creating_slabs = false;
// Process all cells with the same coordinates at once.
bool deleted_dups = false;
while (!tile_queue.empty() && to_process.same_coords(tile_queue.top()) &&
num_cells > 0) {
// For consolidation with deletes, check if the cell was deleted and
// stop copying if it is. All cells after this in the queue have a
// smaller timestamp so they should be deleted.
if (purge_deletes_no_dups_mode_) {
stop_creating_slabs |= tile->post_dedup_bitmap()[to_process.pos_] == 0;
}
if (return_all_dups && !stop_creating_slabs) {
// If we return duplicates, create one slab for all the dups.
if (non_overlapping_ranges) {
if (!purge_deletes_no_dups_mode_ ||
tile->post_dedup_bitmap()[to_process.pos_] != 0) {
tile->set_used();
result_cell_slabs.emplace_back(tile, to_process.pos_, 1);
num_cells--;
}
} else {
// For overlapping ranges, create as many slabs as there are counts.
auto num = tile->post_dedup_bitmap()[to_process.pos_];
if (num_cells < num) {
num_cells = 0;
break;
}
if (num > 0) {
tile->set_used();
}
for (uint64_t i = 0; i < num; i++) {
result_cell_slabs.emplace_back(tile, to_process.pos_, 1);
num_cells--;
}
}