-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
distsql_physical_planner.go
5242 lines (4802 loc) · 187 KB
/
distsql_physical_planner.go
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 2016 The Cockroach Authors.
//
// Use of this software is governed by the CockroachDB Software License
// included in the /LICENSE file.
package sql
import (
"bytes"
"context"
"fmt"
"reflect"
"sort"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/cloud"
"github.com/cockroachdb/cockroach/pkg/gossip"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/kvcoord"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/concurrency/isolation"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/rpc"
"github.com/cockroachdb/cockroach/pkg/rpc/nodedialer"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catenumpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/colflow"
"github.com/cockroachdb/cockroach/pkg/sql/distsql"
"github.com/cockroachdb/cockroach/pkg/sql/execinfra"
"github.com/cockroachdb/cockroach/pkg/sql/execinfra/execagg"
"github.com/cockroachdb/cockroach/pkg/sql/execinfra/execopnode"
"github.com/cockroachdb/cockroach/pkg/sql/execinfrapb"
"github.com/cockroachdb/cockroach/pkg/sql/execstats"
"github.com/cockroachdb/cockroach/pkg/sql/opt/exec"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/physicalplan"
"github.com/cockroachdb/cockroach/pkg/sql/physicalplan/replicaoracle"
"github.com/cockroachdb/cockroach/pkg/sql/rowenc"
"github.com/cockroachdb/cockroach/pkg/sql/sem/eval"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondatapb"
"github.com/cockroachdb/cockroach/pkg/sql/span"
"github.com/cockroachdb/cockroach/pkg/sql/sqlerrors"
"github.com/cockroachdb/cockroach/pkg/sql/sqlinstance"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/intsets"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/cockroach/pkg/util/quotapool"
"github.com/cockroachdb/cockroach/pkg/util/randutil"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/redact"
)
// DistSQLPlanner is used to generate distributed plans from logical
// plans. A rough overview of the process:
//
// - the plan is based on a planNode tree (in the future it will be based on an
// intermediate representation tree). Only a subset of the possible trees is
// supported (this can be checked via CheckSupport).
//
// - we generate a PhysicalPlan for the planNode tree recursively. The
// PhysicalPlan consists of a network of processors and streams, with a set
// of unconnected "result routers". The PhysicalPlan also has information on
// ordering and on the mapping planNode columns to columns in the result
// streams (all result routers output streams with the same schema).
//
// The PhysicalPlan for a scanNode leaf consists of TableReaders, one for each node
// that has one or more ranges.
//
// - for each an internal planNode we start with the plan of the child node(s)
// and add processing stages (connected to the result routers of the children
// node).
type DistSQLPlanner struct {
st *cluster.Settings
// The SQLInstanceID of the gateway node that initiated this query.
gatewaySQLInstanceID base.SQLInstanceID
stopper *stop.Stopper
distSQLSrv *distsql.ServerImpl
spanResolver physicalplan.SpanResolver
// runnerCoordinator is used to send out requests (for running SetupFlow
// RPCs) to a pool of workers.
runnerCoordinator runnerCoordinator
// cancelFlowsCoordinator is responsible for batching up the requests to
// cancel remote flows initiated on the behalf of the current node when the
// local flows errored out.
cancelFlowsCoordinator cancelFlowsCoordinator
// gossip handle used to check node version compatibility.
gossip gossip.OptionalGossip
// sqlInstanceDialer handles communication between SQL nodes/pods.
sqlInstanceDialer *nodedialer.Dialer
// nodeHealth encapsulates the various node health checks to avoid planning
// on unhealthy nodes.
nodeHealth distSQLNodeHealth
// parallelLocalScansSem is a node-wide semaphore on the number of
// additional goroutines that can be used to run concurrent TableReaders
// for the same stage of the fully local physical plans.
parallelLocalScansSem *quotapool.IntPool
// parallelChecksSem is a node-wide semaphore on the number of additional
// goroutines that can be used to run check postqueries (FK and UNIQUE
// constraint checks) in parallel.
parallelChecksSem *quotapool.IntPool
// distSender is used to construct the spanResolver upon SetSQLInstanceInfo.
distSender *kvcoord.DistSender
// nodeDescs is used to construct the spanResolver upon SetSQLInstanceInfo.
nodeDescs kvclient.NodeDescStore
// rpcCtx is used to construct the spanResolver upon SetSQLInstanceInfo.
rpcCtx *rpc.Context
// sqlAddressResolver has information about SQL instances in a non-system
// tenant environment.
sqlAddressResolver sqlinstance.AddressResolver
// codec allows the DistSQLPlanner to determine whether it is creating plans
// for a system tenant or non-system tenant.
codec keys.SQLCodec
clock *hlc.Clock
}
// DistributionType is an enum defining when a plan should be distributed.
type DistributionType int
const (
// LocalDistribution does not distribute a plan across multiple SQL
// instances.
LocalDistribution = iota
// FullDistribution distributes a plan across multiple SQL instances whether
// it is a system tenant or non-system tenant.
FullDistribution
)
// ReplicaOraclePolicy controls which policy the physical planner uses to choose
// a replica for a given range. It is exported so that it may be overwritten
// during initialization by CCL code to enable follower reads.
var ReplicaOraclePolicy = replicaoracle.BinPackingChoice
// NewDistSQLPlanner initializes a DistSQLPlanner.
//
// sqlInstanceID is the ID of the node on which this planner runs. It is used to
// favor itself and other close-by nodes when planning. An invalid sqlInstanceID
// can be passed to aid bootstrapping, but then SetSQLInstanceInfo() needs to be called
// before this planner is used.
func NewDistSQLPlanner(
ctx context.Context,
st *cluster.Settings,
sqlInstanceID base.SQLInstanceID,
rpcCtx *rpc.Context,
distSQLSrv *distsql.ServerImpl,
distSender *kvcoord.DistSender,
nodeDescs kvclient.NodeDescStore,
gw gossip.OptionalGossip,
stopper *stop.Stopper,
isAvailable func(base.SQLInstanceID) bool,
connHealthCheckerSystem func(roachpb.NodeID, rpc.ConnectionClass) error, // will only be used by the system tenant
instanceConnHealthChecker func(base.SQLInstanceID, string) error,
sqlInstanceDialer *nodedialer.Dialer,
codec keys.SQLCodec,
sqlAddressResolver sqlinstance.AddressResolver,
clock *hlc.Clock,
) *DistSQLPlanner {
dsp := &DistSQLPlanner{
st: st,
gatewaySQLInstanceID: sqlInstanceID,
stopper: stopper,
distSQLSrv: distSQLSrv,
gossip: gw,
sqlInstanceDialer: sqlInstanceDialer,
nodeHealth: distSQLNodeHealth{
gossip: gw,
connHealthSystem: connHealthCheckerSystem,
connHealthInstance: instanceConnHealthChecker,
isAvailable: isAvailable,
},
distSender: distSender,
nodeDescs: nodeDescs,
rpcCtx: rpcCtx,
sqlAddressResolver: sqlAddressResolver,
codec: codec,
clock: clock,
}
dsp.parallelLocalScansSem = quotapool.NewIntPool("parallel local scans concurrency",
uint64(localScansConcurrencyLimit.Get(&st.SV)))
localScansConcurrencyLimit.SetOnChange(&st.SV, func(ctx context.Context) {
dsp.parallelLocalScansSem.UpdateCapacity(uint64(localScansConcurrencyLimit.Get(&st.SV)))
})
dsp.parallelChecksSem = quotapool.NewIntPool("parallel checks concurrency",
uint64(parallelChecksConcurrencyLimit.Get(&st.SV)))
parallelChecksConcurrencyLimit.SetOnChange(&st.SV, func(ctx context.Context) {
dsp.parallelChecksSem.UpdateCapacity(uint64(parallelChecksConcurrencyLimit.Get(&st.SV)))
})
if rpcCtx != nil {
// rpcCtx might be nil in some tests.
rpcCtx.Stopper.AddCloser(dsp.parallelLocalScansSem.Closer("stopper"))
rpcCtx.Stopper.AddCloser(dsp.parallelChecksSem.Closer("stopper"))
}
dsp.runnerCoordinator.init(ctx, stopper, &st.SV)
dsp.initCancelingWorkers(ctx)
return dsp
}
// GetAllInstancesByLocality lists all instances that match the passed locality
// filters.
func (dsp *DistSQLPlanner) GetAllInstancesByLocality(
ctx context.Context, filter roachpb.Locality,
) ([]sqlinstance.InstanceInfo, error) {
all, err := dsp.sqlAddressResolver.GetAllInstances(ctx)
if err != nil {
return nil, err
}
all, _ = dsp.filterUnhealthyInstances(all, nil /* nodeStatusesCache */)
log.VEventf(ctx, 2, "resolved sql instances: %v", all)
var pos int
for _, n := range all {
if ok, _ := n.Locality.Matches(filter); ok {
all[pos] = n
pos++
}
}
log.VEventf(ctx, 2, "found %d instances matching locality filter %s; matching instances: %v",
pos, filter, all[:pos])
if pos == 0 {
return nil, errors.Newf("no instances found matching locality filter %s", filter.String())
}
return all[:pos], nil
}
// GetSQLInstanceInfo gets a node descriptor by node ID.
func (dsp *DistSQLPlanner) GetSQLInstanceInfo(
sqlInstanceID base.SQLInstanceID,
) (*roachpb.NodeDescriptor, error) {
return dsp.nodeDescs.GetNodeDescriptor(roachpb.NodeID(sqlInstanceID))
}
// ReplicaOracleConfig returns the DSP's replicaoracle.Config.
func (dsp *DistSQLPlanner) ReplicaOracleConfig(loc roachpb.Locality) replicaoracle.Config {
return replicaoracle.Config{
NodeDescs: dsp.nodeDescs,
NodeID: roachpb.NodeID(dsp.gatewaySQLInstanceID),
Locality: loc,
Settings: dsp.st,
Clock: dsp.clock,
RPCContext: dsp.rpcCtx,
LatencyFunc: dsp.distSender.LatencyFunc(),
HealthFunc: dsp.distSender.HealthFunc(),
}
}
// ConstructAndSetSpanResolver constructs and sets the planner's
// SpanResolver if it is unset. It's a no-op otherwise.
func (dsp *DistSQLPlanner) ConstructAndSetSpanResolver(
ctx context.Context, nodeID roachpb.NodeID, locality roachpb.Locality,
) {
if dsp.spanResolver != nil {
log.Fatal(ctx, "trying to construct and set span resolver when one already exists")
}
sr := physicalplan.NewSpanResolver(dsp.st, dsp.distSender, dsp.nodeDescs, nodeID, locality,
dsp.clock, dsp.rpcCtx, ReplicaOraclePolicy)
dsp.SetSpanResolver(sr)
}
// SetGatewaySQLInstanceID sets the planner's SQL instance ID.
func (dsp *DistSQLPlanner) SetGatewaySQLInstanceID(id base.SQLInstanceID) {
dsp.gatewaySQLInstanceID = id
}
// GatewayID returns the ID of the gateway.
func (dsp *DistSQLPlanner) GatewayID() base.SQLInstanceID {
return dsp.gatewaySQLInstanceID
}
// SetSpanResolver switches to a different SpanResolver. It is the caller's
// responsibility to make sure the DistSQLPlanner is not in use.
func (dsp *DistSQLPlanner) SetSpanResolver(spanResolver physicalplan.SpanResolver) {
dsp.spanResolver = spanResolver
}
// distSQLExprCheckVisitor is a tree.Visitor that checks if expressions
// contain things not supported by distSQL, like distSQL-blocklisted functions.
type distSQLExprCheckVisitor struct {
err error
}
var _ tree.Visitor = &distSQLExprCheckVisitor{}
func (v *distSQLExprCheckVisitor) VisitPre(expr tree.Expr) (recurse bool, newExpr tree.Expr) {
if v.err != nil {
return false, expr
}
switch t := expr.(type) {
case *tree.FuncExpr:
if t.IsDistSQLBlocklist() {
v.err = newQueryNotSupportedErrorf("function %s cannot be executed with distsql", t)
return false, expr
}
case *tree.RoutineExpr:
v.err = newQueryNotSupportedErrorf("user-defined routine %s cannot be executed with distsql", t)
return false, expr
case *tree.DOid:
v.err = newQueryNotSupportedError("OID expressions are not supported by distsql")
return false, expr
case *tree.Subquery:
if hasOidType(t.ResolvedType()) {
// If a subquery results in a DOid datum, the datum will get a type
// annotation (because DOids are ambiguous) when serializing the
// render expression involving the result of the subquery. As a
// result, we might need to perform a cast on a remote node which
// might fail, thus we prohibit the distribution of the main query.
v.err = newQueryNotSupportedError("OID expressions are not supported by distsql")
return false, expr
}
case *tree.CastExpr:
// TODO (rohany): I'm not sure why this CastExpr doesn't have a type
// annotation at this stage of processing...
if typ, ok := tree.GetStaticallyKnownType(t.Type); ok {
switch typ.Family() {
case types.OidFamily:
v.err = newQueryNotSupportedErrorf("cast to %s is not supported by distsql", t.Type)
return false, expr
}
}
case *tree.DArray:
// We need to check for arrays of untyped tuples here since constant-folding
// on builtin functions sometimes produces this. DecodeUntaggedDatum
// requires that all the types of the tuple contents are known.
if t.ResolvedType().ArrayContents().Identical(types.AnyTuple) {
v.err = newQueryNotSupportedErrorf("array %s cannot be executed with distsql", t)
return false, expr
}
case *tree.DTuple:
if t.ResolvedType().Identical(types.AnyTuple) {
v.err = newQueryNotSupportedErrorf("tuple %s cannot be executed with distsql", t)
return false, expr
}
}
return true, expr
}
func (v *distSQLExprCheckVisitor) VisitPost(expr tree.Expr) tree.Expr { return expr }
// hasOidType returns whether t or its contents include an OID type.
func hasOidType(t *types.T) bool {
switch t.Family() {
case types.OidFamily:
return true
case types.ArrayFamily:
return hasOidType(t.ArrayContents())
case types.TupleFamily:
for _, typ := range t.TupleContents() {
if hasOidType(typ) {
return true
}
}
}
return false
}
// checkExprForDistSQL verifies that an expression doesn't contain things that
// are not yet supported by distSQL, like distSQL-blocklisted functions.
func checkExprForDistSQL(expr tree.Expr, distSQLVisitor *distSQLExprCheckVisitor) error {
if expr == nil {
return nil
}
distSQLVisitor.err = nil
tree.WalkExprConst(distSQLVisitor, expr)
return distSQLVisitor.err
}
type distRecommendation int
const (
// cannotDistribute indicates that a plan cannot be distributed.
cannotDistribute distRecommendation = iota
// canDistribute indicates that a plan can be distributed, but it's not
// clear whether it'll be benefit from that.
canDistribute
// shouldDistribute indicates that a plan will likely benefit if distributed.
shouldDistribute
)
// compose returns the recommendation for a plan given recommendations for two
// parts of it.
func (a distRecommendation) compose(b distRecommendation) distRecommendation {
if a == cannotDistribute || b == cannotDistribute {
return cannotDistribute
}
if a == shouldDistribute || b == shouldDistribute {
return shouldDistribute
}
return canDistribute
}
type queryNotSupportedError struct {
msg string
}
func (e *queryNotSupportedError) Error() string {
return e.msg
}
func newQueryNotSupportedError(msg string) error {
return &queryNotSupportedError{msg: msg}
}
func newQueryNotSupportedErrorf(format string, args ...interface{}) error {
return &queryNotSupportedError{msg: fmt.Sprintf(format, args...)}
}
// planNodeNotSupportedErr is the catch-all error value returned from
// checkSupportForPlanNode when a planNode type does not support distributed
// execution.
var planNodeNotSupportedErr = newQueryNotSupportedError("unsupported node")
var cannotDistributeRowLevelLockingErr = newQueryNotSupportedError(
"scans with row-level locking are not supported by distsql",
)
// mustWrapNode returns true if a node has no DistSQL-processor equivalent.
// This must be kept in sync with createPhysPlanForPlanNode.
// TODO(jordan): refactor these to use the observer pattern to avoid duplication.
func (dsp *DistSQLPlanner) mustWrapNode(planCtx *PlanningCtx, node planNode) bool {
switch n := node.(type) {
// Keep these cases alphabetized, please!
case *distinctNode:
case *exportNode:
case *filterNode:
case *groupNode:
case *indexJoinNode:
case *invertedFilterNode:
case *invertedJoinNode:
case *joinNode:
case *limitNode:
case *lookupJoinNode:
case *ordinalityNode:
case *projectSetNode:
case *renderNode:
case *scanNode:
case *sortNode:
case *topKNode:
case *unaryNode:
case *unionNode:
case *valuesNode:
return mustWrapValuesNode(planCtx, n.specifiedInQuery)
case *windowNode:
case *zeroNode:
case *zigzagJoinNode:
default:
return true
}
return false
}
func shouldWrapPlanNodeForExecStats(planCtx *PlanningCtx, node planNode) bool {
if !planCtx.collectExecStats {
// If execution stats aren't being collected, there is no point in
// having the overhead of wrappers.
return false
}
// Wrapping batchedPlanNodes breaks some assumptions (namely that Start is
// called on the processor-adapter) because it's executed in a special "fast
// path" way, so we exempt these from wrapping.
_, ok := node.(batchedPlanNode)
return !ok
}
// mustWrapValuesNode returns whether a valuesNode must be wrapped into the
// physical plan which indicates that we cannot create a values processor. This
// method can be used before actually creating the valuesNode to decide whether
// that creation can be avoided or when we have existing valuesNode and need to
// decide whether we can create a corresponding values processor.
func mustWrapValuesNode(planCtx *PlanningCtx, specifiedInQuery bool) bool {
// If a valuesNode wasn't specified in the query, it means that it was
// autogenerated for things that we don't want to be distributing, like
// populating values from a virtual table. So, we must wrap the valuesNode.
//
// If the plan is local, we also wrap the valuesNode to avoid pointless
// serialization of the values, and also to avoid situations in which
// expressions within the valuesNode were not distributable in the first
// place. Unless the plan is a vector insert where we are inserting a preformed
// coldata.Batch.
return !specifiedInQuery || (planCtx.isLocal && !planCtx.isVectorInsert)
}
// checkSupportForPlanNode returns a distRecommendation (as described above) or
// cannotDistribute and an error if the plan subtree is not distributable.
// The error doesn't indicate complete failure - it's instead the reason that
// this plan couldn't be distributed.
// TODO(radu): add tests for this.
func checkSupportForPlanNode(
node planNode, distSQLVisitor *distSQLExprCheckVisitor,
) (distRecommendation, error) {
switch n := node.(type) {
// Keep these cases alphabetized, please!
case *createStatsNode:
if n.runAsJob {
return cannotDistribute, planNodeNotSupportedErr
}
return shouldDistribute, nil
case *distinctNode:
return checkSupportForPlanNode(n.plan, distSQLVisitor)
case *exportNode:
return checkSupportForPlanNode(n.source, distSQLVisitor)
case *filterNode:
if err := checkExprForDistSQL(n.filter, distSQLVisitor); err != nil {
return cannotDistribute, err
}
return checkSupportForPlanNode(n.source.plan, distSQLVisitor)
case *groupNode:
rec, err := checkSupportForPlanNode(n.plan, distSQLVisitor)
if err != nil {
return cannotDistribute, err
}
for _, agg := range n.funcs {
if agg.distsqlBlocklist {
return cannotDistribute, newQueryNotSupportedErrorf("aggregate %q cannot be executed with distsql", agg.funcName)
}
}
// Distribute aggregations if possible.
return rec.compose(shouldDistribute), nil
case *indexJoinNode:
if n.table.lockingStrength != descpb.ScanLockingStrength_FOR_NONE {
// Index joins that are performing row-level locking cannot
// currently be distributed because their locks would not be
// propagated back to the root transaction coordinator.
// TODO(nvanbenschoten): lift this restriction.
return cannotDistribute, cannotDistributeRowLevelLockingErr
}
// n.table doesn't have meaningful spans, but we need to check support (e.g.
// for any filtering expression).
if _, err := checkSupportForPlanNode(n.table, distSQLVisitor); err != nil {
return cannotDistribute, err
}
return checkSupportForPlanNode(n.input, distSQLVisitor)
case *invertedFilterNode:
return checkSupportForInvertedFilterNode(n, distSQLVisitor)
case *invertedJoinNode:
if n.table.lockingStrength != descpb.ScanLockingStrength_FOR_NONE {
// Inverted joins that are performing row-level locking cannot
// currently be distributed because their locks would not be
// propagated back to the root transaction coordinator.
// TODO(nvanbenschoten): lift this restriction.
return cannotDistribute, cannotDistributeRowLevelLockingErr
}
if err := checkExprForDistSQL(n.onExpr, distSQLVisitor); err != nil {
return cannotDistribute, err
}
rec, err := checkSupportForPlanNode(n.input, distSQLVisitor)
if err != nil {
return cannotDistribute, err
}
return rec.compose(shouldDistribute), nil
case *joinNode:
if err := checkExprForDistSQL(n.pred.onCond, distSQLVisitor); err != nil {
return cannotDistribute, err
}
recLeft, err := checkSupportForPlanNode(n.left.plan, distSQLVisitor)
if err != nil {
return cannotDistribute, err
}
recRight, err := checkSupportForPlanNode(n.right.plan, distSQLVisitor)
if err != nil {
return cannotDistribute, err
}
// If either the left or the right side can benefit from distribution, we
// should distribute.
rec := recLeft.compose(recRight)
// If we can do a hash join, we distribute if possible.
if len(n.pred.leftEqualityIndices) > 0 {
rec = rec.compose(shouldDistribute)
}
return rec, nil
case *limitNode:
// Note that we don't need to check whether we support distribution of
// n.countExpr or n.offsetExpr because those expressions are evaluated
// locally, during the physical planning.
return checkSupportForPlanNode(n.plan, distSQLVisitor)
case *lookupJoinNode:
if n.remoteLookupExpr != nil || n.remoteOnlyLookups {
// This is a locality optimized join.
return cannotDistribute, nil
}
if n.table.lockingStrength != descpb.ScanLockingStrength_FOR_NONE {
// Lookup joins that are performing row-level locking cannot
// currently be distributed because their locks would not be
// propagated back to the root transaction coordinator.
// TODO(nvanbenschoten): lift this restriction.
return cannotDistribute, cannotDistributeRowLevelLockingErr
}
if err := checkExprForDistSQL(n.lookupExpr, distSQLVisitor); err != nil {
return cannotDistribute, err
}
if err := checkExprForDistSQL(n.remoteLookupExpr, distSQLVisitor); err != nil {
return cannotDistribute, err
}
if err := checkExprForDistSQL(n.onCond, distSQLVisitor); err != nil {
return cannotDistribute, err
}
rec, err := checkSupportForPlanNode(n.input, distSQLVisitor)
if err != nil {
return cannotDistribute, err
}
return rec.compose(canDistribute), nil
case *ordinalityNode:
// WITH ORDINALITY never gets distributed so that the gateway node can
// always number each row in order.
return cannotDistribute, nil
case *projectSetNode:
for i := range n.exprs {
if err := checkExprForDistSQL(n.exprs[i], distSQLVisitor); err != nil {
return cannotDistribute, err
}
}
return checkSupportForPlanNode(n.source, distSQLVisitor)
case *renderNode:
for _, e := range n.render {
if err := checkExprForDistSQL(e, distSQLVisitor); err != nil {
return cannotDistribute, err
}
}
return checkSupportForPlanNode(n.source.plan, distSQLVisitor)
case *scanNode:
if n.lockingStrength != descpb.ScanLockingStrength_FOR_NONE {
// Scans that are performing row-level locking cannot currently be
// distributed because their locks would not be propagated back to
// the root transaction coordinator.
// TODO(nvanbenschoten): lift this restriction.
return cannotDistribute, cannotDistributeRowLevelLockingErr
}
switch {
case n.localityOptimized:
// This is a locality optimized scan.
return cannotDistribute, nil
case n.isFull:
// This is a full scan.
return shouldDistribute, nil
default:
// Although we don't yet recommend distributing plans where soft limits
// propagate to scan nodes because we don't have infrastructure to only
// plan for a few ranges at a time, the propagation of the soft limits
// to scan nodes has been added in 20.1 release, so to keep the
// previous behavior we continue to ignore the soft limits for now.
// TODO(yuzefovich): pay attention to the soft limits.
return canDistribute, nil
}
case *sortNode:
rec, err := checkSupportForPlanNode(n.plan, distSQLVisitor)
if err != nil {
return cannotDistribute, err
}
return rec.compose(shouldDistribute), nil
case *topKNode:
rec, err := checkSupportForPlanNode(n.plan, distSQLVisitor)
if err != nil {
return cannotDistribute, err
}
// If we have a top K sort, we can distribute the query.
return rec.compose(canDistribute), nil
case *unaryNode:
return canDistribute, nil
case *unionNode:
recLeft, err := checkSupportForPlanNode(n.left, distSQLVisitor)
if err != nil {
return cannotDistribute, err
}
recRight, err := checkSupportForPlanNode(n.right, distSQLVisitor)
if err != nil {
return cannotDistribute, err
}
return recLeft.compose(recRight), nil
case *valuesNode:
if !n.specifiedInQuery {
// This condition indicates that the valuesNode was created by planning,
// not by the user, like the way vtables are expanded into valuesNodes. We
// don't want to distribute queries like this across the network.
return cannotDistribute, newQueryNotSupportedErrorf("unsupported valuesNode, not specified in query")
}
for _, tuple := range n.tuples {
for _, expr := range tuple {
if err := checkExprForDistSQL(expr, distSQLVisitor); err != nil {
return cannotDistribute, err
}
}
}
return canDistribute, nil
case *windowNode:
rec, err := checkSupportForPlanNode(n.plan, distSQLVisitor)
if err != nil {
return cannotDistribute, err
}
for _, f := range n.funcs {
if len(f.partitionIdxs) > 0 {
// If at least one function has PARTITION BY clause, then we
// should distribute the execution.
return rec.compose(shouldDistribute), nil
}
}
return rec.compose(canDistribute), nil
case *zeroNode:
return canDistribute, nil
case *zigzagJoinNode:
for _, side := range n.sides {
if side.scan.lockingStrength != descpb.ScanLockingStrength_FOR_NONE {
// ZigZag joins that are performing row-level locking cannot
// currently be distributed because their locks would not be
// propagated back to the root transaction coordinator.
// TODO(nvanbenschoten): lift this restriction.
return cannotDistribute, cannotDistributeRowLevelLockingErr
}
}
if err := checkExprForDistSQL(n.onCond, distSQLVisitor); err != nil {
return cannotDistribute, err
}
return shouldDistribute, nil
case *cdcValuesNode:
return cannotDistribute, nil
default:
return cannotDistribute, planNodeNotSupportedErr
}
}
func checkSupportForInvertedFilterNode(
n *invertedFilterNode, distSQLVisitor *distSQLExprCheckVisitor,
) (distRecommendation, error) {
rec, err := checkSupportForPlanNode(n.input, distSQLVisitor)
if err != nil {
return cannotDistribute, err
}
// When filtering is a union of inverted spans, it is distributable: place
// an inverted filterer on each node, which produce the primary keys in
// arbitrary order, and de-duplicate the PKs at the next stage.
// The expression is a union of inverted spans iff all the spans have been
// promoted to FactoredUnionSpans, in which case the Left and Right
// inverted.Expressions are nil.
//
// TODO(sumeer): Even if the filtering cannot be distributed, the
// placement of the inverted filter could be optimized. Specifically, when
// the input is a single processor (because the TableReader is reading
// span(s) that are all on the same node), we can place the inverted
// filterer on that input node. Currently, this approach fails because we
// don't know whether the input is a single processor at this stage, and if
// we blindly returned shouldDistribute, we encounter situations where
// remote TableReaders are feeding an inverted filterer which runs into an
// encoding problem with inverted columns. The remote code tries to decode
// the inverted column as the original type (e.g. for geospatial, tries to
// decode the int cell-id as a geometry) which obviously fails -- this is
// related to #50659. Fix this in the distSQLSpecExecFactory.
filterRec := cannotDistribute
if n.expression.Left == nil && n.expression.Right == nil {
filterRec = shouldDistribute
}
return rec.compose(filterRec), nil
}
//go:generate stringer -type=NodeStatus
// NodeStatus represents a node's health and compatibility in the context of
// physical planning for a query.
type NodeStatus int
const (
// NodeOK means that the node can be used for planning.
NodeOK NodeStatus = iota
// NodeUnhealthy means that the node should be avoided because
// it's not healthy.
NodeUnhealthy
// NodeDraining means that the node should be avoided because
// it's draining.
NodeDraining
)
// spanPartitionState captures information about the current state of the
// partitioning that has occurred during the planning process.
type spanPartitionState struct {
// partitionSpanDecisions is a mapping from a SpanPartitionReason to the number of
// times we have picked an instance for that reason.
partitionSpanDecisions [SpanPartitionReason_LOCALITY_FILTERED_RANDOM_GATEWAY_OVERLOADED + 1]int
// partitionSpans is a mapping from a SQLInstanceID to the number of
// partition spans that have been assigned to that node.
partitionSpans map[base.SQLInstanceID]int
// totalPartitionSpans is the total number of partitions that have been processed
// so far.
totalPartitionSpans int
testingOverrideRandomSelection func() base.SQLInstanceID
}
// update updates the spanPartitionState with the information about the new span partition.
func (p *spanPartitionState) update(
partitionNode base.SQLInstanceID, partitionReason SpanPartitionReason,
) {
p.totalPartitionSpans++
p.partitionSpanDecisions[partitionReason]++
p.partitionSpans[partitionNode]++
}
// PlanningCtx contains data used and updated throughout the planning process of
// a single query.
type PlanningCtx struct {
ExtendedEvalCtx *extendedEvalContext
localityFilter roachpb.Locality
// spanPartitionState captures information about the current state of the
// partitioning that has occurred during the planning process.
spanPartitionState *spanPartitionState
spanIter physicalplan.SpanResolverIterator
// nodeStatuses contains info for all SQLInstanceIDs that are referenced by
// any PhysicalPlan we generate with this context.
nodeStatuses map[base.SQLInstanceID]NodeStatus
infra *physicalplan.PhysicalInfrastructure
// isLocal is set to true if we're planning this query on a single node.
isLocal bool
// distSQLProhibitedErr, if set, indicates why the plan couldn't be
// distributed.
distSQLProhibitedErr error
planner *planner
stmtType tree.StatementReturnType
// planDepth is set to the current depth of the planNode tree. It's used to
// keep track of whether it's valid to run a root node in a special fast path
// mode.
planDepth int
// If set, the DistSQL diagram is **not** generated and not added to the
// trace (when the tracing is enabled). We generally want to include it, but
// on the main query path the overhead becomes too large while we also have
// other ways to get the diagram.
skipDistSQLDiagramGeneration bool
// stmtForDistSQLDiagram, if set, will be used when generating the DistSQL
// diagram to specify the SQL stmt that this plan corresponds to.
stmtForDistSQLDiagram string
// If set, the flows for the physical plan will be passed to this function.
// The flows are not safe for use past the lifetime of the saveFlows function.
saveFlows SaveFlowsFunc
// If set, we will record the mapping from planNode to tracing metadata to
// later allow associating statistics with the planNode.
associateNodeWithComponents func(exec.Node, execComponents)
// If set, statement execution stats should be collected.
collectExecStats bool
// parallelizeScansIfLocal indicates whether we might want to create
// multiple table readers if the physical plan ends up being fully local.
// This value is determined based on whether there are any mutations in the
// plan (which prohibit all concurrency) and whether all parts of the plan
// are supported natively by the vectorized engine.
parallelizeScansIfLocal bool
// Set if this is either a subquery or a postquery (i.e. not the "main"
// query).
subOrPostQuery bool
// mustUseLeafTxn, if set, indicates that this PlanningCtx is used to handle
// one of the plans that will run in parallel with other plans. As such, the
// DistSQL planner will need to use the LeafTxn (even if it's not needed
// based on other "regular" factors).
mustUseLeafTxn bool
// onFlowCleanup contains non-nil functions that will be called after the
// local flow finished running and is being cleaned up. It allows us to
// release the resources that are acquired during the physical planning and
// are being held onto throughout the whole flow lifecycle.
onFlowCleanup []func()
// This is true if plan is a simple insert that can be vectorized.
isVectorInsert bool
// OverridePlannerMon, if set, will be used instead of the Planner.Mon() as
// the parent monitor for the DistSQL flow.
OverridePlannerMon *mon.BytesMonitor
}
var _ physicalplan.ExprContext = &PlanningCtx{}
// NewPhysicalPlan creates an empty PhysicalPlan, backed by the
// PlanInfrastructure in the planning context.
//
// Note that any processors created in the physical plan cannot be discarded;
// they have to be part of the final plan.
func (p *PlanningCtx) NewPhysicalPlan() *PhysicalPlan {
return &PhysicalPlan{
PhysicalPlan: physicalplan.MakePhysicalPlan(p.infra),
}
}
// EvalContext returns the associated EvalContext, or nil if there isn't one.
func (p *PlanningCtx) EvalContext() *eval.Context {
if p.ExtendedEvalCtx == nil {
return nil
}
return &p.ExtendedEvalCtx.Context
}
// IsLocal returns true if this PlanningCtx is being used to plan a query that
// has no remote flows.
func (p *PlanningCtx) IsLocal() bool {
return p.isLocal
}
// getPortalPauseInfo returns the portal pause info if the current planner is
// for a pausable portal. Otherwise, returns nil.
func (p *PlanningCtx) getPortalPauseInfo() *portalPauseInfo {
if p.planner != nil && p.planner.pausablePortal != nil && p.planner.pausablePortal.pauseInfo != nil {
return p.planner.pausablePortal.pauseInfo
}
return nil
}
// setUpForMainQuery updates the PlanningCtx for the main query path.
func (p *PlanningCtx) setUpForMainQuery(
ctx context.Context, planner *planner, recv *DistSQLReceiver,
) {
p.stmtType = recv.stmtType
// Skip the diagram generation since on this "main" query path we can get it
// via the statement bundle.
p.skipDistSQLDiagramGeneration = true
if planner.execCfg.TestingKnobs.TestingSaveFlows != nil {
p.saveFlows = planner.execCfg.TestingKnobs.TestingSaveFlows(planner.stmt.SQL)
} else if planner.instrumentation.ShouldSaveFlows() {
p.saveFlows = getDefaultSaveFlowsFunc(ctx, planner, planComponentTypeMainQuery)
}
p.associateNodeWithComponents = planner.instrumentation.getAssociateNodeWithComponentsFn()
p.collectExecStats = planner.instrumentation.ShouldCollectExecStats()
}
// SaveFlowsFunc is the signature for a function used to examine the physical
// plan for a query. Implementations may not be concurrency-safe.
type SaveFlowsFunc func(
flows map[base.SQLInstanceID]*execinfrapb.FlowSpec,
opChains execopnode.OpChains,
localProcessors []execinfra.LocalProcessor,
vectorized bool,
) error
// getDefaultSaveFlowsFunc returns the default function used to save physical
// plans and their diagrams. The returned function is **not** concurrency-safe.
func getDefaultSaveFlowsFunc(
ctx context.Context, planner *planner, typ planComponentType,
) SaveFlowsFunc {
return func(flows map[base.SQLInstanceID]*execinfrapb.FlowSpec, opChains execopnode.OpChains, localProcessors []execinfra.LocalProcessor, vectorized bool) error {
var diagram execinfrapb.FlowDiagram
if planner.instrumentation.shouldSaveDiagrams() {