-
Notifications
You must be signed in to change notification settings - Fork 414
Expand file tree
/
Copy pathDAGStorageInterpreter.cpp
More file actions
1772 lines (1625 loc) · 75.8 KB
/
DAGStorageInterpreter.cpp
File metadata and controls
1772 lines (1625 loc) · 75.8 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 2023 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <Common/Exception.h>
#include <Common/FailPoint.h>
#include <Common/FmtUtils.h>
#include <Common/Stopwatch.h>
#include <Common/TiFlashException.h>
#include <Common/TiFlashMetrics.h>
#include <Common/config.h> // For ENABLE_CLARA
#include <DataStreams/ExpressionBlockInputStream.h>
#include <DataStreams/FilterBlockInputStream.h>
#include <DataStreams/GeneratedColumnPlaceholderBlockInputStream.h>
#include <DataStreams/IProfilingBlockInputStream.h>
#include <DataStreams/MultiplexInputStream.h>
#include <DataStreams/NullBlockInputStream.h>
#include <DataStreams/TiRemoteBlockInputStream.h>
#include <Flash/Coprocessor/ChunkCodec.h>
#include <Flash/Coprocessor/DAGContext.h>
#include <Flash/Coprocessor/DAGQueryInfo.h>
#include <Flash/Coprocessor/DAGStorageInterpreter.h>
#include <Flash/Coprocessor/InterpreterUtils.h>
#include <Flash/Coprocessor/RemoteRequest.h>
#include <Flash/Coprocessor/collectOutputFieldTypes.h>
#include <Interpreters/Context.h>
#include <Interpreters/SharedContexts/Disagg.h>
#include <Operators/BlockInputStreamSourceOp.h>
#include <Operators/ConcatSourceOp.h>
#include <Operators/CoprocessorReaderSourceOp.h>
#include <Operators/ExpressionTransformOp.h>
#include <Operators/NullSourceOp.h>
#include <Operators/UnorderedSourceOp.h>
#include <Parsers/makeDummyQuery.h>
#include <Storages/DeltaMerge/Index/VectorIndex/Stream/Ctx.h>
#include <Storages/DeltaMerge/ReadThread/ActiveSegmentReadTaskQueue.h>
#include <Storages/DeltaMerge/Remote/DisaggSnapshot.h>
#include <Storages/DeltaMerge/Remote/WNDisaggSnapshotManager.h>
#include <Storages/DeltaMerge/ScanContext.h>
#include <Storages/IManageableStorage.h>
#include <Storages/KVStore/KVStore.h>
#include <Storages/KVStore/Read/LockException.h>
#include <Storages/KVStore/TMTContext.h>
#include <Storages/KVStore/Types.h>
#include <Storages/MutableSupport.h>
#include <Storages/RegionQueryInfo.h>
#include <Storages/S3/S3Common.h>
#include <Storages/StorageDeltaMerge.h>
#include <TiDB/Decode/TypeMapping.h>
#include <TiDB/Schema/SchemaSyncer.h>
#include <TiDB/Schema/TiDBSchemaManager.h>
#include <common/logger_useful.h>
#include <kvproto/coprocessor.pb.h>
#include <tipb/select.pb.h>
#if ENABLE_CLARA
#include <Storages/DeltaMerge/Index/FullTextIndex/Stream/Ctx.h>
#endif
namespace DB
{
namespace FailPoints
{
extern const char region_exception_after_read_from_storage_some_error[];
extern const char region_exception_after_read_from_storage_all_error[];
extern const char pause_with_alter_locks_acquired[];
extern const char force_remote_read_for_batch_cop[];
extern const char force_remote_read_for_batch_cop_once[];
extern const char pause_after_copr_streams_acquired[];
extern const char pause_after_copr_streams_acquired_once[];
extern const char random_trigger_remote_read[];
} // namespace FailPoints
namespace
{
RegionException::RegionReadStatus GetRegionReadStatus(
const RegionInfo & check_info,
const RegionPtr & current_region,
ImutRegionRangePtr & region_range)
{
if (!current_region)
return RegionException::RegionReadStatus::NOT_FOUND;
auto meta_snap = current_region->dumpRegionMetaSnapshot();
if (meta_snap.ver != check_info.region_version)
return RegionException::RegionReadStatus::EPOCH_NOT_MATCH;
// No need to check conf_version if its peer state is normal
if (current_region->peerState() != raft_serverpb::PeerState::Normal)
return RegionException::RegionReadStatus::NOT_FOUND;
region_range = std::move(meta_snap.range);
return RegionException::RegionReadStatus::OK;
}
std::tuple<std::optional<RegionRetryList>, RegionException::RegionReadStatus> MakeRegionQueryInfos(
const TablesRegionInfoMap & dag_region_infos,
const std::unordered_set<RegionID> & region_force_retry,
TMTContext & tmt,
MvccQueryInfo & mvcc_info,
bool batch_cop [[maybe_unused]])
{
mvcc_info.regions_query_info.clear();
RegionRetryList region_need_retry;
RegionException::RegionReadStatus status_res = RegionException::RegionReadStatus::OK;
for (const auto & [physical_table_id, regions] : dag_region_infos)
{
for (const auto & [id, r] : regions.get())
{
if (r.key_ranges.empty())
{
throw TiFlashException(
Errors::Coprocessor::BadRequest,
"Income key ranges is empty, region_id={} version={} conf_version={}",
r.region_id,
r.region_version,
r.region_conf_version);
}
if (region_force_retry.count(id))
{
region_need_retry.emplace_back(r);
status_res = RegionException::RegionReadStatus::NOT_FOUND;
continue;
}
ImutRegionRangePtr region_range{nullptr};
auto status = GetRegionReadStatus(r, tmt.getKVStore()->getRegion(id), region_range);
fiu_do_on(FailPoints::force_remote_read_for_batch_cop, {
if (batch_cop)
status = RegionException::RegionReadStatus::NOT_FOUND;
});
fiu_do_on(FailPoints::force_remote_read_for_batch_cop_once, {
if (batch_cop)
status = RegionException::RegionReadStatus::NOT_FOUND;
});
fiu_do_on(FailPoints::random_trigger_remote_read, {
if (batch_cop)
status = RegionException::RegionReadStatus::NOT_FOUND;
});
if (status != RegionException::RegionReadStatus::OK)
{
region_need_retry.emplace_back(r);
status_res = status;
continue;
}
RegionQueryInfo info(id, r.region_version, r.region_conf_version, physical_table_id);
{
info.range_in_table = region_range->rawKeys();
for (const auto & p : r.key_ranges)
{
TableID table_id_in_range = -1;
if (!computeMappedTableID(*p.first, table_id_in_range) || table_id_in_range != physical_table_id)
{
throw TiFlashException(
Errors::Coprocessor::BadRequest,
"Income key ranges is illegal, region_id={} version={} conf_version={} "
"key_range_table_id={} region_table_id={}",
r.region_id,
r.region_version,
r.region_conf_version,
table_id_in_range,
physical_table_id);
}
if (p.first->compare(*info.range_in_table.first) < 0
|| p.second->compare(*info.range_in_table.second) > 0)
{
throw TiFlashException(
Errors::Coprocessor::BadRequest,
"Income key ranges is illegal, region_id={} version={} conf_version={} request_range=[{}, "
"{}) region_range=[{}, {}]",
r.region_id,
r.region_version,
r.region_conf_version,
p.first->toDebugString(),
p.second->toDebugString(),
info.range_in_table.first->toDebugString(),
info.range_in_table.second->toDebugString());
}
}
info.required_handle_ranges = r.key_ranges;
info.bypass_lock_ts = r.bypass_lock_ts;
}
mvcc_info.regions_query_info.emplace_back(std::move(info));
}
}
if (region_need_retry.empty())
return std::make_tuple(std::nullopt, RegionException::RegionReadStatus::OK);
else
return std::make_tuple(std::move(region_need_retry), status_res);
}
bool hasRegionToRead(const DAGContext & dag_context, const TiDBTableScan & table_scan)
{
bool has_region_to_read = false;
for (const auto physical_table_id : table_scan.getPhysicalTableIDs())
{
const auto & table_regions_info = dag_context.getTableRegionsInfoByTableID(physical_table_id);
if (!table_regions_info.local_regions.empty() || !table_regions_info.remote_regions.empty())
{
has_region_to_read = true;
break;
}
}
return has_region_to_read;
}
// add timezone cast for timestamp type, this is used to support session level timezone
// <has_cast, extra_cast, project_for_remote_read>
std::pair<bool, ExpressionActionsPtr> addExtraCastsAfterTs(
DAGExpressionAnalyzer & analyzer,
const std::vector<UInt8> & may_need_add_cast_column,
const TiDBTableScan & table_scan)
{
// if no column need to add cast, return directly
if (std::find(may_need_add_cast_column.begin(), may_need_add_cast_column.end(), true)
== may_need_add_cast_column.end())
return {false, nullptr};
ExpressionActionsChain chain;
// execute timezone cast or duration cast if needed for local table scan
if (analyzer.appendExtraCastsAfterTS(chain, may_need_add_cast_column, table_scan))
{
ExpressionActionsPtr extra_cast = chain.getLastActions();
assert(extra_cast);
chain.finalize();
chain.clear();
return {true, extra_cast};
}
else
{
return {false, nullptr};
}
}
void injectFailPointForLocalRead([[maybe_unused]] const SelectQueryInfo & query_info)
{
// Inject failpoint to throw RegionException for testing
fiu_do_on(FailPoints::region_exception_after_read_from_storage_some_error, {
const auto & regions_info = query_info.mvcc_query_info->regions_query_info;
RegionException::UnavailableRegions region_ids;
for (const auto & info : regions_info)
{
if (random() % 100 > 50)
region_ids.insert(info.region_id);
}
LOG_WARNING(
Logger::get(),
"failpoint inject region_exception_after_read_from_storage_some_error, throw RegionException with "
"region_ids={}",
region_ids);
throw RegionException(std::move(region_ids), RegionException::RegionReadStatus::NOT_FOUND, nullptr);
});
fiu_do_on(FailPoints::region_exception_after_read_from_storage_all_error, {
const auto & regions_info = query_info.mvcc_query_info->regions_query_info;
RegionException::UnavailableRegions region_ids;
for (const auto & info : regions_info)
region_ids.insert(info.region_id);
LOG_WARNING(
Logger::get(),
"failpoint inject region_exception_after_read_from_storage_all_error, throw RegionException with "
"region_ids={}",
region_ids);
throw RegionException(std::move(region_ids), RegionException::RegionReadStatus::NOT_FOUND, nullptr);
});
}
String genErrMsgForLocalRead(const KeyspaceID keyspace_id, const TableID & table_id, const TableID & logical_table_id)
{
return table_id == logical_table_id
? fmt::format("(while creating read sources from storage, keyspace={} table_id={})", keyspace_id, table_id)
: fmt::format(
"(while creating read sources from storage, keyspace={} table_id={} logical_table_id={})",
keyspace_id,
table_id,
logical_table_id);
}
} // namespace
DAGStorageInterpreter::DAGStorageInterpreter(
Context & context_,
const TiDBTableScan & table_scan_,
const FilterConditions & filter_conditions_,
size_t max_streams_)
: context(context_)
, table_scan(table_scan_)
, filter_conditions(filter_conditions_)
, max_streams(max_streams_)
, log(Logger::get(context.getDAGContext()->log ? context.getDAGContext()->log->identifier() : ""))
, logical_table_id(table_scan.getLogicalTableID())
, tmt(context.getTMTContext())
, mvcc_query_info(new MvccQueryInfo(true, context.getSettingsRef().read_tso))
{
if (unlikely(!hasRegionToRead(dagContext(), table_scan)))
{
throw TiFlashException(
fmt::format("Dag Request does not have region to read for table: {}", logical_table_id),
Errors::Coprocessor::BadRequest);
}
}
DAGStorageInterpreter::~DAGStorageInterpreter() = default;
void DAGStorageInterpreter::execute(DAGPipeline & pipeline)
{
prepare(); // learner read
executeImpl(pipeline);
}
void DAGStorageInterpreter::execute(PipelineExecutorContext & exec_context, PipelineExecGroupBuilder & group_builder)
{
prepare(); // learner read
return executeImpl(exec_context, group_builder);
}
void DAGStorageInterpreter::executeImpl(
PipelineExecutorContext & exec_context,
PipelineExecGroupBuilder & group_builder)
{
auto & dag_context = dagContext();
/*** stage1 build for local storage ***/
if (!mvcc_query_info->regions_query_info.empty())
{
buildLocalExec(exec_context, group_builder, context.getSettingsRef().max_block_size);
if (!group_builder.empty())
{
dag_context.addInboundIOProfileInfos(
table_scan.getTableScanExecutorID(),
group_builder.getCurIOProfileInfos(),
/*is_append=*/true);
/// handle generated column if necessary.
executeGeneratedColumnPlaceholder(exec_context, group_builder, generated_column_infos, log);
DAGExpressionAnalyzer analyzer{group_builder.getCurrentHeader(), context};
/// handle timezone/duration cast for local table scan.
executeCastAfterTableScan(exec_context, group_builder, analyzer);
dag_context.addOperatorProfileInfos(
table_scan.getTableScanExecutorID(),
group_builder.getCurProfileInfos(),
/*is_append=*/true);
/// handle filter conditions for local table scan.
/// If force_push_down_all_filters_to_scan is set, we will build all filter conditions in scan.
/// TODO add runtime filter in Filter input stream.
if (filter_conditions.hasValue() && likely(!context.getSettingsRef().force_push_down_all_filters_to_scan))
{
::DB::executePushedDownFilter(exec_context, group_builder, filter_conditions, analyzer, log);
dag_context.addOperatorProfileInfos(
filter_conditions.executor_id,
group_builder.getCurProfileInfos(),
/*is_append=*/true);
}
}
}
/*** stage2 build for remote read ***/
// Should build `remote_requests` under protect of `table_structure_lock`.
// Note that `buildRemoteRequests` must be called after `buildLocalExec` because
// `buildLocalExec` will setup `region_retry_from_local_region` and we must
// retry those regions or there will be data lost.
auto remote_requests = buildRemoteRequests(dag_context.scan_context_map[table_scan.getTableScanExecutorID()]);
if (dag_context.is_disaggregated_task && !remote_requests.empty())
{
// This means compute node is sending requests with stale region info, we simply reject the request
// and ask compute node to send requests again with correct region info. When compute node updates region info,
// compute node may be sending requests to other WN.
RegionException::UnavailableRegions region_ids;
for (const auto & info : context.getDAGContext()->retry_regions)
region_ids.insert(info.region_id);
throw RegionException(std::move(region_ids), RegionException::RegionReadStatus::EPOCH_NOT_MATCH, "executeImpl");
}
// A failpoint to test pause before alter lock released
FAIL_POINT_PAUSE(FailPoints::pause_with_alter_locks_acquired);
// Release alter locks
// The DeltaTree engine ensures that once sourceOps are created, the caller can get a consistent result
// from those sourceOps even if DDL operations are applied. Release the alter lock so that reading does not
// block DDL operations, keep the drop lock so that the storage not to be dropped during reading.
const TableLockHolders drop_locks = releaseAlterLocks();
// For those regions which are not presented in this tiflash node, we will try to fetch streams by key ranges from other tiflash nodes, only happens in batch cop / mpp mode.
if (!remote_requests.empty())
{
PipelineExecGroupBuilder remote_builder;
buildRemoteExec(exec_context, remote_builder, remote_requests);
if (!remote_builder.empty())
{
dag_context.addInboundIOProfileInfos(
table_scan.getTableScanExecutorID(),
remote_builder.getCurIOProfileInfos(),
/*is_append=*/true);
dag_context.addOperatorProfileInfos(
table_scan.getTableScanExecutorID(),
remote_builder.getCurProfileInfos(),
/*is_append=*/true);
if (filter_conditions.hasValue())
dag_context.addOperatorProfileInfos(
filter_conditions.executor_id,
remote_builder.getCurProfileInfos(),
/*is_append=*/true);
group_builder.merge(std::move(remote_builder));
}
}
/*** stage3 build null source op if group_builder is empty after building for local/remote ***/
if (group_builder.empty())
{
auto header = Block(getColumnWithTypeAndName(genNamesAndTypesForTableScan(table_scan)));
group_builder.addConcurrency(std::make_unique<NullSourceOp>(exec_context, header, log->identifier()));
dag_context.addOperatorProfileInfos(
table_scan.getTableScanExecutorID(),
group_builder.getCurProfileInfos(),
/*is_append=*/true);
if (filter_conditions.hasValue())
dag_context.addOperatorProfileInfos(
filter_conditions.executor_id,
group_builder.getCurProfileInfos(),
/*is_append=*/true);
}
for (const auto & lock : drop_locks)
dagContext().addTableLock(lock);
FAIL_POINT_PAUSE(FailPoints::pause_after_copr_streams_acquired);
FAIL_POINT_PAUSE(FailPoints::pause_after_copr_streams_acquired_once);
}
void DAGStorageInterpreter::executeImpl(DAGPipeline & pipeline)
{
auto & dag_context = dagContext();
/*** stage1 build for local storage ***/
if (!mvcc_query_info->regions_query_info.empty())
{
buildLocalStreams(pipeline, context.getSettingsRef().max_block_size);
if (!pipeline.streams.empty())
{
auto & table_scan_io_input_streams
= dagContext().getInBoundIOInputStreamsMap()[table_scan.getTableScanExecutorID()];
pipeline.transform([&](auto & stream) { table_scan_io_input_streams.push_back(stream); });
/// handle generated column if necessary.
executeGeneratedColumnPlaceholder(generated_column_infos, log, pipeline);
DAGExpressionAnalyzer analyzer{pipeline.firstStream()->getHeader(), context};
/// handle timezone/duration cast for local and remote table scan.
executeCastAfterTableScan(pipeline, analyzer);
recordProfileStreams(pipeline, table_scan.getTableScanExecutorID());
/// handle filter conditions for local table scan.
/// If force_push_down_all_filters_to_scan is set, we will build all filter conditions in scan.
/// TODO add runtime filter in Filter input stream.
if (filter_conditions.hasValue() && likely(!context.getSettingsRef().force_push_down_all_filters_to_scan))
{
::DB::executePushedDownFilter(filter_conditions, analyzer, log, pipeline);
recordProfileStreams(pipeline, filter_conditions.executor_id);
}
}
}
/*** stage2 build for remote read ***/
// Should build `remote_requests` under protect of `table_structure_lock`.
// Note that `buildRemoteRequests` must be called after `buildLocalStreams` because
// `buildLocalStreams` will setup `region_retry_from_local_region` and we must
// retry those regions or there will be data lost.
auto remote_requests = buildRemoteRequests(dag_context.scan_context_map[table_scan.getTableScanExecutorID()]);
if (dag_context.is_disaggregated_task && !remote_requests.empty())
{
// This means compute node is sending requests with stale region info, we simply reject the request
// and ask compute node to send requests again with correct region info. When compute node updates region info,
// compute node may be sending requests to other write node.
RegionException::UnavailableRegions region_ids;
for (const auto & info : context.getDAGContext()->retry_regions)
region_ids.insert(info.region_id);
throw RegionException(std::move(region_ids), RegionException::RegionReadStatus::EPOCH_NOT_MATCH, "executeImpl");
}
// A failpoint to test pause before alter lock released
FAIL_POINT_PAUSE(FailPoints::pause_with_alter_locks_acquired);
// Release alter locks
// The DeltaTree engine ensures that once input streams are created, the caller can get a consistent result
// from those streams even if DDL operations are applied. Release the alter lock so that reading does not
// block DDL operations, keep the drop lock so that the storage not to be dropped during reading.
const TableLockHolders drop_locks = releaseAlterLocks();
// For those regions which are not presented in this tiflash node, we will try to fetch streams by key ranges from other tiflash nodes, only happens in batch cop / mpp mode.
if (!remote_requests.empty())
{
DAGPipeline remote_pipeline;
buildRemoteStreams(remote_requests, remote_pipeline);
if (!remote_pipeline.streams.empty())
{
auto & table_scan_io_input_streams
= dagContext().getInBoundIOInputStreamsMap()[table_scan.getTableScanExecutorID()];
remote_pipeline.transform([&](auto & stream) { table_scan_io_input_streams.push_back(stream); });
recordProfileStreams(remote_pipeline, table_scan.getTableScanExecutorID());
if (filter_conditions.hasValue())
recordProfileStreams(remote_pipeline, filter_conditions.executor_id);
pipeline.streams.insert(
pipeline.streams.end(),
remote_pipeline.streams.begin(),
remote_pipeline.streams.end());
}
}
/*** stage3 build null stream if group_builder is empty after building for local/remote ***/
if (pipeline.streams.empty())
{
auto header = Block(getColumnWithTypeAndName(genNamesAndTypesForTableScan(table_scan)));
pipeline.streams.push_back(std::make_shared<NullBlockInputStream>(header));
recordProfileStreams(pipeline, table_scan.getTableScanExecutorID());
if (filter_conditions.hasValue())
recordProfileStreams(pipeline, filter_conditions.executor_id);
}
for (const auto & lock : drop_locks)
dagContext().addTableLock(lock);
FAIL_POINT_PAUSE(FailPoints::pause_after_copr_streams_acquired);
FAIL_POINT_PAUSE(FailPoints::pause_after_copr_streams_acquired_once);
}
// here we assume that, if the columns' id and data type in query is the same as the columns in TiDB,
// we think we can directly do read, and don't need sync schema.
// compare the columns in table_scan with the columns in storages, to check if the current schema is satisfied this query.
// column.name are always empty from table_scan, and column name is not necessary in read process, so we don't need compare the name here.
std::tuple<bool, String> compareColumns(
ColumnID logical_table_id,
const TiDB::ColumnInfos & table_scan_columns,
const TiDB::ColumnInfos & cur_columns,
const DAGContext & dag_context,
const LoggerPtr & log)
{
std::unordered_map<ColumnID, const TiDB::ColumnInfo *> column_id_map;
for (const auto & column : cur_columns)
column_id_map[column.id] = &column;
for (const auto & column : table_scan_columns)
{
// Exclude virtual columns, including MutSup::extra_handle_id, MutSup::version_col_id,MutSup::delmark_col_id,MutSup::extra_table_id_col_id
if (column.id < 0)
continue;
auto iter = column_id_map.find(column.id);
if (iter == column_id_map.end())
{
String error_message = fmt::format(
"the column in the query is not found in current columns, keyspace={} table_id={} column_id={}",
dag_context.getKeyspaceID(),
logical_table_id,
column.id);
LOG_WARNING(log, error_message);
return std::make_tuple(false, error_message);
}
if (getDataTypeByColumnInfo(column)->getName() != getDataTypeByColumnInfo(*iter->second)->getName())
{
String error_message = fmt::format(
"the column data type in the query is not the same as the current column, keyspace={} table_id={} "
"column_id={} column_type={} query_column_type={}",
dag_context.getKeyspaceID(),
logical_table_id,
column.id,
getDataTypeByColumnInfo(*iter->second)->getName(),
getDataTypeByColumnInfo(column)->getName());
LOG_WARNING(log, error_message);
return std::make_tuple(false, error_message);
}
}
return std::make_tuple(true, "");
}
// Apply learner read to ensure we can get strong consistent with TiKV Region
// leaders. If the local Regions do not match the requested Regions, then build
// request to retry fetching data from other nodes.
void DAGStorageInterpreter::prepare()
{
// About why we do learner read before acquiring structure lock on Storage(s).
// Assume that:
// 1. Read threads do learner read and wait for the Raft applied index with holding a read lock
// on "alter lock" of an IStorage X
// 2. Raft threads try to decode data for Region in the same IStorage X, and find it need to
// apply DDL operations which acquire write lock on "alter locks"
// Under this situation, all Raft threads will be stuck by the read threads, but read threads
// wait for Raft threads to push forward the applied index. Deadlocks happens!!
// So we must do learner read without structure lock on IStorage. After learner read, acquire the
// structure lock of IStorage(s) (to avoid concurrent issues between read threads and DDL
// operations) and build the requested inputstreams. Once the inputstreams build, we should release
// the alter lock to avoid blocking DDL operations.
// TODO: If we can acquire a read-only view on the IStorage structure (both `ITableDeclaration`
// and `TiDB::TableInfo`) we may get this process more simplified. (tiflash/issues/1853)
// Do learner read
DAGContext & dag_context = *context.getDAGContext();
auto scan_context
= std::make_shared<DM::ScanContext>(dag_context.getKeyspaceID(), dag_context.getResourceGroupName());
dag_context.scan_context_map[table_scan.getTableScanExecutorID()] = scan_context;
mvcc_query_info->scan_context = scan_context;
Stopwatch watch;
if (dag_context.isBatchCop() || dag_context.isMPPTask() || dag_context.is_disaggregated_task)
learner_read_snapshot = doBatchCopLearnerRead();
else
learner_read_snapshot = doCopLearnerRead();
scan_context->learner_read_ns += watch.elapsed();
// Acquire read lock on `alter lock` and build the requested inputstreams
storages_with_structure_lock = getAndLockStorages(context.getSettingsRef().schema_version);
assert(storages_with_structure_lock.find(logical_table_id) != storages_with_structure_lock.end());
storage_for_logical_table = storages_with_structure_lock[logical_table_id].storage;
std::tie(required_columns, may_need_add_cast_column) = getColumnsForTableScan();
scan_context->num_columns = required_columns.size();
}
void DAGStorageInterpreter::executeCastAfterTableScan(
PipelineExecutorContext & exec_context,
PipelineExecGroupBuilder & group_builder,
DAGExpressionAnalyzer & analyzer)
{
// execute timezone cast or duration cast if needed for local table scan
auto [has_cast, extra_cast] = addExtraCastsAfterTs(analyzer, may_need_add_cast_column, table_scan);
if (has_cast)
{
for (size_t i = 0; i < group_builder.concurrency(); ++i)
{
auto & builder = group_builder.getCurBuilder(i);
builder.appendTransformOp(
std::make_unique<ExpressionTransformOp>(exec_context, log->identifier(), extra_cast));
}
}
}
void DAGStorageInterpreter::executeCastAfterTableScan(DAGPipeline & pipeline, DAGExpressionAnalyzer & analyzer)
{
// execute timezone cast or duration cast if needed for local table scan
auto [has_cast, extra_cast] = addExtraCastsAfterTs(analyzer, may_need_add_cast_column, table_scan);
if (has_cast)
{
for (auto & stream : pipeline.streams)
{
stream = std::make_shared<ExpressionBlockInputStream>(stream, extra_cast, log->identifier());
stream->setExtraInfo("cast after local tableScan");
}
}
}
std::vector<pingcap::coprocessor::CopTask> DAGStorageInterpreter::buildCopTasks(
const std::vector<RemoteRequest> & remote_requests)
{
assert(!remote_requests.empty());
#ifndef NDEBUG
const DAGSchema & schema = remote_requests[0].schema;
auto schema_match = [&schema](const DAGSchema & other) {
if (schema.size() != other.size())
return false;
for (size_t i = 0; i < schema.size(); ++i)
{
if (schema[i].second.tp != other[i].second.tp || schema[i].second.flag != other[i].second.flag)
return false;
}
return true;
};
for (size_t i = 1; i < remote_requests.size(); ++i)
{
if (!schema_match(remote_requests[i].schema))
throw Exception("Schema mismatch between different partitions for partition table");
}
#endif
pingcap::kv::Cluster * cluster = tmt.getKVCluster();
std::vector<pingcap::coprocessor::CopTask> all_tasks;
for (const auto & remote_request : remote_requests)
{
pingcap::coprocessor::RequestPtr req = std::make_shared<pingcap::coprocessor::Request>();
remote_request.dag_request.SerializeToString(&(req->data));
req->tp = pingcap::coprocessor::ReqType::DAG;
req->start_ts = context.getSettingsRef().read_tso;
req->schema_version = context.getSettingsRef().schema_version;
req->resource_group_name = dagContext().getResourceGroupName();
pingcap::kv::Backoffer bo(pingcap::kv::copBuildTaskMaxBackoff);
pingcap::kv::StoreType store_type = pingcap::kv::StoreType::TiFlash;
std::multimap<std::string, std::string> meta_data;
meta_data.emplace("is_remote_read", "true");
auto tasks = pingcap::coprocessor::buildCopTasks(
bo,
cluster,
remote_request.key_ranges,
req,
store_type,
dagContext().getKeyspaceID(),
remote_request.connection_id,
remote_request.connection_alias,
&Poco::Logger::get("pingcap/coprocessor"),
std::move(meta_data),
[&] { GET_METRIC(tiflash_coprocessor_request_count, type_remote_read_sent).Increment(); });
all_tasks.insert(all_tasks.end(), tasks.begin(), tasks.end());
}
GET_METRIC(tiflash_coprocessor_request_count, type_remote_read_constructed)
.Increment(static_cast<double>(all_tasks.size()));
return all_tasks;
}
CoprocessorReaderPtr DAGStorageInterpreter::buildCoprocessorReader(const std::vector<RemoteRequest> & remote_requests)
{
std::vector<pingcap::coprocessor::CopTask> all_tasks = buildCopTasks(remote_requests);
const DAGSchema & schema = remote_requests[0].schema;
pingcap::kv::Cluster * cluster = tmt.getKVCluster();
bool has_enforce_encode_type
= remote_requests[0].dag_request.has_force_encode_type() && remote_requests[0].dag_request.force_encode_type();
pingcap::kv::LabelFilter tiflash_label_filter = S3::ClientFactory::instance().isEnabled()
? pingcap::kv::labelFilterOnlyTiFlashWriteNode
: pingcap::kv::labelFilterNoTiFlashWriteNode;
size_t concurrent_num = std::min<size_t>(context.getSettingsRef().max_threads, all_tasks.size());
size_t queue_size = context.getSettingsRef().remote_read_queue_size > 0
? context.getSettingsRef().remote_read_queue_size.get()
: concurrent_num * 4;
bool enable_cop_stream = context.getSettingsRef().enable_cop_stream_for_remote_read;
UInt64 cop_timeout = context.getSettingsRef().cop_timeout_for_remote_read;
String store_zone_label;
auto kv_store = tmt.getKVStore();
if likely (kv_store)
{
for (int i = 0; i < kv_store->getStoreMeta().labels_size(); ++i)
{
if (kv_store->getStoreMeta().labels().at(i).key() == "zone")
{
store_zone_label = kv_store->getStoreMeta().labels().at(i).value();
break;
}
}
}
auto coprocessor_reader = std::make_shared<CoprocessorReader>(
schema,
cluster,
std::move(all_tasks),
has_enforce_encode_type,
concurrent_num,
enable_cop_stream,
queue_size,
cop_timeout,
tiflash_label_filter,
log->identifier(),
store_zone_label,
kv_store->getStoreID());
context.getDAGContext()->addCoprocessorReader(coprocessor_reader);
return coprocessor_reader;
}
void DAGStorageInterpreter::buildRemoteStreams(
const std::vector<RemoteRequest> & remote_requests,
DAGPipeline & pipeline)
{
auto coprocessor_reader = buildCoprocessorReader(remote_requests);
size_t concurrent_num = coprocessor_reader->enableCopStream() ? context.getSettingsRef().max_threads.get()
: coprocessor_reader->getConcurrency();
for (size_t i = 0; i < concurrent_num; ++i)
{
BlockInputStreamPtr input = std::make_shared<CoprocessorBlockInputStream>(
coprocessor_reader,
log->identifier(),
table_scan.getTableScanExecutorID(),
/*stream_id=*/0);
pipeline.streams.push_back(input);
}
LOG_DEBUG(log, "remote stream built");
}
void DAGStorageInterpreter::buildRemoteExec(
PipelineExecutorContext & exec_context,
PipelineExecGroupBuilder & group_builder,
const std::vector<RemoteRequest> & remote_requests)
{
auto coprocessor_reader = buildCoprocessorReader(remote_requests);
size_t concurrent_num = coprocessor_reader->enableCopStream() ? context.getSettingsRef().max_threads.get()
: coprocessor_reader->getConcurrency();
/// TODO: support reading data from write nodes
for (size_t i = 0; i < concurrent_num; ++i)
group_builder.addConcurrency(
std::make_unique<CoprocessorReaderSourceOp>(exec_context, log->identifier(), coprocessor_reader));
LOG_DEBUG(log, "remote sourceOps built");
}
DAGContext & DAGStorageInterpreter::dagContext() const
{
return *context.getDAGContext();
}
void DAGStorageInterpreter::recordProfileStreams(DAGPipeline & pipeline, const String & key)
{
auto & profile_streams = dagContext().getProfileStreamsMap()[key];
pipeline.transform([&profile_streams](auto & stream) { profile_streams.push_back(stream); });
}
LearnerReadSnapshot DAGStorageInterpreter::doCopLearnerRead()
{
if (table_scan.isPartitionTableScan())
{
throw TiFlashException(
"Cop request does not support partition table scan",
DB::Errors::Coprocessor::BadRequest);
}
TablesRegionInfoMap regions_for_local_read;
for (const auto physical_table_id : table_scan.getPhysicalTableIDs())
{
regions_for_local_read.emplace(
physical_table_id,
std::cref(context.getDAGContext()->getTableRegionsInfoByTableID(physical_table_id).local_regions));
}
auto [info_retry, status] = MakeRegionQueryInfos(regions_for_local_read, {}, tmt, *mvcc_query_info, false);
if (info_retry)
throw RegionException({info_retry->begin()->get().region_id}, status, "doCopLearnerRead");
return doLearnerRead(logical_table_id, *mvcc_query_info, /*for_batch_cop=*/false, context, log);
}
/// Will assign region_retry_from_local_region
LearnerReadSnapshot DAGStorageInterpreter::doBatchCopLearnerRead()
{
TablesRegionInfoMap regions_for_local_read;
for (const auto physical_table_id : table_scan.getPhysicalTableIDs())
{
const auto & local_regions
= context.getDAGContext()->getTableRegionsInfoByTableID(physical_table_id).local_regions;
regions_for_local_read.emplace(physical_table_id, std::cref(local_regions));
}
if (regions_for_local_read.empty())
return {};
std::unordered_set<RegionID> force_retry;
for (;;)
{
try
{
region_retry_from_local_region.clear();
auto [retry, status]
= MakeRegionQueryInfos(regions_for_local_read, force_retry, tmt, *mvcc_query_info, true);
UNUSED(status);
if (retry)
{
region_retry_from_local_region = std::move(*retry);
for (const auto & r : region_retry_from_local_region)
force_retry.emplace(r.get().region_id);
}
if (mvcc_query_info->regions_query_info.empty())
return {};
return doLearnerRead(logical_table_id, *mvcc_query_info, /*for_batch_cop=*/true, context, log);
}
catch (const LockException & e)
{
// When this is a disaggregated read task on write node issued by compute node, we need compute node
// to take care of retrying.
if (context.getDAGContext()->is_disaggregated_task)
throw;
// We can also use current thread to resolve lock, but it will block next process.
// So, force this region retry in another thread in CoprocessorBlockInputStream.
for (const auto & lock : e.locks)
force_retry.emplace(lock.first);
}
catch (const RegionException & e)
{
// When this is a disaggregated read task on write node issued by compute node, we need compute node
// to take care of retrying.
if (context.getDAGContext()->is_disaggregated_task)
throw;
if (tmt.checkShuttingDown())
throw TiFlashException("TiFlash server is terminating", Errors::Coprocessor::Internal);
// By now, RegionException will contain all region id of MvccQueryInfo, which is needed by CHSpark.
// When meeting RegionException, we can let MakeRegionQueryInfos to check in next loop.
force_retry.insert(e.unavailable_region.begin(), e.unavailable_region.end());
}
catch (DB::Exception & e)
{
const auto keyspace_id = context.getDAGContext()->getKeyspaceID();
e.addMessage(fmt::format(
"(while doing learner read for table, keyspace={} logical_table_id={})",
keyspace_id,
logical_table_id));
throw;
}
}
}
std::unordered_map<TableID, SelectQueryInfo> DAGStorageInterpreter::generateSelectQueryInfos()
{
std::unordered_map<TableID, SelectQueryInfo> ret;
bool use_unordered_concat = context.getSettingsRef().dt_enable_unordered_concat;
// Shared read queue for all physical tables
auto shared_read_queue = std::make_shared<DM::ActiveSegmentReadTaskQueue>(max_streams, log);
auto create_query_info = [&](Int64 table_id) -> SelectQueryInfo {
SelectQueryInfo query_info;
/// to avoid null point exception
query_info.query = dagContext().dummy_ast;
query_info.dag_query = std::make_unique<DAGQueryInfo>(
filter_conditions.conditions,
table_scan.getANNQueryInfo(),
table_scan.getFTSQueryInfo(),
table_scan.getPushedDownFilters(),
table_scan.getUsedIndexes(),
table_scan.getColumns(),
table_scan.getRuntimeFilterIDs(),
table_scan.getMaxWaitTimeMs(),
context.getTimezoneInfo());
query_info.req_id = fmt::format("{} table_id={}", log->identifier(), table_id);
query_info.keep_order = table_scan.keepOrder();
query_info.is_fast_scan = table_scan.isFastScan();
if (use_unordered_concat)
{
query_info.read_queue = shared_read_queue;
}
else
{
// Different read queue for different physical table
query_info.read_queue
= std::make_shared<DM::ActiveSegmentReadTaskQueue>(max_streams, Logger::get(query_info.req_id));
}
return query_info;
};
RUNTIME_CHECK_MSG(mvcc_query_info->scan_context != nullptr, "Unexpected null scan_context");
if (table_scan.isPartitionTableScan())
{
bool has_multiple_partitions = table_scan.getPhysicalTableIDs().size() > 1;
for (const auto physical_table_id : table_scan.getPhysicalTableIDs())
{
SelectQueryInfo query_info = create_query_info(physical_table_id);
query_info.mvcc_query_info = std::make_unique<MvccQueryInfo>(
mvcc_query_info->resolve_locks,
mvcc_query_info->start_ts,
mvcc_query_info->scan_context);
query_info.has_multiple_partitions = has_multiple_partitions;
ret.emplace(physical_table_id, std::move(query_info));
}
// Dispatch the regions_query_info to different physical table's query_info
for (auto & r : mvcc_query_info->regions_query_info)
{
ret[r.physical_table_id].mvcc_query_info->regions_query_info.push_back(r);
}
}
else
{
const TableID table_id = logical_table_id;
SelectQueryInfo query_info = create_query_info(table_id);
query_info.mvcc_query_info = std::move(mvcc_query_info);
ret.emplace(table_id, std::move(query_info));
}
return ret;
}
bool DAGStorageInterpreter::checkRetriableForBatchCopOrMPP(
const TableID & table_id,
const SelectQueryInfo & query_info,
const RegionException & e,
const Int32 num_allow_retry)
{
const DAGContext & dag_context = *context.getDAGContext();
assert((dag_context.isBatchCop() || dag_context.isMPPTask()));
const auto & dag_regions = dag_context.getTableRegionsInfoByTableID(table_id).local_regions;
FmtBuffer buffer;
if (likely(num_allow_retry > 0))
{
auto & regions_query_info = query_info.mvcc_query_info->regions_query_info;
for (auto iter = regions_query_info.begin(); iter != regions_query_info.end(); /**/)
{
if (e.unavailable_region.find(iter->region_id) != e.unavailable_region.end())
{
// move the error regions info from `query_info.mvcc_query_info->regions_query_info` to `region_retry_from_local_region`