forked from man-group/ArcticDB
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclause.cpp
More file actions
2860 lines (2671 loc) · 144 KB
/
Copy pathclause.cpp
File metadata and controls
2860 lines (2671 loc) · 144 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
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
/* Copyright 2026 Man Group Operations Limited
*
* Use of this software is governed by the Business Source License 1.1 included in the file licenses/BSL.txt.
*
* As of the Change Date specified in that file, in accordance with the Business Source License, use of this software
* will be governed by the Apache License, version 2.0.
*/
#include <vector>
#include <variant>
#include <arcticdb/processing/processing_unit.hpp>
#include <arcticdb/column_store/segment_reslicer.hpp>
#include <arcticdb/column_store/string_pool.hpp>
#include <arcticdb/util/offset_string.hpp>
#include <arcticdb/stream/merge.hpp>
#include <arcticdb/processing/clause.hpp>
#include <arcticdb/pipeline/column_name_resolution.hpp>
#include <arcticdb/pipeline/column_stats.hpp>
#include <arcticdb/pipeline/frame_slice.hpp>
#include <arcticdb/pipeline/query.hpp>
#include <arcticdb/util/test/random_throw.hpp>
#include <ankerl/unordered_dense.h>
#include <arcticdb/util/movable_priority_queue.hpp>
#include <arcticdb/stream/merge_utils.hpp>
#include <arcticdb/processing/unsorted_aggregation.hpp>
#include <arcticdb/stream/index.hpp>
#include <arcticdb/pipeline/slicing.hpp>
#include <arcticdb/storage/store.hpp>
#include <arcticdb/stream/stream_sink.hpp>
#include <arcticdb/version/schema_checks.hpp>
#include <arcticdb/pipeline/frame_utils.hpp>
#include <arcticdb/util/collection_utils.hpp>
#include <boost/regex.hpp>
#include <ranges>
namespace {
using namespace arcticdb;
/// Remove all row slice entities and ranges and keys whose indexes do not appear in row_slices_to_keep
/// @param offsets Must be structured by row slice with ranges and keys
/// @param ranges_and_keys Must be structured by row slice with offsets
void filter_selected_ranges_and_keys_and_reindex_entities(
const std::span<const size_t> row_slices_to_keep, std::vector<std::vector<size_t>>& offsets,
std::vector<RangesAndKey>& ranges_and_keys
) {
ARCTICDB_DEBUG_CHECK(
ErrorCode::E_ASSERTION_FAILURE,
std::ranges::adjacent_find(row_slices_to_keep, std::ranges::greater_equal{}) == row_slices_to_keep.end(),
"Elements of rows slices to keep must be sorted and unique"
);
std::vector<std::vector<size_t>> new_offsets;
new_offsets.reserve(row_slices_to_keep.size());
for (const size_t row_slice_to_keep : row_slices_to_keep) {
new_offsets.emplace_back(std::move(offsets[row_slice_to_keep]));
}
offsets = std::move(new_offsets);
size_t new_entity_id = 0;
std::vector<RangesAndKey> new_ranges_and_keys;
new_ranges_and_keys.reserve(ranges_and_keys.size());
for (std::span<size_t> row_slice : offsets) {
for (size_t& entity_id : row_slice) {
new_ranges_and_keys.emplace_back(std::move(ranges_and_keys[entity_id]));
entity_id = new_entity_id++;
}
}
ranges_and_keys = std::move(new_ranges_and_keys);
}
template<typename TDT>
requires util::instantiation_of<TDT, TypeDescriptorTag>
position_t write_py_string_to_pool_or_throw(
PyObject* const py_string_object, const size_t row_in_segment, const RowRange& row_range,
std::optional<ScopedGILLock>& gil_lock, StringPool& new_string_pool, const std::string_view column_name
) {
return util::variant_match(
add_py_string_to_pool<TDT::data_type()>(py_string_object, gil_lock, new_string_pool),
[](position_t offset) { return offset; },
[&](convert::StringEncodingError&& err) -> position_t {
err.row_index_in_slice_ = row_in_segment;
err.raise(column_name, row_range.first);
}
);
}
template<typename TDT>
requires util::instantiation_of<TDT, TypeDescriptorTag>
void rebuild_sequence_column_in_new_pool(
Column& target_column, const StringPool& old_string_pool, StringPool& new_string_pool,
const util::BitSet* rows_to_add_in_new_pool = nullptr
) {
if (rows_to_add_in_new_pool) {
ColumnData target_column_data = target_column.data();
auto accessor = random_accessor<TDT>(&target_column_data);
for (auto row = rows_to_add_in_new_pool->first(); row != rows_to_add_in_new_pool->end(); ++row) {
if (is_a_string(accessor[*row])) {
const std::string_view string_value = old_string_pool.get_const_view(accessor[*row]);
const OffsetString& new_offset = new_string_pool.get(string_value);
accessor[*row] = new_offset.offset();
}
}
} else {
arcticdb::for_each<TDT>(target_column, [&](auto& value) {
if (is_a_string(value)) {
const std::string_view string_value = old_string_pool.get_const_view(value);
const OffsetString& new_offset = new_string_pool.get(string_value);
value = new_offset.offset();
}
});
}
}
/// When merge update is performed on a string column the string pool is rebuild from scratch, thus we must iterate over
/// all rows in the column. When the column is a part of a timeseries all target rows stored in rows_to_update will be
/// ordered (i.e. sorted(flatten(rows_to_update)) = true). This means we can iterate over the target column row and
/// at the same time forward iterate on the source rows. It's a nested loop but the complexity is O(n + m + k)
/// where n is the total number of rows in the target, m are the rows in the source, and k are the total matches between
/// source and target (i.e. sum(rows_to_update[i] for i in range(len(rows_to_update))))
template<typename TDT>
requires util::instantiation_of<TDT, TypeDescriptorTag>
bool merge_update_string_column_timeseries(
Column& target_column, const std::span<const std::vector<size_t>> rows_to_update, const Field& target_field,
const RowRange& row_range, const StringPool& target_string_pool,
const std::span<PyObject* const> source_column_view, StringPool& new_string_pool
) {
bool is_column_changed = false;
if constexpr (is_fixed_string_type(TDT::data_type())) {
user_input::raise<ErrorCode::E_INVALID_USER_ARGUMENT>(
"Fixed string sequences are not supported for merge update"
);
} else if constexpr (is_dynamic_string_type(TDT::data_type())) {
// GIL will be acquired if there is a string that is not pure ASCII/UTF-8
// In this case a PyObject will be allocated by convert::py_unicode_to_buffer
// If such a string is encountered in a column, then the GIL will be held until that whole column has
// been processed, on the assumption that if a column has one such string it will probably have many.
std::optional<ScopedGILLock> gil_lock;
// TODO: Insert support is not implemented for string columns in merge update. When a source row
// has no match in the target, a new row should be created in the target column.
auto source_row_it = rows_to_update.begin();
auto next_target_row_to_update = source_row_it->begin();
// TODO: Handle sparse target columns. When the target column is sparse, unset rows are skipped by
// for_each_enumerated, so matched source rows targeting sparse positions will not be updated.
arcticdb::for_each_enumerated<TDT>(target_column, [&](auto row) {
source_row_it = std::find_if(
source_row_it,
rows_to_update.end(),
[&, new_row = false](const std::vector<size_t>& vec) mutable {
// TODO: Handle inserts. An empty vec means the source row has no match and should
// be inserted into the target.
next_target_row_to_update = std::find_if(
new_row ? vec.begin() : next_target_row_to_update,
vec.end(),
[&](const int64_t target_row_to_update) { return target_row_to_update >= row.idx(); }
);
if (next_target_row_to_update == vec.end()) {
new_row = true;
}
return next_target_row_to_update != vec.end();
}
);
const bool current_target_row_is_matched = source_row_it != rows_to_update.end() &&
next_target_row_to_update != source_row_it->end() &&
static_cast<int64_t>(*next_target_row_to_update) == row.idx();
if (current_target_row_is_matched) {
is_column_changed = true;
const auto py_string_object = source_column_view[source_row_it - rows_to_update.begin()];
row.value() = write_py_string_to_pool_or_throw<TDT>(
py_string_object, row.idx(), row_range, gil_lock, new_string_pool, target_field.name()
);
} else {
if (is_a_string(row.value())) {
const std::string_view string_in_target = target_string_pool.get_const_view(row.value());
const OffsetString offset_in_new_pool = new_string_pool.get(string_in_target);
row.value() = offset_in_new_pool.offset();
}
}
});
}
return is_column_changed;
}
/// When merge update is performed on a string column the string pool is rebuild from scratch, thus we must iterate over
/// all rows in the column. When the column is *not* part of a timeseries the rows in rows_to_update are in random
/// order. To avoid having quadratic complexity (i.e. O(n * k) where n are the rows in the target and k are all matches
/// i.e. sum(rows_to_update[i] for i in range(len(rows_to_update)))) we invert the loops and iterate over all
/// rows_to_update perform the update and then add additional loop over all rows in target to rebuild the string pool.
/// Asymptotically this will yield the same complexity as the timeseries case but practically is a bit slower.
template<typename TDT>
requires util::instantiation_of<TDT, TypeDescriptorTag>
bool merge_update_string_column_rowrange(
Column& target_column, const std::span<const std::vector<size_t>> rows_to_update, const Field& target_field,
const RowRange& row_range, const StringPool& target_string_pool,
const std::span<PyObject* const> source_column_view, StringPool& new_string_pool
) {
bool is_column_changed = false;
if constexpr (is_fixed_string_type(TDT::data_type())) {
user_input::raise<ErrorCode::E_INVALID_USER_ARGUMENT>(
"Fixed string sequences are not supported for merge update"
);
} else if constexpr (is_dynamic_string_type(TDT::data_type())) {
util::BitSet target_rows_not_matched_by_source(target_column.row_count());
// GIL will be acquired if there is a string that is not pure ASCII/UTF-8
// In this case a PyObject will be allocated by convert::py_unicode_to_buffer
// If such a string is encountered in a column, then the GIL will be held until that whole column has
// been processed, on the assumption that if a column has one such string it will probably have many.
std::optional<ScopedGILLock> gil_lock;
ColumnData target_column_data = target_column.data();
auto target_column_accessor = random_accessor<TDT>(&target_column_data);
for (size_t source_row = 0; source_row < rows_to_update.size(); ++source_row) {
for (size_t target_row : rows_to_update[source_row]) {
const auto py_string_object = source_column_view[source_row];
target_column_accessor[target_row] = write_py_string_to_pool_or_throw<TDT>(
py_string_object, target_row, row_range, gil_lock, new_string_pool, target_field.name()
);
is_column_changed = true;
target_rows_not_matched_by_source.set(target_row);
}
}
target_rows_not_matched_by_source.flip();
rebuild_sequence_column_in_new_pool<TDT>(
target_column, target_string_pool, new_string_pool, &target_rows_not_matched_by_source
);
}
return is_column_changed;
}
struct MergeUpdateStringColumnFlags {
/// The column is part of a timeseries dataframe
bool is_timeseries = false;
/// Only move the data to a new string pool.
bool data_not_changed = false;
};
template<typename TDT>
requires util::instantiation_of<TDT, TypeDescriptorTag>
bool merge_update_string_column(
Column& target_column, const MergeUpdateStringColumnFlags& flags,
const std::span<const std::vector<size_t>> rows_to_update, const Field& target_field, const RowRange& row_range,
const StringPool& target_string_pool, const std::span<PyObject* const> source_column_view,
StringPool& new_string_pool
) {
if (flags.data_not_changed) {
rebuild_sequence_column_in_new_pool<TDT>(target_column, target_string_pool, new_string_pool);
return false;
} else {
if (flags.is_timeseries) {
return merge_update_string_column_timeseries<TDT>(
target_column,
rows_to_update,
target_field,
row_range,
target_string_pool,
source_column_view,
new_string_pool
);
} else {
return merge_update_string_column_rowrange<TDT>(
target_column,
rows_to_update,
target_field,
row_range,
target_string_pool,
source_column_view,
new_string_pool
);
}
}
}
struct NaNAwareFloatComparator {
template<std::floating_point T>
bool operator()(const T a, const T b) const {
return a == b || (std::isnan(a) && std::isnan(b));
}
};
struct NaNAwareFloatHasher {
using is_avalanching = void;
template<std::floating_point T>
uint64_t operator()(const T a) const {
if (std::isnan(a)) {
// IEEE allows multiple different bit representations of NaN. std::isnan is required to return true for all
// different bit bit representations of NaN, std::quient_NaN is an implementation defined constant.
return ankerl::unordered_dense::hash<T>()(std::numeric_limits<T>::quiet_NaN());
} else {
return std::hash<T>()(a);
}
}
};
template<
typename SourceTDT, typename TargetTDT, typename SourceValueRawType = TargetTDT::DataTypeTag::raw_type,
typename TargetValueRawType = TargetTDT::DataTypeTag::raw_type>
requires std::same_as<std::decay_t<SourceTDT>, std::decay_t<TargetTDT>>
std::variant<bool, convert::StringEncodingError> are_merge_values_matching(
const SourceValueRawType& source_value, const TargetValueRawType& target_value,
const StringPool& target_string_pool, std::optional<ScopedGILLock>& scoped_gil_lock
) {
if constexpr (is_sequence_type(SourceTDT::data_type())) {
const bool is_source_null = is_py_none(source_value) || is_py_nan(source_value);
const bool is_target_null = !is_a_string(target_value);
if (is_source_null ^ is_target_null) {
return false;
} else if (is_source_null && is_target_null) {
return true;
} else {
return util::variant_match(
create_py_object_wrapper_or_error<TargetTDT::data_type()>(source_value, scoped_gil_lock),
[](convert::StringEncodingError&& err) -> std::variant<bool, convert::StringEncodingError> {
return err;
},
[&](convert::PyStringWrapper&& wrapper) -> std::variant<bool, convert::StringEncodingError> {
return target_string_pool.get_const_view(target_value) ==
std::string_view(wrapper.buffer_, wrapper.length_);
}
);
}
} else if constexpr (is_floating_point_type(SourceTDT::data_type())) {
constexpr static NaNAwareFloatComparator comparator;
return comparator(source_value, target_value);
} else {
return source_value == target_value;
}
}
template<typename TDT>
requires util::instantiation_of<TDT, TypeDescriptorTag>
auto map_column_values_to_rows(const ColumnWithStrings& column) {
constexpr static bool is_target_sequence_type = is_sequence_type(TDT::data_type());
constexpr static bool is_target_floating_point_type = is_floating_point_type(TDT::data_type());
using TargetRawType = typename TDT::DataTypeTag::raw_type;
using TargetValueType = std::conditional_t<is_target_sequence_type, std::optional<std::string_view>, TargetRawType>;
using Hasher = std::conditional_t<
is_target_floating_point_type,
NaNAwareFloatHasher,
ankerl::unordered_dense::hash<TargetValueType>>;
using Comparator =
std::conditional_t<is_target_floating_point_type, NaNAwareFloatComparator, std::equal_to<TargetValueType>>;
ankerl::unordered_dense::map<TargetValueType, std::vector<size_t>, Hasher, Comparator> target_values;
arcticdb::for_each_enumerated<TDT>(*column.column_, [&](auto row) {
if constexpr (is_target_sequence_type) {
if (is_a_string(row.value())) {
target_values[column.string_at_offset(row.value())].push_back(row.idx());
} else {
target_values[std::nullopt].push_back(row.idx());
}
} else {
target_values[row.value()].push_back(row.idx());
}
});
return target_values;
}
} // namespace
namespace arcticdb {
namespace ranges = std::ranges;
using namespace pipelines;
class GroupingMap {
using NumericMapType = std::variant<
std::monostate, std::shared_ptr<ankerl::unordered_dense::map<bool, size_t>>,
std::shared_ptr<ankerl::unordered_dense::map<uint8_t, size_t>>,
std::shared_ptr<ankerl::unordered_dense::map<uint16_t, size_t>>,
std::shared_ptr<ankerl::unordered_dense::map<uint32_t, size_t>>,
std::shared_ptr<ankerl::unordered_dense::map<uint64_t, size_t>>,
std::shared_ptr<ankerl::unordered_dense::map<int8_t, size_t>>,
std::shared_ptr<ankerl::unordered_dense::map<int16_t, size_t>>,
std::shared_ptr<ankerl::unordered_dense::map<int32_t, size_t>>,
std::shared_ptr<ankerl::unordered_dense::map<int64_t, size_t>>,
std::shared_ptr<ankerl::unordered_dense::map<float, size_t>>,
std::shared_ptr<ankerl::unordered_dense::map<double, size_t>>>;
NumericMapType map_;
public:
size_t size() const {
return util::variant_match(
map_, [](const std::monostate&) { return size_t(0); }, [](const auto& other) { return other->size(); }
);
}
template<typename T>
std::shared_ptr<ankerl::unordered_dense::map<T, size_t>> get() {
ARCTICDB_DEBUG_THROW(5)
return util::variant_match(
map_,
[that = this](const std::monostate&) {
that->map_ = std::make_shared<ankerl::unordered_dense::map<T, size_t>>();
return std::get<std::shared_ptr<ankerl::unordered_dense::map<T, size_t>>>(that->map_);
},
[](const std::shared_ptr<ankerl::unordered_dense::map<T, size_t>>& ptr) { return ptr; },
[](const auto&) -> std::shared_ptr<ankerl::unordered_dense::map<T, size_t>> {
schema::raise<ErrorCode::E_UNSUPPORTED_COLUMN_TYPE>(
"GroupBy does not support the grouping column type changing with dynamic schema"
);
}
);
}
};
struct SegmentWrapper {
SegmentInMemory seg_;
SegmentInMemory::iterator it_;
const StreamId id_;
explicit SegmentWrapper(SegmentInMemory&& seg) :
seg_(std::move(seg)),
it_(seg_.begin()),
id_(seg_.descriptor().id()) {}
bool advance() { return ++it_ != seg_.end(); }
SegmentInMemory::Row& row() { return *it_; }
const StreamId& id() const { return id_; }
};
static auto first_missing_column(OutputSchema& output_schema, const std::unordered_set<std::string>& required_columns) {
const auto& column_types = output_schema.column_types();
for (auto input_column_it = required_columns.begin(); input_column_it != required_columns.end();
++input_column_it) {
if (!column_types.contains(*input_column_it) &&
!column_types.contains(stream::mangled_name(*input_column_it))) {
return input_column_it;
}
}
return required_columns.end();
}
void check_column_presence(
OutputSchema& output_schema, const std::unordered_set<std::string>& required_columns,
std::string_view clause_name
) {
const auto first_missing = first_missing_column(output_schema, required_columns);
schema::check<ErrorCode::E_COLUMN_DOESNT_EXIST>(
first_missing == required_columns.end(),
"{}Clause requires column '{}' to exist in input data",
clause_name,
first_missing == required_columns.end() ? "" : *first_missing
);
}
void check_is_timeseries(const StreamDescriptor& stream_descriptor, std::string_view clause_name) {
schema::check<ErrorCode::E_UNSUPPORTED_INDEX_TYPE>(
stream_descriptor.index().type() == IndexDescriptor::Type::TIMESTAMP &&
stream_descriptor.index().field_count() >= 1 &&
stream_descriptor.field(0).type() == make_scalar_type(DataType::NANOSECONDS_UTC64),
"{}Clause can only be applied to timeseries",
clause_name
);
}
OutputSchema modify_schema(OutputSchema&& schema, const std::vector<std::shared_ptr<Clause>>& clauses) {
for (const auto& clause : clauses) {
schema = clause->modify_schema(std::move(schema));
}
return schema;
}
std::vector<EntityId> PassthroughClause::process(std::vector<EntityId>&& entity_ids) const {
return std::move(entity_ids);
}
std::vector<EntityId> FilterClause::process(std::vector<EntityId>&& entity_ids) const {
ARCTICDB_SAMPLE(FilterClause, 0)
if (entity_ids.empty()) {
return {};
}
auto proc = gather_entities<std::shared_ptr<SegmentInMemory>, std::shared_ptr<RowRange>, std::shared_ptr<ColRange>>(
*component_manager_, std::move(entity_ids)
);
proc.set_expression_context(expression_context_);
ARCTICDB_RUNTIME_DEBUG(log::memory(), "Doing filter {} for entity ids {}", root_node_name_, entity_ids);
auto variant_data = proc.get(root_node_name_);
std::vector<EntityId> output;
util::variant_match(
variant_data,
[&proc, &output, this](util::BitSet& bitset) {
if (bitset.count() > 0) {
proc.apply_filter(std::move(bitset), optimisation_);
output = push_entities(*component_manager_, std::move(proc));
} else {
log::memory().debug("Filter returned empty result");
}
},
[](EmptyResult) { log::memory().debug("Filter returned empty result"); },
[&output, &proc, this](FullResult) { output = push_entities(*component_manager_, std::move(proc)); },
[](const auto&) { util::raise_rte("Expected bitset from filter clause"); }
);
return output;
}
OutputSchema FilterClause::modify_schema(OutputSchema&& output_schema) const {
check_column_presence(output_schema, *clause_info_.input_columns_, "Filter");
auto root_expr = expression_context_->expression_nodes_.get_value(root_node_name_.value);
std::variant<BitSetTag, DataType> return_type =
root_expr->compute(*expression_context_, output_schema.column_types());
user_input::check<ErrorCode::E_INVALID_USER_ARGUMENT>(
std::holds_alternative<BitSetTag>(return_type), "FilterClause AST would produce a column, not a bitset"
);
return output_schema;
}
std::string FilterClause::to_string() const {
return expression_context_ ? fmt::format("WHERE {}", root_node_name_.value) : "";
}
std::vector<EntityId> ProjectClause::process(std::vector<EntityId>&& entity_ids) const {
ARCTICDB_DEBUG_THROW(5)
if (entity_ids.empty()) {
return {};
}
auto proc = gather_entities<std::shared_ptr<SegmentInMemory>, std::shared_ptr<RowRange>, std::shared_ptr<ColRange>>(
*component_manager_, std::move(entity_ids)
);
proc.set_expression_context(expression_context_);
auto variant_data = proc.get(expression_context_->root_node_name_);
std::vector<EntityId> output;
util::variant_match(
variant_data,
[&proc, &output, this](ColumnWithStrings& col) {
add_column(proc, col);
output = push_entities(*component_manager_, std::move(proc));
},
[&proc, &output, this](const std::shared_ptr<Value>& val) {
// It is possible for the AST to produce a Value, either through use of apply with a raw
// value, or through use of the ternary operator
// Turn this Value into a dense column where all of the entries are the same as this value,
// of the same length as the other segments in this processing unit
auto rows = proc.segments_->back()->row_count();
auto output_column = std::make_unique<Column>(val->descriptor(), Sparsity::PERMITTED);
auto output_bytes = rows * get_type_size(output_column->type().data_type());
output_column->allocate_data(output_bytes);
output_column->set_row_data(rows);
auto string_pool = std::make_shared<StringPool>();
details::visit_type(val->data_type(), [&](auto val_tag) {
using val_type_info = ScalarTypeInfo<decltype(val_tag)>;
if constexpr (is_dynamic_string_type(val_type_info::data_type)) {
using TargetType = val_type_info::RawType;
const auto offset = string_pool->get(*val->str_data(), val->len()).offset();
auto data = output_column->ptr_cast<TargetType>(0, output_bytes);
std::fill_n(data, rows, offset);
} else if constexpr (is_numeric_type(val_type_info::data_type) ||
is_bool_type(val_type_info::data_type)) {
using TargetType = val_type_info::RawType;
auto value = static_cast<TargetType>(val->get<typename val_type_info::RawType>());
auto data = output_column->ptr_cast<TargetType>(0, output_bytes);
std::fill_n(data, rows, value);
} else {
util::raise_rte("Unexpected Value type in ProjectClause: {}", val->data_type());
}
});
ColumnWithStrings col(std::move(output_column), string_pool, "");
add_column(proc, col);
output = push_entities(*component_manager_, std::move(proc));
},
[&proc, &output, this](const EmptyResult&) {
if (expression_context_->dynamic_schema_)
output = push_entities(*component_manager_, std::move(proc));
else
util::raise_rte("Cannot project from empty column with static schema");
},
[](const auto&) { util::raise_rte("Expected column from projection clause"); }
);
return output;
}
OutputSchema ProjectClause::modify_schema(OutputSchema&& output_schema) const {
check_column_presence(output_schema, *clause_info_.input_columns_, "Project");
util::variant_match(
expression_context_->root_node_name_,
[&](const ExpressionName& root_node_name) {
auto root_expr = expression_context_->expression_nodes_.get_value(root_node_name.value);
std::variant<BitSetTag, DataType> return_type =
root_expr->compute(*expression_context_, output_schema.column_types());
user_input::check<ErrorCode::E_INVALID_USER_ARGUMENT>(
std::holds_alternative<DataType>(return_type),
"ProjectClause AST would produce a bitset, not a column"
);
output_schema.add_field(output_column_, std::get<DataType>(return_type));
},
[&](const ValueName& root_node_name) {
output_schema.add_field(
output_column_,
expression_context_->values_.get_value(root_node_name.value)->descriptor().data_type()
);
},
[](const auto&) {
// Shouldn't make it here due to check in ctor
user_input::raise<ErrorCode::E_INVALID_USER_ARGUMENT>("ProjectClause AST would not produce a column");
}
);
return output_schema;
}
[[nodiscard]] std::string ProjectClause::to_string() const {
return expression_context_ ? fmt::format(
"PROJECT Column[\"{}\"] = {}",
output_column_,
std::holds_alternative<ExpressionName>(expression_context_->root_node_name_)
? std::get<ExpressionName>(expression_context_->root_node_name_).value
: std::get<ValueName>(expression_context_->root_node_name_).value
)
: "";
}
void ProjectClause::add_column(ProcessingUnit& proc, const ColumnWithStrings& col) const {
auto& last_segment = *proc.segments_->back();
auto seg = std::make_shared<SegmentInMemory>();
// Add in the same index fields as the last existing segment in proc
seg->descriptor().set_index(last_segment.descriptor().index());
for (uint32_t idx = 0; idx < last_segment.descriptor().index().field_count(); ++idx) {
seg->add_column(last_segment.field(idx), last_segment.column_ptr(idx));
}
// Add the column with its string pool and set the segment row data
seg->add_column(scalar_field(col.column_->type().data_type(), output_column_), col.column_);
seg->set_string_pool(col.string_pool_);
seg->set_row_data(last_segment.row_count() - 1);
// Calculate the row range and col range for the new segment
auto row_range = std::make_shared<RowRange>(*proc.row_ranges_->back());
auto last_col_idx = proc.col_ranges_->back()->second;
auto col_range = std::make_shared<ColRange>(last_col_idx, last_col_idx + 1);
proc.segments_->emplace_back(std::move(seg));
proc.row_ranges_->emplace_back(std::move(row_range));
proc.col_ranges_->emplace_back(std::move(col_range));
}
AggregationClause::AggregationClause(
const std::string& grouping_column, const std::vector<NamedAggregator>& named_aggregators
) :
grouping_column_(grouping_column) {
ARCTICDB_DEBUG_THROW(5)
clause_info_.input_structure_ = ProcessingStructure::HASH_BUCKETED;
clause_info_.can_combine_with_column_selection_ = false;
clause_info_.index_ = NewIndex(grouping_column_);
clause_info_.input_columns_ = std::make_optional<std::unordered_set<std::string>>({grouping_column_});
str_ = "AGGREGATE {";
for (const auto& named_aggregator : named_aggregators) {
str_.append(fmt::format(
"{}: ({}, {}), ",
named_aggregator.output_column_name_,
named_aggregator.input_column_name_,
named_aggregator.aggregation_operator_
));
clause_info_.input_columns_->insert(named_aggregator.input_column_name_);
auto typed_input_column_name = ColumnName(named_aggregator.input_column_name_);
auto typed_output_column_name = ColumnName(named_aggregator.output_column_name_);
if (named_aggregator.aggregation_operator_ == "sum") {
aggregators_.emplace_back(SumAggregatorUnsorted(typed_input_column_name, typed_output_column_name));
} else if (named_aggregator.aggregation_operator_ == "mean") {
aggregators_.emplace_back(MeanAggregatorUnsorted(typed_input_column_name, typed_output_column_name));
} else if (named_aggregator.aggregation_operator_ == "max") {
aggregators_.emplace_back(MaxAggregatorUnsorted(typed_input_column_name, typed_output_column_name));
} else if (named_aggregator.aggregation_operator_ == "min") {
aggregators_.emplace_back(MinAggregatorUnsorted(typed_input_column_name, typed_output_column_name));
} else if (named_aggregator.aggregation_operator_ == "count") {
aggregators_.emplace_back(CountAggregatorUnsorted(typed_input_column_name, typed_output_column_name));
} else {
user_input::raise<ErrorCode::E_INVALID_USER_ARGUMENT>(
"Unknown aggregation operator provided: {}", named_aggregator.aggregation_operator_
);
}
}
str_.append("}");
}
std::vector<std::vector<EntityId>> AggregationClause::structure_for_processing(
std::vector<std::vector<EntityId>>&& entity_ids_vec
) {
// Some could be empty, so actual number may be lower
auto max_num_buckets = ConfigsMap::instance()->get_int(
"Partition.NumBuckets", async::TaskScheduler::instance()->cpu_thread_count()
);
max_num_buckets = std::min(max_num_buckets, static_cast<int64_t>(std::numeric_limits<bucket_id>::max()));
// Preallocate results with expected sizes, erase later if any are empty
std::vector<std::vector<EntityId>> res(max_num_buckets);
// With an even distribution, expect each element of res to have entity_ids_vec.size() elements
for (auto& res_element : res) {
res_element.reserve(entity_ids_vec.size());
}
ARCTICDB_DEBUG_THROW(5)
// Experimentation shows flattening the entities into a single vector and a single call to
// component_manager_->get is faster than not flattening and making multiple calls
auto entity_ids = util::flatten_vectors(std::move(entity_ids_vec));
auto [buckets] = component_manager_->get_entities<bucket_id>(entity_ids);
for (auto [idx, entity_id] : folly::enumerate(entity_ids)) {
res[buckets[idx]].emplace_back(entity_id);
}
// Get rid of any empty buckets
std::erase_if(res, [](const std::vector<EntityId>& entity_ids) { return entity_ids.empty(); });
return res;
}
std::vector<EntityId> AggregationClause::process(std::vector<EntityId>&& entity_ids) const {
ARCTICDB_DEBUG_THROW(5)
ARCTICDB_SAMPLE(AggregationClause, 0)
if (entity_ids.empty()) {
return {};
}
auto proc = gather_entities<std::shared_ptr<SegmentInMemory>, std::shared_ptr<RowRange>, std::shared_ptr<ColRange>>(
*component_manager_, std::move(entity_ids)
);
auto row_slices = split_by_row_slice(std::move(proc));
// Sort procs following row range descending order, as we are going to iterate through them backwards
// front() is UB if vector is empty. Should be non-empty by construction, but exception > UB
internal::check<ErrorCode::E_ASSERTION_FAILURE>(
ranges::all_of(
row_slices,
[](const auto& proc) { return proc.row_ranges_.has_value() && !proc.row_ranges_->empty(); }
),
"Unexpected empty row_ranges_ in AggregationClause::process"
);
ranges::sort(row_slices, [](const auto& left, const auto& right) {
return left.row_ranges_->front()->start() > right.row_ranges_->front()->start();
});
internal::check<ErrorCode::E_INVALID_ARGUMENT>(
!aggregators_.empty(), "AggregationClause::process does not make sense with no aggregators"
);
std::vector<GroupingAggregatorData> aggregators_data;
aggregators_data.reserve(aggregators_.size());
ranges::transform(aggregators_, std::back_inserter(aggregators_data), [&](const auto& agg) {
return agg.get_aggregator_data();
});
// Work out the common type between the processing units for the columns being aggregated
for (auto& row_slice : row_slices) {
for (auto agg_data : folly::enumerate(aggregators_data)) {
// Check that segments row ranges are the same
internal::check<ErrorCode::E_ASSERTION_FAILURE>(
ranges::all_of(
*row_slice.row_ranges_,
[&](const auto& row_range) {
return row_range->start() == row_slice.row_ranges_->at(0)->start();
}
),
"Expected all data segments in one processing unit to have the same row ranges"
);
auto input_column_name = aggregators_.at(agg_data.index).get_input_column_name();
auto input_column = row_slice.get(input_column_name);
if (std::holds_alternative<ColumnWithStrings>(input_column)) {
agg_data->add_data_type(std::get<ColumnWithStrings>(input_column).column_->type().data_type());
}
}
}
size_t num_unique{0};
size_t next_group_id{0};
auto string_pool = std::make_shared<StringPool>();
DataType grouping_data_type;
GroupingMap grouping_map;
// Iterating backwards as we are going to erase from this vector as we go along
// This is to spread out deallocation of the input segments
auto it = row_slices.rbegin();
while (it != row_slices.rend()) {
auto& row_slice = *it;
auto partitioning_column = row_slice.get(ColumnName(grouping_column_));
if (std::holds_alternative<ColumnWithStrings>(partitioning_column)) {
ColumnWithStrings col = std::get<ColumnWithStrings>(partitioning_column);
details::visit_type(col.column_->type().data_type(), [&, this](auto data_type_tag) {
using col_type_info = ScalarTypeInfo<decltype(data_type_tag)>;
grouping_data_type = col_type_info::data_type;
// Faster to initialise to zero (missing value group) and use raw ptr than repeated calls to
// emplace_back
std::vector<size_t> row_to_group(col.column_->last_row() + 1, 0);
size_t* row_to_group_ptr = row_to_group.data();
auto hash_to_group = grouping_map.get<typename col_type_info::RawType>();
// For string grouping columns, keep a local map within this ProcessingUnit
// from offsets to groups, to avoid needless calls to col.string_at_offset and
// string_pool->get
// This could be slower in cases where there aren't many repeats in string
// grouping columns. Maybe track hit ratio of finds and stop using it if it is
// too low?
// Tested with 100,000,000 row dataframe with 100,000 unique values in the grouping column. Timings:
// 11.14 seconds without caching
// 11.01 seconds with caching
// Not worth worrying about right now
ankerl::unordered_dense::map<typename col_type_info::RawType, size_t> offset_to_group;
const bool is_sparse = col.column_->is_sparse();
if (is_sparse && next_group_id == 0) {
// We use 0 for the missing value group id
++next_group_id;
}
ssize_t previous_value_index = 0;
arcticdb::for_each_enumerated<typename col_type_info::TDT>(
*col.column_,
[&] ARCTICDB_LAMBDA_INLINE(auto enumerating_it) {
typename col_type_info::RawType val;
if constexpr (is_sequence_type(col_type_info::data_type)) {
auto offset = enumerating_it.value();
if (auto it = offset_to_group.find(offset); it != offset_to_group.end()) {
val = it->second;
} else {
std::optional<std::string_view> str = col.string_at_offset(offset);
if (str.has_value()) {
val = string_pool->get(*str, true).offset();
} else {
val = offset;
}
typename col_type_info::RawType val_copy(val);
offset_to_group.emplace(offset, val_copy);
}
} else {
val = enumerating_it.value();
}
if (is_sparse) {
for (auto j = previous_value_index; j != enumerating_it.idx(); ++j) {
static constexpr size_t missing_value_group_id = 0;
*row_to_group_ptr++ = missing_value_group_id;
}
previous_value_index = enumerating_it.idx() + 1;
}
if (auto it = hash_to_group->find(val); it == hash_to_group->end()) {
*row_to_group_ptr++ = next_group_id;
auto group_id = next_group_id++;
hash_to_group->emplace(val, group_id);
} else {
*row_to_group_ptr++ = it->second;
}
}
);
num_unique = next_group_id;
util::check(num_unique != 0, "Got zero unique values");
for (auto agg_data : folly::enumerate(aggregators_data)) {
auto input_column_name = aggregators_.at(agg_data.index).get_input_column_name();
auto input_column = row_slice.get(input_column_name);
std::optional<ColumnWithStrings> opt_input_column;
if (std::holds_alternative<ColumnWithStrings>(input_column)) {
auto column_with_strings = std::get<ColumnWithStrings>(input_column);
// Empty columns don't contribute to aggregations
if (!is_empty_type(column_with_strings.column_->type().data_type())) {
opt_input_column.emplace(std::move(column_with_strings));
}
}
if (opt_input_column) {
// The column is missing from the segment. Do not perform any aggregation and leave it to
// the NullValueReducer to take care of the default values.
agg_data->aggregate(*opt_input_column, row_to_group, num_unique);
}
}
});
} else {
util::raise_rte("Expected single column from expression");
}
it = static_cast<decltype(row_slices)::reverse_iterator>((row_slices.erase(std::next(it).base())));
}
SegmentInMemory seg;
auto index_col = std::make_shared<Column>(
make_scalar_type(grouping_data_type), grouping_map.size(), AllocationType::PRESIZED, Sparsity::NOT_PERMITTED
);
seg.add_column(scalar_field(grouping_data_type, grouping_column_), index_col);
seg.descriptor().set_index(IndexDescriptorImpl(IndexDescriptorImpl::Type::ROWCOUNT, 0));
details::visit_type(grouping_data_type, [&grouping_map, &index_col](auto data_type_tag) {
using col_type_info = ScalarTypeInfo<decltype(data_type_tag)>;
auto hashes = grouping_map.get<typename col_type_info::RawType>();
std::vector<std::pair<typename col_type_info::RawType, size_t>> elements;
for (const auto& hash : *hashes)
elements.emplace_back(hash.first, hash.second);
ranges::sort(
elements,
[](const std::pair<typename col_type_info::RawType, size_t>& l,
const std::pair<typename col_type_info::RawType, size_t>& r) { return l.second < r.second; }
);
auto column_data = index_col->data();
std::transform(
elements.cbegin(),
elements.cend(),
column_data.begin<typename col_type_info::TDT>(),
[](const auto& element) { return element.first; }
);
});
index_col->set_row_data(grouping_map.size() - 1);
for (auto agg_data : folly::enumerate(aggregators_data)) {
seg.concatenate(agg_data->finalize(
aggregators_.at(agg_data.index).get_output_column_name(), processing_config_.dynamic_schema_, num_unique
));
}
seg.set_string_pool(string_pool);
seg.set_row_id(num_unique - 1);
return push_entities(*component_manager_, ProcessingUnit(std::move(seg)));
}
OutputSchema AggregationClause::modify_schema(OutputSchema&& output_schema) const {
check_column_presence(output_schema, *clause_info_.input_columns_, "Aggregation");
output_schema.clear_default_values();
const auto& input_stream_desc = output_schema.stream_descriptor();
StreamDescriptor stream_desc(input_stream_desc.id());
stream_desc.add_field(input_stream_desc.field(*input_stream_desc.find_field(grouping_column_)));
stream_desc.set_index({IndexDescriptorImpl::Type::ROWCOUNT, 0});
for (const auto& agg : aggregators_) {
const auto& input_column_name = agg.get_input_column_name().value;
const auto& output_column_name = agg.get_output_column_name().value;
const auto& input_column_type = output_schema.column_types()[input_column_name];
auto agg_data = agg.get_aggregator_data();
agg_data.add_data_type(input_column_type);
const DataType output_column_type = agg_data.get_output_data_type();
stream_desc.add_scalar_field(output_column_type, output_column_name);
const std::optional<Value>& default_value = agg_data.get_default_value();
if (default_value) {
output_schema.set_default_value_for_column(output_column_name, *default_value);
}
}
output_schema.set_stream_descriptor(std::move(stream_desc));
auto mutable_index = output_schema.norm_metadata_.mutable_df()->mutable_common()->mutable_index();
mutable_index->set_name(grouping_column_);
mutable_index->clear_fake_name();
mutable_index->set_is_physically_stored(true);
return output_schema;
}
[[nodiscard]] std::string AggregationClause::to_string() const { return str_; }
template<ResampleBoundary closed_boundary>
ResampleClause<closed_boundary>::ResampleClause(
std::string rule, ResampleBoundary label_boundary, BucketGeneratorT&& generate_bucket_boundaries,
timestamp offset, ResampleOrigin origin
) :
rule_(std::move(rule)),
label_boundary_(label_boundary),
generate_bucket_boundaries_(std::move(generate_bucket_boundaries)),
offset_(offset),
origin_(std::move(origin)) {
clause_info_.input_structure_ = ProcessingStructure::TIME_BUCKETED;
clause_info_.can_combine_with_column_selection_ = false;
clause_info_.index_ = KeepCurrentTopLevelIndex();
}
template<ResampleBoundary closed_boundary>
const ClauseInfo& ResampleClause<closed_boundary>::clause_info() const {
return clause_info_;
}
template<ResampleBoundary closed_boundary>
void ResampleClause<closed_boundary>::set_component_manager(std::shared_ptr<ComponentManager> component_manager) {
component_manager_ = std::move(component_manager);
}
template<ResampleBoundary closed_boundary>
OutputSchema ResampleClause<closed_boundary>::modify_schema(OutputSchema&& output_schema) const {
check_is_timeseries(output_schema.stream_descriptor(), "Resample");
output_schema.clear_default_values();
check_column_presence(output_schema, *clause_info_.input_columns_, "Resample");
const auto& input_stream_desc = output_schema.stream_descriptor();
StreamDescriptor stream_desc(input_stream_desc.id());
stream_desc.add_field(input_stream_desc.field(0));
stream_desc.set_index(IndexDescriptorImpl(IndexDescriptor::Type::TIMESTAMP, 1));
for (const auto& agg : aggregators_) {
const auto& input_column_name = agg.get_input_column_name().value;
const auto& output_column_name = agg.get_output_column_name().value;
const auto& input_column_type = output_schema.column_types()[input_column_name];
agg.check_aggregator_supported_with_data_type(input_column_type);
auto output_column_type = agg.generate_output_data_type(input_column_type);
stream_desc.add_scalar_field(output_column_type, output_column_name);
const std::optional<Value>& default_value = agg.get_default_value(input_column_type);
if (default_value) {
output_schema.set_default_value_for_column(output_column_name, *default_value);
}
}
output_schema.set_stream_descriptor(std::move(stream_desc));
if (output_schema.norm_metadata_.df().common().has_multi_index()) {
const auto& multi_index = output_schema.norm_metadata_.mutable_df()->mutable_common()->multi_index();
auto name = multi_index.name();
auto tz = multi_index.tz();
bool fake_name{false};
for (auto pos : multi_index.fake_field_pos()) {
if (pos == 0) {
fake_name = true;
break;
}
}
auto mutable_index = output_schema.norm_metadata_.mutable_df()->mutable_common()->mutable_index();
mutable_index->set_tz(tz);
mutable_index->set_is_physically_stored(true);
mutable_index->set_name(name);
mutable_index->set_fake_name(fake_name);