Repository navigation
Expand file tree
/
Copy pathexecuteQuery.cpp
More file actions
1868 lines (1642 loc) · 87 KB
/
Copy pathexecuteQuery.cpp
File metadata and controls
1868 lines (1642 loc) · 87 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
#include <Core/ProtocolDefines.h>
#include <Common/VectorWithMemoryTracking.h>
#include <memory>
#include <optional>
#include <Analyzer/QueryNode.h>
#include <Analyzer/UnionNode.h>
#include <Analyzer/createUniqueAliasesIfNecessary.h>
#include <base/scope_guard.h>
#include <Columns/ColumnConst.h>
#include <Common/FailPoint.h>
#include <Common/ProfileEvents.h>
#include <Core/QueryProcessingStage.h>
#include <Core/Settings.h>
#include <DataTypes/DataTypeString.h>
#include <DataTypes/DataTypesNumber.h>
#include <Databases/DatabaseReplicated.h>
#include <Interpreters/Cluster.h>
#include <Interpreters/ClusterProxy/SelectStreamFactory.h>
#include <Interpreters/ClusterProxy/executeQuery.h>
#include <Interpreters/Context.h>
#include <Interpreters/DatabaseCatalog.h>
#include <Interpreters/ExpressionActions.h>
#include <Interpreters/InterpreterSelectQueryAnalyzer.h>
#include <Interpreters/OptimizeShardingKeyRewriteInVisitor.h>
#include <Interpreters/ProcessList.h>
#include <Interpreters/getCustomKeyFilterForParallelReplicas.h>
#if CLICKHOUSE_CLOUD
#include <Interpreters/SharedDatabaseCatalog.h>
#endif
#include <Parsers/ASTInsertQuery.h>
#include <Parsers/stripQuerySettings.h>
#include <Planner/Utils.h>
#include <Processors/QueryPlan/MaterializingCTEStep.h>
#include <Processors/QueryPlan/ParallelReplicasLocalPlan.h>
#include <Processors/QueryPlan/QueryPlan.h>
#include <Processors/QueryPlan/ReadFromLocalReplica.h>
#include <Processors/QueryPlan/ReadFromMergeTree.h>
#include <Processors/QueryPlan/ParallelReplicasSplitStep.h>
#include <Storages/MergeTree/RequestResponse.h>
#include <Processors/QueryPlan/ReadFromPreparedSource.h>
#include <Processors/QueryPlan/ReadFromRemote.h>
#include <Processors/QueryPlan/UnionStep.h>
#include <Processors/Sinks/EmptySink.h>
#include <Processors/Sources/NullSource.h>
#include <Processors/Sources/RemoteSource.h>
#include <QueryPipeline/Pipe.h>
#include <QueryPipeline/RemoteQueryExecutor.h>
#include <QueryPipeline/UnavailableShardTracker.h>
#include <Storages/Distributed/DistributedSettings.h>
#include <Storages/MergeTree/ParallelReplicasReadingCoordinator.h>
#include <Storages/SelectQueryInfo.h>
#include <Storages/StorageReplicatedMergeTree.h>
#include <Storages/buildQueryTreeForShard.h>
#include <Storages/getStructureOfRemoteTable.h>
#include <Storages/removeGroupingFunctionSpecializations.h>
#include <string_view>
#include <unordered_set>
namespace ProfileEvents
{
extern const Event Shards;
}
namespace DB
{
namespace Setting
{
extern const SettingsMap additional_table_filters;
extern const SettingsUInt64 allow_experimental_parallel_reading_from_replicas;
extern const SettingsBool async_insert_select_as_async_insert;
extern const SettingsUInt64 force_optimize_skip_unused_shards;
extern const SettingsUInt64 force_optimize_skip_unused_shards_nesting;
extern const SettingsBool http_allow_database_as_path;
extern const SettingsBool http_allow_filters_as_path;
extern const SettingsBool http_allow_filters_as_unrecognized_url_parameters;
extern const SettingsBool http_allow_table_as_file;
extern const SettingsString implicit_table_at_top_level;
extern const SettingsDouble limit;
extern const SettingsLoadBalancing load_balancing;
extern const SettingsUInt64 max_concurrent_queries_for_user;
extern const SettingsUInt64 max_distributed_depth;
extern const SettingsSeconds max_execution_time;
extern const SettingsSeconds max_execution_time_leaf;
extern const SettingsUInt64 max_memory_usage_for_user;
extern const SettingsUInt64 max_skip_unavailable_shards_num;
extern const SettingsFloat max_skip_unavailable_shards_ratio;
extern const SettingsMaxThreads max_threads;
extern const SettingsNonZeroUInt64 max_parallel_replicas;
extern const SettingsDouble offset;
extern const SettingsDouble page;
extern const SettingsString format;
extern const SettingsString input_format;
extern const SettingsString output_format;
extern const SettingsString default_format;
extern const SettingsString compression;
extern const SettingsString database;
extern const SettingsString select;
extern const SettingsString order;
extern const SettingsString sort;
extern const SettingsString filter;
extern const SettingsString additional_result_filter;
extern const SettingsBool optimize_skip_unused_shards;
extern const SettingsUInt64 optimize_skip_unused_shards_nesting;
extern const SettingsBool optimize_skip_unused_shards_rewrite_in;
extern const SettingsString parallel_replicas_custom_key;
extern const SettingsParallelReplicasMode parallel_replicas_mode;
extern const SettingsUInt64 parallel_replicas_custom_key_range_lower;
extern const SettingsUInt64 parallel_replicas_custom_key_range_upper;
extern const SettingsBool parallel_replicas_local_plan;
extern const SettingsBool parallel_replicas_prefer_local_replica;
extern const SettingsBool parallel_replicas_allow_view_over_mergetree;
extern const SettingsBool parallel_replicas_for_object_storage_tables;
extern const SettingsMilliseconds queue_max_wait_ms;
extern const SettingsBool run_query_in_background;
extern const SettingsBool skip_unavailable_shards;
extern const SettingsSkipUnavailableShardsMode skip_unavailable_shards_mode;
extern const SettingsOverflowMode timeout_overflow_mode;
extern const SettingsOverflowMode timeout_overflow_mode_leaf;
extern const SettingsBool use_hedged_requests;
extern const SettingsBool serialize_query_plan;
extern const SettingsBool async_socket_for_remote;
extern const SettingsBool async_query_sending_for_remote;
extern const SettingsString cluster_for_parallel_replicas;
extern const SettingsBool parallel_replicas_support_projection;
extern const SettingsUInt64 distributed_group_by_top_k;
}
namespace DistributedSetting
{
extern const DistributedSettingsBool skip_unavailable_shards;
extern const DistributedSettingsSkipUnavailableShardsMode skip_unavailable_shards_mode;
}
namespace ErrorCodes
{
extern const int TOO_LARGE_DISTRIBUTED_DEPTH;
extern const int LOGICAL_ERROR;
extern const int UNEXPECTED_CLUSTER;
extern const int INCONSISTENT_CLUSTER_DEFINITION;
extern const int NOT_IMPLEMENTED;
}
namespace FailPoints
{
extern const char parallel_replicas_force_local_replica_inactive[];
extern const char parallel_replicas_insert_select_drop_active_replica[];
}
namespace
{
/// `isSuitableForInsertSelectWithParallelReplicas` builds a throwaway parallel-replicas plan just to detect
/// whether the SELECT reads with parallel replicas. That probe runs the same connection-pool preparation as
/// the real coordinator-building pass, so without this guard it would consume the `ONCE` test failpoint
/// `parallel_replicas_insert_select_drop_active_replica` before the executed coordinator is built, and the
/// regression test would no longer exercise the reuse path it is meant to guard. Suppress the test failpoint
/// while the discarded probe plan is built (the probe and the real build run on the same thread in sequence).
thread_local bool in_insert_select_suitability_probe = false;
}
namespace ClusterProxy
{
void stripDatabaseSetting(Settings & settings)
{
/// Also reset a `database` that is merely *marked* changed (e.g. explicitly reset to the
/// default with `SET database = ''`), so the inter-server packet does not carry it.
if (settings[Setting::database].changed || !settings[Setting::database].value.empty())
{
settings[Setting::database] = "";
settings[Setting::database].changed = false;
}
}
void stripInitiatorOnlySettings(Settings & settings)
{
/// Not propagated to the next layer of distribution: it applies only to the servers the initiator queries directly,
/// which have the initiator's sort above them. The initiator sets it for those reads (`enableGroupByTopK`) after
/// this strip.
if (settings[Setting::distributed_group_by_top_k].changed || settings[Setting::distributed_group_by_top_k] != 0)
{
settings[Setting::distributed_group_by_top_k] = 0;
settings[Setting::distributed_group_by_top_k].changed = false;
}
/// All of the settings below are interpreted only at the initiator: they either shape the
/// final query (`select`, `order`, `sort`, `filter`, `limit`, `offset`, `page`,
/// `additional_result_filter`) or shape how the result is serialised to the user
/// (`format`, `output_format`, `default_format`, `compression`). Forwarding them to remote
/// shards is at best wasted work and at worst breaks distributed queries — `format = 'Null'`,
/// for example, sets `null_format = true` on each shard, suppressing TCP `sendData` and
/// producing empty blocks; `getStructureOfRemoteTable` then `continue`s without throwing
/// `NetException`, leaving `fail_messages` empty and surfacing as
/// `NO_REMOTE_SHARD_AVAILABLE. Log: ` with an empty body. The query-shaping settings would
/// similarly cause the per-shard subquery to be re-shaped a second time. Strip the settings
/// here so the inter-server `Settings` packet does not carry them. This is shared by the
/// `Distributed` fan-out and the `*Cluster` table functions (`IStorageCluster`), which both
/// materialize these settings on the initiator before reaching the remote servers.
if (settings[Setting::offset].changed || settings[Setting::offset] != 0)
{
settings[Setting::offset] = 0;
settings[Setting::offset].changed = false;
}
if (settings[Setting::limit].changed || settings[Setting::limit] != 0)
{
settings[Setting::limit] = 0;
settings[Setting::limit].changed = false;
}
if (settings[Setting::page].changed || settings[Setting::page] != 0)
{
settings[Setting::page] = 0;
settings[Setting::page].changed = false;
}
if (settings[Setting::select].changed || !settings[Setting::select].value.empty())
{
settings[Setting::select] = "";
settings[Setting::select].changed = false;
}
if (settings[Setting::order].changed || !settings[Setting::order].value.empty())
{
settings[Setting::order] = "";
settings[Setting::order].changed = false;
}
if (settings[Setting::sort].changed || !settings[Setting::sort].value.empty())
{
settings[Setting::sort] = "";
settings[Setting::sort].changed = false;
}
if (settings[Setting::filter].changed || !settings[Setting::filter].value.empty())
{
settings[Setting::filter] = "";
settings[Setting::filter].changed = false;
}
if (settings[Setting::additional_result_filter].changed || !settings[Setting::additional_result_filter].value.empty())
{
settings[Setting::additional_result_filter] = "";
settings[Setting::additional_result_filter].changed = false;
}
if (settings[Setting::format].changed || !settings[Setting::format].value.empty())
{
settings[Setting::format] = "";
settings[Setting::format].changed = false;
}
if (settings[Setting::input_format].changed || !settings[Setting::input_format].value.empty())
{
settings[Setting::input_format] = "";
settings[Setting::input_format].changed = false;
}
if (settings[Setting::output_format].changed || !settings[Setting::output_format].value.empty())
{
settings[Setting::output_format] = "";
settings[Setting::output_format].changed = false;
}
if (settings[Setting::default_format].changed || !settings[Setting::default_format].value.empty())
{
settings[Setting::default_format] = "";
settings[Setting::default_format].changed = false;
}
if (settings[Setting::compression].changed || !settings[Setting::compression].value.empty())
{
settings[Setting::compression] = "";
settings[Setting::compression].changed = false;
}
/// The HTTP/path-only settings are interpreted exclusively by the HTTP query-construction path on
/// the initiator (`http_allow_database_as_path`, `http_allow_table_as_file`,
/// `http_allow_filters_as_path`, `http_allow_filters_as_unrecognized_url_parameters`) or only
/// rewrite a FROM-less top-level query before it is wrapped (`implicit_table_at_top_level`, which
/// is already cleared for subqueries). They are irrelevant on a remote TCP query, and — for the
/// settings introduced here — forwarding them to an older shard during a rolling upgrade triggers
/// `UNKNOWN_SETTING`. Strip them in the shared helper so every remote path has the same contract.
if (settings[Setting::http_allow_database_as_path].changed || settings[Setting::http_allow_database_as_path])
{
settings[Setting::http_allow_database_as_path] = false;
settings[Setting::http_allow_database_as_path].changed = false;
}
if (settings[Setting::http_allow_table_as_file].changed || settings[Setting::http_allow_table_as_file])
{
settings[Setting::http_allow_table_as_file] = false;
settings[Setting::http_allow_table_as_file].changed = false;
}
if (settings[Setting::http_allow_filters_as_path].changed || settings[Setting::http_allow_filters_as_path])
{
settings[Setting::http_allow_filters_as_path] = false;
settings[Setting::http_allow_filters_as_path].changed = false;
}
if (settings[Setting::http_allow_filters_as_unrecognized_url_parameters].changed
|| settings[Setting::http_allow_filters_as_unrecognized_url_parameters])
{
settings[Setting::http_allow_filters_as_unrecognized_url_parameters] = false;
settings[Setting::http_allow_filters_as_unrecognized_url_parameters].changed = false;
}
if (settings[Setting::implicit_table_at_top_level].changed || !settings[Setting::implicit_table_at_top_level].value.empty())
{
settings[Setting::implicit_table_at_top_level] = "";
settings[Setting::implicit_table_at_top_level].changed = false;
}
/// `async_insert_select_as_async_insert` gates the initiator's local `INSERT ... SELECT` async-queue
/// route, which the `parallel_distributed_insert_select` path never reaches on the initiator. A shard
/// resolves its own value (including through the forwarded `compatibility`), so the initiator's copy is
/// redundant, and forwarding this name to an older shard on a rolling upgrade triggers `UNKNOWN_SETTING`.
/// Its default is `true`.
if (settings[Setting::async_insert_select_as_async_insert].changed
|| !settings[Setting::async_insert_select_as_async_insert])
{
settings[Setting::async_insert_select_as_async_insert] = true;
settings[Setting::async_insert_select_as_async_insert].changed = false;
}
/// `parallel_replicas_for_object_storage_tables` is consulted only by the initiator's analysis. Its default is `true`.
if (settings[Setting::parallel_replicas_for_object_storage_tables].changed
|| !settings[Setting::parallel_replicas_for_object_storage_tables])
{
settings[Setting::parallel_replicas_for_object_storage_tables] = true;
settings[Setting::parallel_replicas_for_object_storage_tables].changed = false;
}
/// `database` is an initiator-only setting as well: the query sent to a shard may leave the remote
/// table unqualified (e.g. a `Distributed` table created with an empty database argument), and
/// the shard must resolve it against its own default database.
stripDatabaseSetting(settings);
}
/// Single source of truth for the initiator-only setting names. MUST list exactly the settings reset by
/// `stripInitiatorOnlySettings` above. Used both to test membership (`isInitiatorOnlySettingName`) and to
/// remove these settings from a query's own `SETTINGS` clause before that query *text* is forwarded to a
/// shard: a forwarded query string — the optimized `parallel_distributed_insert_select` paths in
/// `StorageDistributed`, and `IStorageCluster`'s `formatWithSecretsOneLine()` — would otherwise carry an
/// initiator-only setting written in the user's `SETTINGS` clause, getting it re-applied or, for the
/// settings new to the HTTP table-as-file feature, rejected as `UNKNOWN_SETTING` by an older shard during
/// a rolling upgrade.
constexpr std::string_view initiator_only_setting_names[] = {
"select", "order", "sort", "filter", "limit", "offset", "page", "additional_result_filter",
"format", "input_format", "output_format", "default_format", "compression",
"http_allow_database_as_path", "http_allow_table_as_file", "http_allow_filters_as_path",
"http_allow_filters_as_unrecognized_url_parameters", "implicit_table_at_top_level",
"async_insert_select_as_async_insert",
"parallel_replicas_for_object_storage_tables",
"database",
"distributed_group_by_top_k",
};
bool isInitiatorOnlySettingName(std::string_view name)
{
for (std::string_view candidate : initiator_only_setting_names)
if (candidate == name)
return true;
return false;
}
void stripInitiatorOnlySettingsFromQuery(const ASTPtr & query)
{
/// `removeSettingsFromQuery` clears the names from every query-level `SETTINGS` carrier, covering both
/// the `name = value` (`changes`) and `name = DEFAULT` (`default_settings`) forms.
removeSettingsFromQuery(query, initiator_only_setting_names);
}
void stripInitiatorOnlySettingsFromDDLQuery(const ASTPtr & query)
{
/// A stored view body keeps the setting that decides how the view reads its table.
std::vector<std::string_view> names;
for (std::string_view name : initiator_only_setting_names)
if (name != "parallel_replicas_for_object_storage_tables")
names.push_back(name);
removeSettingsFromQuery(query, names);
}
static ContextMutablePtr updateSettingsAndClientInfoForCluster(const Cluster & cluster,
bool is_remote_function,
ContextPtr context,
const Settings & settings,
const StorageID & main_table,
ASTPtr additional_filter_ast,
LoggerPtr log,
const DistributedSettings * distributed_settings)
{
ClientInfo new_client_info = context->getClientInfo();
Settings new_settings {settings};
new_settings[Setting::queue_max_wait_ms] = Cluster::saturate(new_settings[Setting::queue_max_wait_ms], settings[Setting::max_execution_time]);
/// In case of interserver mode we should reset initial_user for remote() function to use passed user from the query.
if (is_remote_function)
{
const auto & address = cluster.getShardsAddresses().front().front();
/// The forwarded current roles are the roles of the initial user, so they cannot be passed on for another user.
if (new_client_info.initial_user != address.user)
new_client_info.current_roles.reset();
new_client_info.initial_user = address.user;
}
/// If "secret" (in remote_servers) is not in use,
/// user on the shard is not the same as the user on the initiator,
/// hence per-user limits should not be applied.
const bool interserver_mode = !cluster.getSecret().empty();
if (!interserver_mode)
{
/// Does not matter on remote servers, because queries are sent under different user.
new_settings[Setting::max_concurrent_queries_for_user] = 0;
new_settings[Setting::max_memory_usage_for_user] = 0;
/// Set as unchanged to avoid sending to remote server.
new_settings[Setting::max_concurrent_queries_for_user].changed = false;
new_settings[Setting::max_memory_usage_for_user].changed = false;
}
if (settings[Setting::force_optimize_skip_unused_shards_nesting] && settings[Setting::force_optimize_skip_unused_shards])
{
if (new_settings[Setting::force_optimize_skip_unused_shards_nesting] == 1)
{
new_settings[Setting::force_optimize_skip_unused_shards] = false;
new_settings[Setting::force_optimize_skip_unused_shards].changed = false;
if (log)
LOG_TRACE(log, "Disabling force_optimize_skip_unused_shards for nested queries (force_optimize_skip_unused_shards_nesting exceeded)");
}
else
{
--new_settings[Setting::force_optimize_skip_unused_shards_nesting].value;
new_settings[Setting::force_optimize_skip_unused_shards_nesting].changed = true;
if (log)
LOG_TRACE(
log, "force_optimize_skip_unused_shards_nesting is now {}", new_settings[Setting::force_optimize_skip_unused_shards_nesting].value);
}
}
if (settings[Setting::optimize_skip_unused_shards_nesting] && settings[Setting::optimize_skip_unused_shards])
{
if (new_settings[Setting::optimize_skip_unused_shards_nesting] == 1)
{
new_settings[Setting::optimize_skip_unused_shards] = false;
new_settings[Setting::optimize_skip_unused_shards].changed = false;
if (log)
LOG_TRACE(log, "Disabling optimize_skip_unused_shards for nested queries (optimize_skip_unused_shards_nesting exceeded)");
}
else
{
--new_settings[Setting::optimize_skip_unused_shards_nesting].value;
new_settings[Setting::optimize_skip_unused_shards_nesting].changed = true;
if (log)
LOG_TRACE(log, "optimize_skip_unused_shards_nesting is now {}", new_settings[Setting::optimize_skip_unused_shards_nesting].value);
}
}
if (!settings[Setting::skip_unavailable_shards].changed && distributed_settings)
{
new_settings[Setting::skip_unavailable_shards] = (*distributed_settings)[DistributedSetting::skip_unavailable_shards].value;
new_settings[Setting::skip_unavailable_shards].changed = true;
}
if (!settings[Setting::skip_unavailable_shards_mode].changed && distributed_settings)
{
new_settings[Setting::skip_unavailable_shards_mode] = (*distributed_settings)[DistributedSetting::skip_unavailable_shards_mode].value;
new_settings[Setting::skip_unavailable_shards_mode].changed = true;
}
/// Strip the initiator-only settings (query-shaping and result-serialisation) so the
/// inter-server `Settings` packet does not carry them; see `stripInitiatorOnlySettings`.
stripInitiatorOnlySettings(new_settings);
new_settings[Setting::run_query_in_background] = false;
/// Setting additional_table_filters may be applied to Distributed table.
/// In case if query is executed up to WithMergableState on remote shard, it is impossible to filter on initiator.
/// We need to propagate the setting, but change the table name from distributed to source.
///
/// Here we don't try to analyze setting again. In case if query_info->additional_filter_ast is not empty, some filter was applied.
/// It's just easier to add this filter for a source table.
if (additional_filter_ast)
{
Tuple tuple;
tuple.push_back(main_table.getShortName());
tuple.push_back(additional_filter_ast->formatWithSecretsOneLine());
new_settings[Setting::additional_table_filters].value.push_back(std::move(tuple));
}
if (context->canUseTaskBasedParallelReplicas() && is_remote_function)
{
/// `remote()` without a configured cluster has no cluster to scope parallel replicas to.
if (cluster.getName().empty())
new_settings[Setting::allow_experimental_parallel_reading_from_replicas] = 0;
else
new_settings[Setting::cluster_for_parallel_replicas] = cluster.getName();
}
/// `clusterAllReplicas` already reads every replica as a shard of its own, so there is nothing left
/// for parallel replicas to split
if (context->canUseTaskBasedParallelReplicas() && cluster.replicasAsShards())
new_settings[Setting::allow_experimental_parallel_reading_from_replicas] = 0;
/// The body of a `SQL SECURITY DEFINER` / `NONE` view must not hand its reads to the replicas of a shard,
/// in any parallel replicas mode: a replica cannot run them with the privileges of the view definer.
/// With the setting cleared, `ReadFromRemote` does not fan the shard query out with `canUseOffsetParallelReplicas` either.
/// A `sampling_key` follower is the exception: it must keep the setting, so that the shard reads only the slice
/// that `parallel_replicas_count` / `parallel_replica_offset` assign to it, otherwise the result is multiplied
/// by the number of replicas. Its new fan-out is prevented by `disableOffsetParallelReplicas` below instead.
const bool keep_sampling_key_slice = context->isSQLSecurityOverriddenBody() && context->isSamplingKeyParallelReplicasFollower();
if (context->isSQLSecurityOverriddenBody() && !keep_sampling_key_slice)
new_settings[Setting::allow_experimental_parallel_reading_from_replicas] = 0;
/// Parallel replicas are not disabled here for a cluster whose every shard has one replica:
/// `new_settings` is what the shard receives, and its own table may be a `Distributed` table over a
/// cluster that can use them. Whether this hop uses them is decided per shard below, and a shard
/// that cannot declines on its own, see `canUseParallelReplicasOnInitiator`.
if (settings[Setting::max_execution_time_leaf].totalMicroseconds() > 0)
{
/// Replace 'max_execution_time' of this sub-query with 'max_execution_time_leaf' and 'timeout_overflow_mode'
/// with 'timeout_overflow_mode_leaf'
new_settings[Setting::max_execution_time] = settings[Setting::max_execution_time_leaf];
new_settings[Setting::timeout_overflow_mode] = settings[Setting::timeout_overflow_mode_leaf];
}
/// in case of parallel replicas custom key use round robing load balancing
/// so custom key partitions will be spread over nodes in round-robin fashion
if (context->canUseParallelReplicasCustomKeyForCluster(cluster) && !settings[Setting::load_balancing].changed)
{
new_settings[Setting::load_balancing] = LoadBalancing::ROUND_ROBIN;
}
/// disable plan serialization for sample and custom key modes
/// until filter generation for these modes are done on query plan level
if (context->canUseOffsetParallelReplicas())
new_settings[Setting::serialize_query_plan] = false;
auto new_context = Context::createCopy(context);
new_context->setSettings(new_settings);
new_context->setClientInfo(new_client_info);
if (context->canUseParallelReplicasCustomKeyForCluster(cluster) || keep_sampling_key_slice)
new_context->disableOffsetParallelReplicas();
return new_context;
}
ContextMutablePtr updateSettingsForCluster(const Cluster & cluster, ContextPtr context, const Settings & settings, const StorageID & main_table)
{
return updateSettingsAndClientInfoForCluster(cluster,
/* is_remote_function= */ false,
context,
settings,
main_table,
/* additional_filter_ast= */ {},
/* log= */ {},
/* distributed_settings= */ {});
}
AdditionalShardFilterGenerator
getShardFilterGeneratorForCustomKey(const Cluster & cluster, ContextPtr context, const ColumnsDescription & columns)
{
if (!context->canUseParallelReplicasCustomKeyForCluster(cluster))
return {};
const auto & settings = context->getSettingsRef();
auto custom_key_ast = parseCustomKeyForTable(settings[Setting::parallel_replicas_custom_key], *context);
if (custom_key_ast == nullptr)
return {};
return [my_custom_key_ast = std::move(custom_key_ast),
column_description = columns,
custom_key_type = settings[Setting::parallel_replicas_mode].value,
custom_key_range_lower = settings[Setting::parallel_replicas_custom_key_range_lower].value,
custom_key_range_upper = settings[Setting::parallel_replicas_custom_key_range_upper].value,
query_context = context,
replica_count = cluster.getShardsInfo().front().per_replica_pools.size()](uint64_t replica_num) -> ASTPtr
{
return getCustomKeyFilterForParallelReplica(
replica_count,
replica_num - 1,
my_custom_key_ast,
{custom_key_type, custom_key_range_lower, custom_key_range_upper},
column_description,
query_context);
};
}
void executeQuery(
QueryPlan & query_plan,
SharedHeader header,
QueryProcessingStage::Enum processed_stage,
const StorageID & main_table,
const ASTPtr & table_func_ptr,
SelectStreamFactory & stream_factory,
LoggerPtr log,
ContextPtr context,
const SelectQueryInfo & query_info,
const ExpressionActionsPtr & sharding_key_expr,
const std::string & sharding_key_column_name,
const DistributedSettings & distributed_settings,
AdditionalShardFilterGenerator shard_filter_generator,
bool is_remote_function)
{
const Settings & settings = context->getSettingsRef();
if (settings[Setting::max_distributed_depth] && context->getClientInfo().distributed_depth >= settings[Setting::max_distributed_depth])
throw Exception(ErrorCodes::TOO_LARGE_DISTRIBUTED_DEPTH, "Maximum distributed depth exceeded");
const ClusterPtr & not_optimized_cluster = query_info.cluster;
QueryPlanPtrs plans;
SelectStreamFactory::Shards remote_shards;
auto cluster = query_info.getCluster();
auto new_context = updateSettingsAndClientInfoForCluster(*cluster, is_remote_function, context,
settings, main_table, query_info.additional_filter_ast, log, &distributed_settings);
if (context->getSettingsRef()[Setting::allow_experimental_parallel_reading_from_replicas].value
&& context->getSettingsRef()[Setting::allow_experimental_parallel_reading_from_replicas].value
!= new_context->getSettingsRef()[Setting::allow_experimental_parallel_reading_from_replicas].value)
{
LOG_TRACE(
log,
"Parallel reading from replicas is disabled for cluster. There are no shards with more than 1 replica: cluster={}",
cluster->getName());
}
new_context->increaseDistributedDepth();
const size_t shards = cluster->getShardCount();
ProfileEvents::increment(ProfileEvents::Shards, shards);
/// Tracker is shared between local-missing-table skip path in SelectStreamFactory and
/// remote unavailable-shard skip path in ReadFromRemote so max_skip_unavailable_shards_num
/// and max_skip_unavailable_shards_ratio are enforced uniformly across both paths.
/// Needed even with no limit set: it is also what notices that every shard was skipped.
UnavailableShardTrackerPtr unavailable_shard_tracker;
{
const auto & new_settings_ref = new_context->getSettingsRef();
if (new_settings_ref[Setting::skip_unavailable_shards])
{
size_t max_num = new_settings_ref[Setting::max_skip_unavailable_shards_num];
Float64 max_ratio = static_cast<double>(new_settings_ref[Setting::max_skip_unavailable_shards_ratio]);
unavailable_shard_tracker = std::make_shared<UnavailableShardTracker>(shards, max_num, max_ratio);
}
}
/// All shards share the query tree, so that the query is planned once, unless it is rewritten for the shard.
const auto query_for_all_shards = query_info.query_tree->clone();
for (size_t i = 0, s = cluster->getShardsInfo().size(); i < s; ++i)
{
const auto & shard_info = cluster->getShardsInfo()[i];
auto query_for_shard = query_for_all_shards;
if (sharding_key_expr && query_info.optimized_cluster && settings[Setting::optimize_skip_unused_shards_rewrite_in] && shards > 1 &&
/// TODO: support composite sharding key
sharding_key_expr->getRequiredColumns().size() == 1)
{
query_for_shard = query_for_shard->clone();
OptimizeShardingKeyRewriteInVisitor::Data visitor_data{
sharding_key_expr,
sharding_key_column_name,
shard_info,
not_optimized_cluster->getSlotToShard(),
};
optimizeShardingKeyRewriteIn(query_for_shard, std::move(visitor_data), query_info.table_expression->getAlias(), new_context);
}
// decide for each shard if parallel reading from replicas should be enabled
// according to settings and number of replicas declared per shard
const auto & addresses = cluster->getShardsAddresses().at(i);
const bool parallel_replicas_enabled = addresses.size() > 1 && new_context->canUseTaskBasedParallelReplicas();
stream_factory.createForShard(
shard_info,
query_for_shard,
main_table,
table_func_ptr,
new_context,
plans,
remote_shards,
static_cast<UInt32>(shards),
parallel_replicas_enabled,
shard_filter_generator,
unavailable_shard_tracker);
}
if (!remote_shards.empty())
{
Scalars scalars = context->hasQueryContext() ? context->getQueryContext()->getScalars() : Scalars{};
scalars.emplace(
"_shard_count", Block{{DataTypeUInt32().createColumnConst(1, shards), std::make_shared<DataTypeUInt32>(), "_shard_count"}});
auto external_tables = context->getExternalTables();
auto plan = std::make_unique<QueryPlan>();
auto read_from_remote = std::make_unique<ReadFromRemote>(
std::move(remote_shards),
header,
processed_stage,
main_table,
table_func_ptr,
new_context,
getThrottler(context),
std::move(scalars),
std::move(external_tables),
log,
shards,
query_info.storage_limits,
not_optimized_cluster->getName(),
not_optimized_cluster->getShardScopeIdentity(),
std::move(unavailable_shard_tracker));
read_from_remote->setStepDescription("Read from remote replica");
plan->addStep(std::move(read_from_remote));
plan->addInterpreterContext(new_context);
plans.emplace_back(std::move(plan));
}
if (plans.empty())
return;
if (plans.size() == 1)
{
query_plan = std::move(*plans.front());
return;
}
SharedHeaders input_headers;
input_headers.reserve(plans.size());
for (auto & plan : plans)
input_headers.emplace_back(plan->getCurrentHeader());
auto union_step = std::make_unique<UnionStep>(std::move(input_headers));
query_plan.unitePlans(std::move(union_step), std::move(plans));
}
/// Second column of the `_shard_num` scalar block: which shard numbering the shard number belongs to.
static constexpr auto SHARD_NUM_CLUSTER_COLUMN = "_cluster_for_parallel_replicas";
Block makeShardNumScalar(UInt32 shard_num, const String & shard_scope_identity)
{
return Block{
{DataTypeUInt32().createColumnConst(1, shard_num), std::make_shared<DataTypeUInt32>(), "_shard_num"},
{DataTypeString().createColumnConst(1, shard_scope_identity), std::make_shared<DataTypeString>(), SHARD_NUM_CLUSTER_COLUMN}};
}
/// The `_shard_num` scalar shipped by the initiator of a distributed query, or `nullopt` when this query is
/// not running inside one.
static std::optional<Block> getShardNumScalar(const ContextPtr & context)
{
if (!context->hasQueryContext() || !context->getQueryContext()->hasScalar("_shard_num"))
return {};
return context->getQueryContext()->getScalar("_shard_num");
}
/// The shard number the initiator shipped, or 0 when none was. Says nothing about which numbering it
/// indexes, so it resolves no cluster and cannot fail.
static UInt64 getShippedShardNum(const ContextPtr & context)
{
const auto block = getShardNumScalar(context);
if (!block)
return 0;
return block->safeGetByPosition(0).column->getUInt(0);
}
/// The shipped `_shard_num` and the `cluster_for_parallel_replicas` setting are not necessarily about the
/// same cluster, and a shard number from one cluster indexes an unrelated shard of another. Honour the
/// shard scope only when the scalar demonstrably belongs to `cluster`.
ShardScope getShardScopeForCluster(const ContextPtr & context, const Cluster & cluster)
{
const auto block = getShardNumScalar(context);
if (!block)
return {};
ShardScope scope{ShardScopeKind::Scoped, block->safeGetByPosition(0).column->getUInt(0)};
if (scope.shard_num == 0)
return {};
/// An older initiator ships a single-column block; absent provenance means "trust the scalar".
if (!block->has(SHARD_NUM_CLUSTER_COLUMN))
return scope;
const std::string_view provenance = block->getByName(SHARD_NUM_CLUSTER_COLUMN).column->getDataAt(0);
/// Compare the numbering, not the name: a derived cluster keeps the name and may renumber the shards.
/// An empty identity authenticates nothing, so it must never compare equal.
if (provenance.empty() || provenance != cluster.getShardScopeIdentity())
scope.kind = ShardScopeKind::Foreign;
return scope;
}
bool hasForeignShardScope(const ContextPtr & context)
{
const String cluster_name = context->getSettingsRef()[Setting::cluster_for_parallel_replicas];
if (cluster_name.empty())
return false;
/// Not `getClusterForParallelReplicas`: it throws for an unknown cluster, and callers of this predicate
/// do not otherwise resolve one.
const ClusterPtr cluster = context->tryGetCluster(cluster_name);
if (!cluster)
return false;
const auto scope = getShardScopeForCluster(context, *cluster);
if (scope.kind != ShardScopeKind::Foreign)
return false;
LOG_DEBUG(
getLogger("ParallelReplicas"),
"Disabling parallel replicas: shard scope shard_num={} was produced for another cluster, not for cluster={}",
scope.shard_num,
cluster_name);
return true;
}
static ContextMutablePtr updateContextForParallelReplicas(const LoggerPtr & logger, const ContextPtr & context, const UInt64 & shard_num)
{
const auto & settings = context->getSettingsRef();
auto context_mutable = Context::createCopy(context);
context_mutable->increaseDistributedDepth();
/// check hedged connections setting
if (settings[Setting::use_hedged_requests].value)
{
LOG_INFO(
logger,
"Disabling 'use_hedged_requests' in favor of 'enable_parallel_replicas'. "
"Hedged connections are not used for parallel reading from replicas");
/// disable hedged connections -> parallel replicas uses own logic to choose replicas
context_mutable->setSetting("use_hedged_requests", Field{false});
}
/// If parallel replicas executed over distributed table i.e. in scope of a shard,
/// currently, local plan for parallel replicas is not created.
/// Having local plan is prerequisite to use projection with parallel replicas.
/// So, currently, we disable projection support with parallel replicas when reading over distributed table with parallel replicas
/// Otherwise, it can lead to incorrect results, in particular with use of implicit projection min_max_count
if (shard_num > 0 && settings[Setting::parallel_replicas_support_projection].value)
{
LOG_TRACE(
logger,
"Disabling 'parallel_replicas_support_projection'. Currently, it's not supported for queries with parallel replicas over distributed tables");
context_mutable->setSetting("parallel_replicas_support_projection", Field{false});
}
if (settings[Setting::max_execution_time_leaf].totalMicroseconds() > 0)
{
/// Replace 'max_execution_time' of this sub-query with 'max_execution_time_leaf' and 'timeout_overflow_mode'
/// with 'timeout_overflow_mode_leaf'
context_mutable->setSetting("max_execution_time", static_cast<Field>(settings[Setting::max_execution_time_leaf]));
context_mutable->setSetting("timeout_overflow_mode", static_cast<Field>(settings[Setting::timeout_overflow_mode_leaf]));
/// The substitution above only affects remote replicas: each of them builds its own 'QueryStatus'
/// from the settings shipped with the sub-query, so 'max_execution_time_leaf' is enforced there.
/// The local replica, however, executes inside the initiator's pipeline and shares the initiator's
/// 'QueryStatus', whose limits come from the original (outer) query and are not bounded by the leaf
/// timeout. As a result, with a local plan the leaf reading would not use the leaf timeout contract.
/// Disable the local plan when that contract is stricter than, or differs from, the initiator's timeout
/// contract so that all leaf reading happens on remote replicas where it is honored (see
/// 'leafTimeoutRequiresRemoteOnlyLeafReading').
if (settings[Setting::parallel_replicas_local_plan] && leafTimeoutRequiresRemoteOnlyLeafReading(settings))
{
LOG_TRACE(
logger,
"Disabling 'parallel_replicas_local_plan' because the leaf timeout contract differs from the "
"initiator's: the local replica shares the initiator's query status and cannot use the leaf "
"timeout separately");
context_mutable->setSetting("parallel_replicas_local_plan", Field{false});
}
}
/// Strip the initiator-only settings (the query-shaping and result-serialisation settings, and
/// `database`) before sending the query to the secondary replicas: they are materialized on the
/// initiator and must not be re-applied per replica (which would re-shape the already-shaped
/// per-replica query or break it, e.g. `format = 'Null'`). This mirrors the `Distributed`
/// fan-out and the `*Cluster` table functions; see `stripInitiatorOnlySettings`.
{
Settings new_settings = context_mutable->getSettingsCopy();
stripInitiatorOnlySettings(new_settings);
context_mutable->setSettings(new_settings);
}
return context_mutable;
}
static std::pair<ClusterPtr, size_t> prepareClusterForParallelReplicas(const LoggerPtr & logger, const ContextPtr & context)
{
/// check cluster for parallel replicas
auto not_optimized_cluster = context->getClusterForParallelReplicas();
const auto scope = getShardScopeForCluster(context, *not_optimized_cluster);
const UInt64 shard_num = scope.kind == ShardScopeKind::Scoped ? scope.shard_num : 0;
/// Admission declines a foreign scalar, so reaching this point with one is an admission gap.
if (scope.kind == ShardScopeKind::Foreign)
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Parallel replicas shard scope shard_num={} was produced for another cluster, cannot be applied to cluster={}",
scope.shard_num,
not_optimized_cluster->getName());
ClusterPtr new_cluster = not_optimized_cluster;
/// if got valid shard_num from query initiator, then parallel replicas scope is the specified shard
/// shards are numbered in order of appearance in the cluster config
if (shard_num > 0)
{
const auto shard_count = not_optimized_cluster->getShardCount();
if (shard_num > shard_count)
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Shard number is greater than shard count: shard_num={} shard_count={} cluster={}",
shard_num,
shard_count,
not_optimized_cluster->getName());
chassert(shard_count == not_optimized_cluster->getShardsAddresses().size());
LOG_DEBUG(logger, "Parallel replicas query in shard scope: shard_num={} cluster={}", shard_num, not_optimized_cluster->getName());
// get cluster for shard specified by shard_num
// shard_num is 1-based, but getClusterWithSingleShard expects 0-based index
new_cluster = not_optimized_cluster->getClusterWithSingleShard(shard_num - 1);
}
else
{
if (not_optimized_cluster->getShardCount() > 1)
throw DB::Exception(
ErrorCodes::UNEXPECTED_CLUSTER,
"`cluster_for_parallel_replicas` setting refers to cluster with several shards. Expected a cluster with one shard");
}
return {new_cluster, shard_num};
}
std::vector<bool> getReplicasLiveness(const String & cluster_name, const ClusterPtr & cluster)
{
ReplicasInfo replicas_info;
#if CLICKHOUSE_CLOUD
/// The shared catalog cluster is exposed in `system.clusters` both under its plain name and under the
/// `all_groups.` prefix, and both report the same `is_active` data - accept either spelling here.
if (SharedDatabaseCatalog::initialized())
{
const String & catalog_cluster_name = SharedDatabaseCatalog::instance().getClusterName();
if (cluster_name == catalog_cluster_name
|| cluster_name == SharedDatabaseCatalog::ALL_GROUPS_CLUSTER_PREFIX + catalog_cluster_name)
replicas_info = SharedDatabaseCatalog::instance().getClusterWithReplicasInfo(cluster_name).second;
}
#endif
if (replicas_info.replicas.empty())
{
/// A `Replicated` database is exposed in `system.clusters` both as `<db>` and as `all_groups.<db>`;
/// the latter resolves to the same database after stripping the prefix (see `tryGetReplicatedDatabaseCluster`).
/// Strip it here too, otherwise an `all_groups.<db>` cluster gets no liveness data and we fall back to
/// counting inactive replicas again.
String database_name = cluster_name;
bool all_groups = false;
static constexpr std::string_view all_groups_prefix = DatabaseReplicated::ALL_GROUPS_CLUSTER_PREFIX;
if (database_name.starts_with(all_groups_prefix))
{
database_name = database_name.substr(all_groups_prefix.size());
all_groups = true;
}
if (auto database = DatabaseCatalog::instance().tryGetDatabase(database_name))
if (const auto * replicated = typeid_cast<const DatabaseReplicated *>(database.get()))
{
/// The cluster name is resolved by `Context::getCluster`, which prefers a
/// configured or discovered cluster over a `Replicated` database of the same name. When such a
/// cluster shadows the database, the resolved `cluster` is not the database's own cluster: its
/// replica names do not match the database's ZooKeeper nodes, so `tryGetReplicasInfo` would
/// report every replica inactive and the caller would collapse onto the local replica.
/// Only trust the database liveness when the resolved cluster really is this database's own
/// cluster (`system.clusters` likewise reports such configured clusters with unknown `is_active`).
const ClusterPtr database_cluster = all_groups ? replicated->tryGetAllGroupsCluster() : replicated->tryGetCluster();
if (database_cluster == cluster)
replicas_info = replicated->tryGetReplicasInfo(cluster);
}
}
std::vector<bool> is_active;
is_active.reserve(replicas_info.replicas.size());
for (const auto & replica : replicas_info.replicas)
is_active.push_back(replica.is_active);
return is_active;
}
/// Liveness of the replicas in cluster order, local replica forced active; empty when unknown.
static std::vector<bool>
getParallelReplicasLiveness(const ContextPtr & context, const ClusterPtr & cluster, std::optional<size_t> & local_replica_index)
{
const auto & settings = context->getSettingsRef();
const auto & shard = cluster->getShardsInfo().at(0);
/// Exclude replicas that are known to be inactive (e.g. stale registrations left over after autoscaling).
/// The reading coordinator distributes mark segments by hashing over the number of replicas, so counting
/// replicas that never participate leaves "phantom" segments that only the source replica picks up, which
/// produces a severe work-distribution skew. See `is_active` in `system.clusters`.
std::vector<bool> is_active = getReplicasLiveness(settings[Setting::cluster_for_parallel_replicas], cluster);
if (!is_active.empty() && is_active.size() != shard.getAllNodeCount())
is_active.clear(); /// Liveness does not match the cluster definition; fall back to using all replicas.