-
Notifications
You must be signed in to change notification settings - Fork 190
Expand file tree
/
Copy pathversion_core.cpp
More file actions
3464 lines (3226 loc) · 175 KB
/
version_core.cpp
File metadata and controls
3464 lines (3226 loc) · 175 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 <arcticdb/version/version_core.hpp>
#include <arcticdb/column_store/column_algorithms.hpp>
#include <arcticdb/column_store/column_reslicer.hpp>
#include <column_stats.pb.h>
#include <arcticdb/stream/segment_aggregator.hpp>
#include <arcticdb/pipeline/write_frame.hpp>
#include <arcticdb/pipeline/slicing.hpp>
#include <arcticdb/pipeline/frame_utils.hpp>
#include <pipeline/frame_slice.hpp>
#include <arcticdb/codec/codec.hpp>
#include <folly/futures/FutureSplitter.h>
#include <folly/executors/InlineExecutor.h>
#include <arcticdb/pipeline/write_options.hpp>
#include <arcticdb/stream/index.hpp>
#include <arcticdb/pipeline/query.hpp>
#include <arcticdb/pipeline/read_pipeline.hpp>
#include <arcticdb/pipeline/column_stats_filter.hpp>
#include <arcticdb/async/task_scheduler.hpp>
#include <arcticdb/async/tasks.hpp>
#include <arcticdb/util/name_validation.hpp>
#include <arcticdb/stream/incompletes.hpp>
#include <arcticdb/pipeline/pipeline_context.hpp>
#include <arcticdb/pipeline/read_frame.hpp>
#include <arcticdb/pipeline/read_options.hpp>
#include <arcticdb/pipeline/column_mapping.hpp>
#include <arcticdb/stream/stream_sink.hpp>
#include <arcticdb/stream/schema.hpp>
#include <arcticdb/pipeline/index_writer.hpp>
#include <arcticdb/pipeline/index_utils.hpp>
#include <arcticdb/version/schema_checks.hpp>
#include <arcticdb/version/version_utils.hpp>
#include <arcticdb/entity/merge_descriptors.hpp>
#include <arcticdb/processing/component_manager.hpp>
#include <arcticdb/util/collection_utils.hpp>
#include <arcticdb/util/format_date.hpp>
#include <iterator>
#include <aws/core/utils/stream/ResponseStream.h>
namespace arcticdb::version_store {
[[nodiscard]] static ReadOptions defragmentation_read_options_generator(const WriteOptions& options) {
ReadOptions read_options;
read_options.set_dynamic_schema(options.dynamic_schema);
return read_options;
}
namespace ranges = std::ranges;
static void modify_descriptor(
const std::shared_ptr<pipelines::PipelineContext>& pipeline_context, const ReadOptions& read_options
) {
if (opt_false(read_options.force_strings_to_object()) || opt_false(read_options.force_strings_to_fixed()))
pipeline_context->orig_desc_ = pipeline_context->desc_;
auto& desc = *pipeline_context->desc_;
if (opt_false(read_options.force_strings_to_object())) {
auto& fields = desc.fields();
for (Field& field_desc : fields) {
if (field_desc.type().data_type() == DataType::ASCII_FIXED64)
set_data_type(DataType::ASCII_DYNAMIC64, field_desc.mutable_type());
if (field_desc.type().data_type() == DataType::UTF_FIXED64)
set_data_type(DataType::UTF_DYNAMIC64, field_desc.mutable_type());
}
} else if (opt_false(read_options.force_strings_to_fixed())) {
auto& fields = desc.fields();
for (Field& field_desc : fields) {
if (field_desc.type().data_type() == DataType::ASCII_DYNAMIC64)
set_data_type(DataType::ASCII_FIXED64, field_desc.mutable_type());
if (field_desc.type().data_type() == DataType::UTF_DYNAMIC64)
set_data_type(DataType::UTF_FIXED64, field_desc.mutable_type());
}
}
}
VersionedItem write_dataframe_impl(
const std::shared_ptr<Store>& store, VersionId version_id, const std::shared_ptr<InputFrame>& frame,
const WriteOptions& options, const std::shared_ptr<DeDupMap>& de_dup_map, bool sparsify_floats,
bool validate_index
) {
ARCTICDB_SUBSAMPLE_DEFAULT(WaitForWriteCompletion)
ARCTICDB_DEBUG(
log::version(),
"write_dataframe_impl stream_id: {} , version_id: {}, {} rows",
frame->desc().id(),
version_id,
frame->num_rows
);
auto atom_key_fut =
async_write_dataframe_impl(store, version_id, frame, options, de_dup_map, sparsify_floats, validate_index);
return {std::move(atom_key_fut).get()};
}
std::tuple<IndexPartialKey, SlicingPolicy> get_partial_key_and_slicing_policy(
const WriteOptions& options, const InputFrame& frame, VersionId version_id, bool validate_index
) {
if (version_id == 0) {
auto check_outcome = verify_symbol_key(frame.desc().id());
if (std::holds_alternative<Error>(check_outcome)) {
std::get<Error>(check_outcome).throw_error();
}
}
// Slice the frame according to the write options
auto slicing_arg = get_slicing_policy(options, frame);
auto partial_key = IndexPartialKey{frame.desc().id(), version_id};
if (validate_index && !index_is_not_timeseries_or_is_sorted_ascending(frame)) {
sorting::raise<ErrorCode::E_UNSORTED_DATA>(
"When calling write with validate_index enabled, input data must be sorted"
);
}
return std::make_tuple(partial_key, slicing_arg);
}
folly::Future<entity::AtomKey> async_write_dataframe_impl(
const std::shared_ptr<Store>& store, VersionId version_id, const std::shared_ptr<InputFrame>& frame,
const WriteOptions& options, const std::shared_ptr<DeDupMap>& de_dup_map, bool sparsify_floats,
bool validate_index
) {
ARCTICDB_SAMPLE(DoWrite, 0)
frame->set_bucketize_dynamic(options.bucketize_dynamic);
auto [partial_key, slicing_policy] =
get_partial_key_and_slicing_policy(options, *frame, version_id, validate_index);
return write_frame(std::move(partial_key), frame, slicing_policy, store, de_dup_map, sparsify_floats);
}
void sorted_data_check_append(const InputFrame& frame, index::IndexSegmentReader& index_segment_reader) {
if (!index_is_not_timeseries_or_is_sorted_ascending(frame)) {
sorting::raise<ErrorCode::E_UNSORTED_DATA>(
"When calling append with validate_index enabled, input data must be sorted"
);
}
sorting::check<ErrorCode::E_UNSORTED_DATA>(
!std::holds_alternative<stream::TimeseriesIndex>(frame.index) ||
index_segment_reader.tsd().sorted() == SortedValue::ASCENDING,
"When calling append with validate_index enabled, the existing data must be sorted"
);
}
folly::Future<AtomKey> async_append_impl(
const std::shared_ptr<Store>& store, const UpdateInfo& update_info, const std::shared_ptr<InputFrame>& frame,
const WriteOptions& options, bool validate_index, bool empty_types
) {
util::check(
update_info.previous_index_key_.has_value(), "Cannot append as there is no previous index key to append to"
);
const StreamId stream_id = frame->desc().id();
ARCTICDB_DEBUG(log::version(), "append stream_id: {} , version_id: {}", stream_id, update_info.next_version_id_);
auto index_segment_reader = index::get_index_reader(*(update_info.previous_index_key_), store);
bool bucketize_dynamic = index_segment_reader.bucketize_dynamic();
auto row_offset = index_segment_reader.tsd().total_rows();
util::check_rte(!index_segment_reader.is_pickled(), "Cannot append to pickled data");
frame->set_offset(static_cast<ssize_t>(row_offset));
fix_descriptor_mismatch_or_throw(APPEND, options.dynamic_schema, index_segment_reader, *frame, empty_types);
if (validate_index) {
sorted_data_check_append(*frame, index_segment_reader);
}
frame->set_bucketize_dynamic(bucketize_dynamic);
auto slicing_arg = get_slicing_policy(options, *frame);
return append_frame(
IndexPartialKey{stream_id, update_info.next_version_id_},
frame,
slicing_arg,
index_segment_reader,
store,
options.dynamic_schema,
options.ignore_sort_order
);
}
VersionedItem append_impl(
const std::shared_ptr<Store>& store, const UpdateInfo& update_info, const std::shared_ptr<InputFrame>& frame,
const WriteOptions& options, bool validate_index, bool empty_types
) {
ARCTICDB_SUBSAMPLE_DEFAULT(WaitForWriteCompletion)
auto version_key_fut = async_append_impl(store, update_info, frame, options, validate_index, empty_types);
auto versioned_item = VersionedItem(std::move(version_key_fut).get());
ARCTICDB_DEBUG(
log::version(),
"write_dataframe_impl stream_id: {} , version_id: {}",
versioned_item.symbol(),
update_info.next_version_id_
);
return versioned_item;
}
namespace {
bool is_before(const IndexRange& a, const IndexRange& b) { return a.start_ < b.start_; }
bool is_after(const IndexRange& a, const IndexRange& b) { return a.end_ > b.end_; }
void check_index_match(const Index& index, const IndexDescriptorImpl& desc) {
if (std::holds_alternative<TimeseriesIndex>(index))
util::check(
desc.type() == IndexDescriptor::Type::TIMESTAMP || desc.type() == IndexDescriptor::Type::EMPTY,
"Index mismatch, cannot update a non-timeseries-indexed frame with a timeseries"
);
else
util::check(
desc.type() == IndexDescriptorImpl::Type::ROWCOUNT,
"Index mismatch, cannot update a timeseries with a non-timeseries-indexed frame"
);
}
/// Represents all slices which are intersecting (but not overlapping) with range passed to update
/// First member is a vector of all segments intersecting with the first row-slice of the update range
/// Second member is a vector of all segments intersecting with the last row-slice of the update range
using IntersectingSegments = std::tuple<std::vector<SliceAndKey>, std::vector<SliceAndKey>>;
[[nodiscard]] folly::Future<IntersectingSegments> async_intersecting_segments(
std::shared_ptr<std::vector<SliceAndKey>> affected_keys, const IndexRange& front_range,
const IndexRange& back_range, VersionId version_id, const std::shared_ptr<Store>& store
) {
if (!front_range.specified_ && !back_range.specified_) {
return folly::makeFuture<IntersectingSegments>(IntersectingSegments{});
}
internal::check<ErrorCode::E_ASSERTION_FAILURE>(
front_range.specified_ && back_range.specified_,
"Both first and last index range of the update range must intersect with at least one of the slices in the "
"dataframe"
);
std::vector<folly::Future<SliceAndKey>> maybe_intersect_before_fut;
std::vector<folly::Future<SliceAndKey>> maybe_intersect_after_fut;
for (const auto& affected_slice_and_key : *affected_keys) {
const auto& affected_range = affected_slice_and_key.key().index_range();
if (intersects(affected_range, front_range) && !overlaps(affected_range, front_range) &&
is_before(affected_range, front_range)) {
maybe_intersect_before_fut.emplace_back(async_rewrite_partial_segment(
affected_slice_and_key, front_range, version_id, AffectedSegmentPart::START, store
));
}
if (intersects(affected_range, back_range) && !overlaps(affected_range, back_range) &&
is_after(affected_range, back_range)) {
maybe_intersect_after_fut.emplace_back(async_rewrite_partial_segment(
affected_slice_and_key, back_range, version_id, AffectedSegmentPart::END, store
));
}
}
return collectAll(
collectAll(maybe_intersect_before_fut)
.via(&async::io_executor())
.thenValueInline([store](auto&& maybe_intersect_before) {
return rollback_slices_on_quota_exceeded(
std::move(maybe_intersect_before), std::static_pointer_cast<StreamSink>(store)
);
}),
collectAll(maybe_intersect_after_fut)
.via(&async::io_executor())
.thenValueInline([store](auto&& maybe_intersect_after) {
return rollback_slices_on_quota_exceeded(
std::move(maybe_intersect_after), std::static_pointer_cast<StreamSink>(store)
);
})
)
.via(&async::cpu_executor())
.thenValue([store](auto&& try_before_and_after) -> folly::Future<IntersectingSegments> {
auto& [try_intersect_before, try_intersect_after] = try_before_and_after;
return rollback_batches_on_quota_exceeded(
{std::move(try_intersect_before), std::move(try_intersect_after)}, store
)
.via(&async::cpu_executor())
.thenValue([](auto&& batch) {
auto& intersect_before = batch[0];
auto& intersect_after = batch[1];
return IntersectingSegments{std::move(intersect_before), std::move(intersect_after)};
});
})
.via(&async::io_executor());
}
/// When segments are produced by the processing pipeline, some rows might be missing. Imagine a filter with the middle
/// rows filtered out. These slices cannot be put in an index key as the row slices in the index key must be contiguous.
/// This function adjusts the row slices so that there are no gaps.
/// @note The difference between this and adjust_slice_ranges is that this will not change the column slices. While
/// adjust_slice_ranges will change the column slices, making the first slice start from 0 even for timestamp-index
/// dataframes (which should have column range starting from 1 when being written to disk).
void compact_row_slices(std::span<SliceAndKey> slices) {
ARCTICDB_DEBUG_CHECK(
ErrorCode::E_ASSERTION_FAILURE,
ranges::adjacent_find(
slices,
[](const SliceAndKey& a, const SliceAndKey& b) {
return a > b || (a.slice().col_range != b.slice().col_range &&
a.slice().col_range.start() != b.slice().col_range.end());
}
) == slices.end(),
"SlicesAndKeys must be sorted by column slice and all column slices must be present"
);
size_t current_compacted_row = 0;
size_t previous_uncompacted_end = slices.empty() ? 0 : slices.front().slice().row_range.end();
size_t previous_col_slice_end = slices.empty() ? 0 : slices.front().slice().col_range.end();
for (SliceAndKey& slice : slices) {
// Aggregation clause performs aggregations in parallel for each group. Thus, it can produce several slices with
// the exact row_range and column_range. The ordering doesn't matter, but this must be taken into account so
// that the row slices are always increasing. The second condition in the "if" takes care of this scenario.
if (slice.slice().row_range.start() < previous_uncompacted_end &&
slice.slice().col_range.start() > previous_col_slice_end) {
current_compacted_row = 0;
}
previous_uncompacted_end = slice.slice().row_range.end();
const size_t rows_in_slice = slice.slice().row_range.diff();
slice.slice().row_range.first = current_compacted_row;
slice.slice().row_range.second = current_compacted_row + rows_in_slice;
current_compacted_row += rows_in_slice;
previous_col_slice_end = slice.slice().col_range.end();
}
}
bool is_fake_index_name(const arcticc::pb2::descriptors_pb2::NormalizationMetadata& normalization_metadata) {
const auto& common = normalization_metadata.has_df() ? normalization_metadata.df().common()
: normalization_metadata.series().common();
const bool is_fake_datetime_index_name = common.has_index() && common.index().fake_name();
const bool is_fake_mutliindex_name =
common.has_multi_index() &&
ranges::find(common.multi_index().fake_field_pos(), 0) != common.multi_index().fake_field_pos().end();
// We store "fakeness" in two separate places. If the dataframe/series was originally datetime indexed we will store
// it in the "index" protobuf message. If the dataframe was a multiindex we will store the positions of all fake
// names in the "multi_index" protobuf message and not touch the fake_name property of "index".
return is_fake_datetime_index_name || is_fake_mutliindex_name;
}
} // namespace
VersionedItem delete_range_impl(
const std::shared_ptr<Store>& store, const StreamId& stream_id, const UpdateInfo& update_info,
const UpdateQuery& query, const WriteOptions&&, bool dynamic_schema
) {
util::check(update_info.previous_index_key_.has_value(), "Cannot delete from non-existent symbol {}", stream_id);
util::check(std::holds_alternative<IndexRange>(query.row_filter), "Delete range requires index range argument");
const auto& index_range = std::get<IndexRange>(query.row_filter);
ARCTICDB_DEBUG(
log::version(),
"Delete range in versioned dataframe for stream_id: {} , version_id = {}",
stream_id,
update_info.next_version_id_
);
auto index_segment_reader = index::get_index_reader(update_info.previous_index_key_.value(), store);
util::check_rte(!index_segment_reader.is_pickled(), "Cannot delete date range of pickled data");
auto index = index_type_from_descriptor(index_segment_reader.tsd().as_stream_descriptor());
util::check(
std::holds_alternative<TimeseriesIndex>(index),
"Delete in range will not work as expected with a non-timeseries index"
);
std::vector<FilterQuery<index::IndexSegmentReader>> queries = build_update_query_filters<index::IndexSegmentReader>(
query.row_filter, index, index_range, dynamic_schema, index_segment_reader.bucketize_dynamic()
);
auto combined = combine_filter_functions(queries);
auto affected_keys = filter_index(index_segment_reader, std::move(combined));
std::vector<SliceAndKey> unaffected_keys;
std::set_difference(
std::begin(index_segment_reader),
std::end(index_segment_reader),
std::begin(affected_keys),
std::end(affected_keys),
std::back_inserter(unaffected_keys)
);
auto [intersect_before, intersect_after] = async_intersecting_segments(
std::make_shared<std::vector<SliceAndKey>>(affected_keys),
index_range,
index_range,
update_info.next_version_id_,
store
)
.get();
auto orig_filter_range = std::holds_alternative<std::monostate>(query.row_filter)
? get_query_index_range(index, index_range)
: query.row_filter;
size_t row_count = 0;
const std::array<std::vector<SliceAndKey>, 5> groups{
strictly_before(orig_filter_range, unaffected_keys),
std::move(intersect_before),
std::move(intersect_after),
strictly_after(orig_filter_range, unaffected_keys)
};
auto flattened_slice_and_keys = flatten_and_fix_rows(groups, row_count);
std::sort(std::begin(flattened_slice_and_keys), std::end(flattened_slice_and_keys));
auto version_key_fut = util::variant_match(
index,
[&index_segment_reader, &flattened_slice_and_keys, &stream_id, &update_info, &store, &row_count](auto idx) {
using IndexType = decltype(idx);
auto tsd = std::make_shared<TimeseriesDescriptor>(index_segment_reader.tsd().clone());
tsd->set_total_rows(row_count);
return pipelines::index::write_index<IndexType>(
*tsd,
std::move(flattened_slice_and_keys),
IndexPartialKey{stream_id, update_info.next_version_id_},
store
);
}
);
auto versioned_item = VersionedItem(std::move(version_key_fut).get());
ARCTICDB_DEBUG(log::version(), "updated stream_id: {} , version_id: {}", stream_id, update_info.next_version_id_);
return versioned_item;
}
void check_update_data_is_sorted(const InputFrame& frame, const index::IndexSegmentReader& index_segment_reader) {
bool is_time_series = std::holds_alternative<stream::TimeseriesIndex>(frame.index);
sorting::check<ErrorCode::E_UNSORTED_DATA>(
is_time_series, "When calling update, the input data must be a time series."
);
bool input_data_is_sorted =
frame.desc().sorted() == SortedValue::ASCENDING || frame.desc().sorted() == SortedValue::UNKNOWN;
// If changing this error message, the corresponding message in _normalization.py::restrict_data_to_date_range_only
// should also be updated
sorting::check<ErrorCode::E_UNSORTED_DATA>(
input_data_is_sorted, "When calling update, the input data must be sorted."
);
bool existing_data_is_sorted = index_segment_reader.sorted() == SortedValue::ASCENDING ||
index_segment_reader.sorted() == SortedValue::UNKNOWN;
sorting::check<ErrorCode::E_UNSORTED_DATA>(
existing_data_is_sorted, "When calling update, the existing data must be sorted."
);
}
struct UpdateRanges {
IndexRange front;
IndexRange back;
IndexRange original_index_range;
};
static UpdateRanges compute_update_ranges(
const FilterRange& row_filter, const InputFrame& update_frame, std::span<SliceAndKey> update_slice_and_keys
) {
return util::variant_match(
row_filter,
[&](std::monostate) -> UpdateRanges {
util::check(
std::holds_alternative<TimeseriesIndex>(update_frame.index),
"Update with row count index is not permitted"
);
if (update_slice_and_keys.empty()) {
// If there are no new keys, then we can't intersect with the existing data.
return UpdateRanges{{}, {}, update_frame.index_range};
}
return UpdateRanges{
update_slice_and_keys.front().key().index_range(),
update_slice_and_keys.back().key().index_range(),
update_frame.index_range
};
},
[&](const IndexRange& idx_range) { return UpdateRanges{idx_range, idx_range, idx_range}; },
[](const RowRange&) -> UpdateRanges {
util::raise_rte("Unexpected row_range in update query");
return {};
}
);
}
static void check_can_update(
const InputFrame& frame, const index::IndexSegmentReader& index_segment_reader, const UpdateInfo& update_info,
bool dynamic_schema, bool empty_types
) {
util::check(
update_info.previous_index_key_.has_value(),
"Cannot update as there is no previous index key to update into"
);
util::check_rte(!index_segment_reader.is_pickled(), "Cannot update pickled data");
check_index_match(frame.index, index_segment_reader.tsd().index());
const auto index_desc = index_segment_reader.tsd().index();
util::check(index::is_timeseries_index(index_desc), "Update not supported for non-timeseries indexes");
check_update_data_is_sorted(frame, index_segment_reader);
(void)check_and_mark_slices(index_segment_reader, false, std::nullopt);
fix_descriptor_mismatch_or_throw(UPDATE, dynamic_schema, index_segment_reader, frame, empty_types);
}
static std::shared_ptr<std::vector<SliceAndKey>> get_keys_affected_by_update(
const index::IndexSegmentReader& index_segment_reader, const InputFrame& frame, const UpdateQuery& query,
bool dynamic_schema
) {
std::vector<FilterQuery<index::IndexSegmentReader>> queries = build_update_query_filters<index::IndexSegmentReader>(
query.row_filter, frame.index, frame.index_range, dynamic_schema, index_segment_reader.bucketize_dynamic()
);
return std::make_shared<std::vector<SliceAndKey>>(
filter_index(index_segment_reader, combine_filter_functions(queries))
);
}
static std::vector<SliceAndKey> get_keys_not_affected_by_update(
const index::IndexSegmentReader& index_segment_reader, std::span<const SliceAndKey> affected_keys
) {
std::vector<SliceAndKey> unaffected_keys;
std::set_difference(
index_segment_reader.begin(),
index_segment_reader.end(),
affected_keys.begin(),
affected_keys.end(),
std::back_inserter(unaffected_keys)
);
return unaffected_keys;
}
static std::pair<std::vector<SliceAndKey>, size_t> get_slice_and_keys_for_update(
const UpdateRanges& update_ranges, std::span<const SliceAndKey> unaffected_keys,
std::span<const SliceAndKey> affected_keys, const IntersectingSegments& segments_intersecting_with_update_range,
std::vector<SliceAndKey>&& new_slice_and_keys
) {
const size_t new_keys_size = new_slice_and_keys.size();
size_t row_count = 0;
const std::array<std::vector<SliceAndKey>, 5> groups{
strictly_before(update_ranges.original_index_range, unaffected_keys),
std::move(std::get<0>(segments_intersecting_with_update_range)),
std::move(new_slice_and_keys),
std::move(std::get<1>(segments_intersecting_with_update_range)),
strictly_after(update_ranges.original_index_range, unaffected_keys)
};
auto flattened_slice_and_keys = flatten_and_fix_rows(groups, row_count);
util::check(
unaffected_keys.size() + new_keys_size + (affected_keys.size() * 2) >= flattened_slice_and_keys.size(),
"Output size mismatch: {} + {} + (2 * {}) < {}",
unaffected_keys.size(),
new_keys_size,
affected_keys.size(),
flattened_slice_and_keys.size()
);
std::sort(std::begin(flattened_slice_and_keys), std::end(flattened_slice_and_keys));
return {flattened_slice_and_keys, row_count};
}
folly::Future<AtomKey> async_update_impl(
const std::shared_ptr<Store>& store, const UpdateInfo& update_info, const UpdateQuery& query,
const std::shared_ptr<InputFrame>& frame, WriteOptions&& options, bool dynamic_schema, bool empty_types
) {
return index::async_get_index_reader(*(update_info.previous_index_key_), store)
.thenValue([store, update_info, query, frame, options = std::move(options), dynamic_schema, empty_types](
index::IndexSegmentReader&& index_segment_reader
) {
check_can_update(*frame, index_segment_reader, update_info, dynamic_schema, empty_types);
ARCTICDB_DEBUG(
log::version(),
"Update versioned dataframe for stream_id: {} , version_id = {}",
frame->desc().id(),
update_info.previous_index_key_->version_id()
);
frame->set_bucketize_dynamic(index_segment_reader.bucketize_dynamic());
return slice_and_write(
frame,
get_slicing_policy(options, *frame),
IndexPartialKey{frame->desc().id(), update_info.next_version_id_},
store
)
.via(&async::cpu_executor())
.thenValue([store,
update_info,
query,
frame,
dynamic_schema,
index_segment_reader = std::move(index_segment_reader
)](std::vector<SliceAndKey>&& new_slice_and_keys) mutable {
std::sort(std::begin(new_slice_and_keys), std::end(new_slice_and_keys));
auto affected_keys =
get_keys_affected_by_update(index_segment_reader, *frame, query, dynamic_schema);
auto unaffected_keys =
get_keys_not_affected_by_update(index_segment_reader, *affected_keys);
util::check(
affected_keys->size() + unaffected_keys.size() == index_segment_reader.size(),
"The sum of affected keys and unaffected keys must be "
"equal to the total number of "
"keys {} + {} != {}",
affected_keys->size(),
unaffected_keys.size(),
index_segment_reader.size()
);
const UpdateRanges update_ranges =
compute_update_ranges(query.row_filter, *frame, new_slice_and_keys);
auto new_slice_and_keys_ptr =
std::make_shared<std::vector<SliceAndKey>>(std::move(new_slice_and_keys));
return async_intersecting_segments(
affected_keys,
update_ranges.front,
update_ranges.back,
update_info.next_version_id_,
store
)
.thenValue([new_slice_and_keys_ptr,
update_ranges = update_ranges,
unaffected_keys = std::move(unaffected_keys),
affected_keys = std::move(affected_keys),
index_segment_reader = std::move(index_segment_reader),
frame,
dynamic_schema,
update_info,
store](IntersectingSegments&& intersecting_segments) mutable {
auto [flattened_slice_and_keys, row_count] = get_slice_and_keys_for_update(
update_ranges,
unaffected_keys,
*affected_keys,
std::move(intersecting_segments),
std::move(*new_slice_and_keys_ptr)
);
auto tsd = index::get_merged_tsd(
row_count, dynamic_schema, index_segment_reader.tsd(), frame
);
return index::write_index(
index_type_from_descriptor(tsd.as_stream_descriptor()),
std::move(tsd),
std::move(flattened_slice_and_keys),
IndexPartialKey{frame->desc().id(), update_info.next_version_id_},
store
);
})
.thenError([store,
new_slice_and_keys_ptr](folly::exception_wrapper&& error) mutable {
if (error.template is_compatible_with<QuotaExceededException>()) {
return remove_slice_and_keys(std::move(*new_slice_and_keys_ptr), *store)
.thenTry([error](auto&&) {
return folly::makeSemiFuture<AtomKeyImpl>(error);
});
}
return folly::makeFuture<AtomKeyImpl>(error);
});
});
});
}
VersionedItem update_impl(
const std::shared_ptr<Store>& store, const UpdateInfo& update_info, const UpdateQuery& query,
const std::shared_ptr<InputFrame>& frame, WriteOptions&& options, bool dynamic_schema, bool empty_types
) {
auto versioned_item = VersionedItem(
async_update_impl(store, update_info, query, frame, std::move(options), dynamic_schema, empty_types).get()
);
ARCTICDB_DEBUG(
log::version(), "updated stream_id: {} , version_id: {}", frame->desc().id(), update_info.next_version_id_
);
return versioned_item;
}
folly::Future<ReadVersionOutput> read_multi_key(
const std::shared_ptr<Store>& store, const ReadOptions& read_options, const SegmentInMemory& index_key_seg,
std::shared_ptr<std::any> handler_data, AtomKey&& key
) {
std::vector<AtomKey> keys;
keys.reserve(index_key_seg.row_count());
for (size_t idx = 0; idx < index_key_seg.row_count(); idx++) {
keys.emplace_back(read_key_row(index_key_seg, static_cast<ssize_t>(idx)));
}
AtomKey dup{keys[0]};
VersionedItem versioned_item{std::move(dup)};
TimeseriesDescriptor multi_key_desc{index_key_seg.index_descriptor()};
return read_frame_for_version(store, versioned_item, std::make_shared<ReadQuery>(), read_options, handler_data)
.thenValue([multi_key_desc = std::move(multi_key_desc),
keys = std::move(keys),
key = std::move(key)](ReadVersionOutput&& read_version_output) mutable {
multi_key_desc.mutable_proto().mutable_normalization()->CopyFrom(
read_version_output.frame_and_descriptor_.desc_.proto().normalization()
);
read_version_output.frame_and_descriptor_.desc_ = std::move(multi_key_desc);
read_version_output.frame_and_descriptor_.keys_ = std::move(keys);
read_version_output.versioned_item_ = VersionedItem(std::move(key));
return std::move(read_version_output);
});
}
void add_slice_to_component_manager(
EntityId entity_id, pipelines::SegmentAndSlice& segment_and_slice,
std::shared_ptr<ComponentManager> component_manager, EntityFetchCount fetch_count
) {
ARCTICDB_DEBUG(log::memory(), "Adding entity id {}", entity_id);
component_manager->add_entity(
entity_id,
std::make_shared<SegmentInMemory>(std::move(segment_and_slice.segment_in_memory_)),
std::make_shared<RowRange>(std::move(segment_and_slice.ranges_and_key_.row_range_)),
std::make_shared<ColRange>(std::move(segment_and_slice.ranges_and_key_.col_range_)),
std::make_shared<AtomKey>(std::move(segment_and_slice.ranges_and_key_.key_)),
fetch_count
);
}
size_t num_scheduling_iterations(const std::vector<std::shared_ptr<Clause>>& clauses) {
if (clauses.empty()) {
return 0UL;
}
size_t res = 1UL;
for (auto it = std::next(clauses.cbegin()); it != clauses.cend(); ++it) {
auto prev_it = std::prev(it);
if ((*prev_it)->clause_info().output_structure_ != (*it)->clause_info().input_structure_) {
++res;
}
}
ARCTICDB_DEBUG(
log::memory(), "Processing pipeline has {} scheduling stages after the initial read and process", res
);
return res;
}
void remove_processed_clauses(std::vector<std::shared_ptr<Clause>>& clauses) {
// Erase all the clauses we have already scheduled to run
ARCTICDB_SAMPLE_DEFAULT(RemoveProcessedClauses)
if (!clauses.empty()) {
auto it = std::next(clauses.cbegin());
while (it != clauses.cend()) {
auto prev_it = std::prev(it);
if ((*prev_it)->clause_info().output_structure_ == (*it)->clause_info().input_structure_) {
++it;
} else {
break;
}
}
clauses.erase(clauses.cbegin(), it);
}
}
std::pair<std::vector<std::vector<EntityId>>, std::shared_ptr<ankerl::unordered_dense::map<EntityId, size_t>>>
get_entity_ids_and_position_map(
std::shared_ptr<ComponentManager>& component_manager, size_t num_segments,
std::vector<std::vector<size_t>>&& processing_unit_indexes
) {
// Map from entity id to position in segment_and_slice_futures
auto id_to_pos = std::make_shared<ankerl::unordered_dense::map<EntityId, size_t>>();
id_to_pos->reserve(num_segments);
// Map from position in segment_and_slice_future_splitters to entity ids
std::vector<EntityId> pos_to_id;
pos_to_id.reserve(num_segments);
auto ids = component_manager->get_new_entity_ids(num_segments);
for (auto&& [idx, id] : folly::enumerate(ids)) {
pos_to_id.emplace_back(id);
id_to_pos->emplace(id, idx);
}
std::vector<std::vector<EntityId>> entity_work_units;
entity_work_units.reserve(processing_unit_indexes.size());
for (const auto& indexes : processing_unit_indexes) {
entity_work_units.emplace_back();
entity_work_units.back().reserve(indexes.size());
for (auto index : indexes) {
entity_work_units.back().emplace_back(pos_to_id[index]);
}
}
return std::make_pair(std::move(entity_work_units), std::move(id_to_pos));
}
std::shared_ptr<std::vector<folly::Future<std::vector<EntityId>>>> schedule_first_iteration(
std::shared_ptr<ComponentManager> component_manager, size_t num_segments,
std::vector<std::vector<EntityId>>&& entities_by_work_unit,
std::shared_ptr<std::vector<EntityFetchCount>>&& segment_fetch_counts,
std::vector<FutureOrSplitter>&& segment_and_slice_future_splitters,
std::shared_ptr<ankerl::unordered_dense::map<EntityId, size_t>>&& id_to_pos,
std::shared_ptr<std::vector<std::shared_ptr<Clause>>>& clauses
) {
// TODO 11961775873: remove this kill switch
static const bool process_on_cpu_executor = ConfigsMap::instance()->get_int("Storage.ProcessOnCpuExecutor", 1) == 1;
log::version().info(
"Storage.ProcessOnCpuExecutor={}: scheduling first iteration on {} executor",
process_on_cpu_executor ? 1 : 0,
process_on_cpu_executor ? "CPU" : "IO");
auto* processing_executor = process_on_cpu_executor ? dynamic_cast<folly::Executor*>(&async::cpu_executor())
: dynamic_cast<folly::Executor*>(&folly::InlineExecutor::instance());
// Used to make sure each entity is only added into the component manager once
auto slice_added_mtx = std::make_shared<std::vector<std::mutex>>(num_segments);
auto slice_added = std::make_shared<std::vector<bool>>(num_segments, false);
auto futures = std::make_shared<std::vector<folly::Future<std::vector<EntityId>>>>();
// ===== DEBUG: count how many read futures are already fulfilled at entry =====
{
size_t ready_at_entry = 0;
for (const auto& fos : segment_and_slice_future_splitters) {
if (std::holds_alternative<folly::Future<pipelines::SegmentAndSlice>>(fos)) {
if (std::get<folly::Future<pipelines::SegmentAndSlice>>(fos).isReady()) ready_at_entry++;
}
}
log::version().info(
"schedule_first_iteration ENTRY: {}/{} read futures already fulfilled",
ready_at_entry,
segment_and_slice_future_splitters.size());
}
auto lambda_run_count = std::make_shared<std::atomic<size_t>>(0);
const size_t total_work_units = entities_by_work_unit.size();
size_t work_unit_idx = 0;
for (auto& entity_ids : entities_by_work_unit) {
std::vector<folly::Future<pipelines::SegmentAndSlice>> local_futs;
local_futs.reserve(entity_ids.size());
bool all_ready = true;
for (auto id : entity_ids) {
const auto pos = id_to_pos->at(id);
auto& future_or_splitter = segment_and_slice_future_splitters[pos];
// Some of the entities for this unit of work may be shared with other units of work
util::variant_match(
future_or_splitter,
[&local_futs, &all_ready](folly::Future<pipelines::SegmentAndSlice>& fut) {
if (!fut.isReady()) all_ready = false;
local_futs.emplace_back(std::move(fut));
},
[&local_futs, &all_ready](folly::FutureSplitter<pipelines::SegmentAndSlice>& splitter) {
all_ready = false;
local_futs.emplace_back(splitter.getFuture());
}
);
}
// Switch to the CPU executor by default (but with a kill switch) for reasons detailed in the PR description:
// https://github.com/man-group/ArcticDB/pull/3086
futures->emplace_back(folly::collect(local_futs)
.via(processing_executor)
.thenValueInline([component_manager,
segment_fetch_counts,
id_to_pos,
slice_added_mtx,
slice_added,
clauses,
lambda_run_count,
work_unit_idx,
entity_ids = std::move(entity_ids
)](std::vector<pipelines::SegmentAndSlice>&& segment_and_slices
) mutable {
auto n = lambda_run_count->fetch_add(1) + 1;
log::version().info(
"schedule_first_iteration LAMBDA unit={} run_count={} tid={}",
work_unit_idx,
n,
static_cast<unsigned long>(pthread_self()));
for (auto&& [idx, segment_and_slice] : folly::enumerate(segment_and_slices)) {
auto entity_id = entity_ids[idx];
auto pos = id_to_pos->at(entity_id);
std::lock_guard lock{slice_added_mtx->at(pos)};
if (!(*slice_added)[pos]) {
ARCTICDB_DEBUG(log::version(), "Adding entity {}", entity_id);
add_slice_to_component_manager(
entity_id,
segment_and_slice,
component_manager,
segment_fetch_counts->at(pos)
);
(*slice_added)[pos] = true;
}
}
return async::MemSegmentProcessingTask(*clauses, std::move(entity_ids))();
}));
log::version().info(
"schedule_first_iteration ATTACH unit={} all_ready_before_attach={} lambdas_run_so_far={}",
work_unit_idx,
all_ready,
lambda_run_count->load());
work_unit_idx++;
}
log::version().info(
"schedule_first_iteration EXIT: {}/{} lambdas fired during attach loop",
lambda_run_count->load(),
total_work_units);
return futures;
}
folly::Future<std::vector<EntityId>> schedule_remaining_iterations(
std::vector<std::vector<EntityId>>&& entity_ids_vec,
std::shared_ptr<std::vector<std::shared_ptr<Clause>>> clauses
) {
auto scheduling_iterations = num_scheduling_iterations(*clauses);
folly::Future<std::vector<std::vector<EntityId>>> entity_ids_vec_fut(std::move(entity_ids_vec));
for (auto i = 0UL; i < scheduling_iterations; ++i) {
entity_ids_vec_fut =
std::move(entity_ids_vec_fut)
.thenValue([clauses,
scheduling_iterations,
i](std::vector<std::vector<EntityId>>&& entity_id_vectors) {
ARCTICDB_RUNTIME_DEBUG(
log::memory(), "Scheduling iteration {} of {}", i, scheduling_iterations
);
util::check(
!clauses->empty(),
"Scheduling iteration {} has no clauses to process",
scheduling_iterations
);
if (i > 0) {
remove_processed_clauses(*clauses);
}
auto next_units_of_work =
clauses->front()->structure_for_processing(std::move(entity_id_vectors));
std::vector<folly::Future<std::vector<EntityId>>> work_futures;
for (auto& unit_of_work : next_units_of_work) {
ARCTICDB_RUNTIME_DEBUG(
log::memory(), "Scheduling work for entity ids: {}", unit_of_work
);
work_futures.emplace_back(async::submit_cpu_task(
async::MemSegmentProcessingTask{*clauses, std::move(unit_of_work)}
));
}
return folly::collect(work_futures).via(&async::io_executor());
});
}
return std::move(entity_ids_vec_fut).thenValueInline(util::flatten_vectors<EntityId>);
}
folly::Future<std::vector<EntityId>> schedule_clause_processing(
std::shared_ptr<ComponentManager> component_manager,
std::vector<folly::Future<pipelines::SegmentAndSlice>>&& segment_and_slice_futures,
std::vector<std::vector<size_t>>&& processing_unit_indexes,
std::shared_ptr<std::vector<std::shared_ptr<Clause>>> clauses
) {
// All the shared pointers as arguments to this function and created within it are to ensure that resources are
// correctly kept alive after this function returns its future
const auto num_segments = segment_and_slice_futures.size();
// Map from index in segment_and_slice_future_splitters to the number of calls to process in the first clause that
// will require that segment
auto segment_fetch_counts = generate_segment_fetch_counts(processing_unit_indexes, num_segments);
auto segment_and_slice_future_splitters =
split_futures(std::move(segment_and_slice_futures), *segment_fetch_counts);
auto [entities_by_work_unit, entity_id_to_segment_pos] =
get_entity_ids_and_position_map(component_manager, num_segments, std::move(processing_unit_indexes));
// At this point we have a set of entity ids grouped by the work units produced by the original
// structure_for_processing, and a map of those ids to the position in the vector of futures or future-splitters
// (which is the same order as originally generated from the index via the pipeline_context and ranges_and_keys), so
// we can add each entity id and its components to the component manager and schedule the first stage of work (i.e.
// from the beginning until either the end of the pipeline or the next required structure_for_processing
auto futures = schedule_first_iteration(
component_manager,
num_segments,
std::move(entities_by_work_unit),
std::move(segment_fetch_counts),
std::move(segment_and_slice_future_splitters),
std::move(entity_id_to_segment_pos),
clauses
);
return folly::collect(*futures).via(&async::io_executor()).thenValueInline([clauses](auto&& entity_ids_vec) {
remove_processed_clauses(*clauses);
return schedule_remaining_iterations(std::move(entity_ids_vec), clauses);
});
}
void set_output_descriptors(
const ProcessingUnit& proc, const std::vector<std::shared_ptr<Clause>>& clauses,
const std::shared_ptr<PipelineContext>& pipeline_context
) {
std::optional<std::string> index_column;
for (auto clause = clauses.rbegin(); clause != clauses.rend(); ++clause) {
bool should_break = util::variant_match(
(*clause)->clause_info().index_,
[](const KeepCurrentIndex&) { return false; },
[&](const KeepCurrentTopLevelIndex&) {
if (pipeline_context->norm_meta_->mutable_df()->mutable_common()->has_multi_index()) {
const auto& multi_index =
pipeline_context->norm_meta_->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 =
pipeline_context->norm_meta_->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);
}
return true;
},
[&](const NewIndex& new_index) {
index_column = new_index;
auto mutable_index = pipeline_context->norm_meta_->mutable_df()->mutable_common()->mutable_index();
mutable_index->set_name(new_index);
mutable_index->clear_fake_name();
mutable_index->set_is_physically_stored(true);
return true;
}
);
if (should_break) {
break;
}
}