-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
distsql_physical_planner.go
3573 lines (3232 loc) · 120 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 Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package sql
import (
"context"
"fmt"
"reflect"
"sort"
"github.com/cockroachdb/cockroach/pkg/gossip"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/kvcoord"
"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/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc"
"github.com/cockroachdb/cockroach/pkg/sql/distsql"
"github.com/cockroachdb/cockroach/pkg/sql/execinfra"
"github.com/cockroachdb/cockroach/pkg/sql/execinfrapb"
"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/tree"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"github.com/cockroachdb/cockroach/pkg/util/envutil"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
)
// 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 {
// planVersion is the version of DistSQL targeted by the plan we're building.
// This is currently only assigned to the node's current DistSQL version and
// is used to skip incompatible nodes when mapping spans.
planVersion execinfrapb.DistSQLVersion
st *cluster.Settings
// The nodeID of the gateway node that initiated this query.
// TODO(asubiotto): This usage of NodeID instead of SQLInstanceID is
// temporary: https://github.com/cockroachdb/cockroach/issues/49596
gatewayNodeID roachpb.NodeID
stopper *stop.Stopper
distSQLSrv *distsql.ServerImpl
spanResolver physicalplan.SpanResolver
// metadataTestTolerance is the minimum level required to plan metadata test
// processors.
metadataTestTolerance execinfra.MetadataTestLevel
// runnerChan is used to send out requests (for running SetupFlow RPCs) to a
// pool of workers.
runnerChan chan runnerRequest
// gossip handle used to check node version compatibility.
gossip gossip.OptionalGossip
nodeDialer *nodedialer.Dialer
// nodeHealth encapsulates the various node health checks to avoid planning
// on unhealthy nodes.
nodeHealth distSQLNodeHealth
// distSender is used to construct the spanResolver upon SetNodeInfo.
distSender *kvcoord.DistSender
// nodeDescs is used to construct the spanResolver upon SetNodeInfo.
nodeDescs kvcoord.NodeDescStore
// rpcCtx is used to construct the spanResolver upon SetNodeInfo.
rpcCtx *rpc.Context
}
// 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
// If true, the plan diagram (in JSON) is logged for each plan (used for
// debugging).
var logPlanDiagram = envutil.EnvOrDefaultBool("COCKROACH_DISTSQL_LOG_PLAN", false)
// NewDistSQLPlanner initializes a DistSQLPlanner.
//
// nodeID 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 nodeID can be
// passed to aid bootstrapping, but then SetNodeInfo() needs to be called
// before this planner is used.
// TODO(asubiotto): This usage of NodeID instead of SQLInstanceID is
// temporary: https://github.com/cockroachdb/cockroach/issues/49596
func NewDistSQLPlanner(
ctx context.Context,
planVersion execinfrapb.DistSQLVersion,
st *cluster.Settings,
nodeID roachpb.NodeID,
rpcCtx *rpc.Context,
distSQLSrv *distsql.ServerImpl,
distSender *kvcoord.DistSender,
nodeDescs kvcoord.NodeDescStore,
gw gossip.OptionalGossip,
stopper *stop.Stopper,
isLive func(roachpb.NodeID) (bool, error),
nodeDialer *nodedialer.Dialer,
) *DistSQLPlanner {
dsp := &DistSQLPlanner{
planVersion: planVersion,
st: st,
gatewayNodeID: nodeID,
stopper: stopper,
distSQLSrv: distSQLSrv,
gossip: gw,
nodeDialer: nodeDialer,
nodeHealth: distSQLNodeHealth{
gossip: gw,
connHealth: nodeDialer.ConnHealth,
isLive: isLive,
},
distSender: distSender,
nodeDescs: nodeDescs,
rpcCtx: rpcCtx,
metadataTestTolerance: execinfra.NoExplain,
}
dsp.initRunners(ctx)
return dsp
}
func (dsp *DistSQLPlanner) shouldPlanTestMetadata() bool {
return dsp.distSQLSrv.TestingKnobs.MetadataTestLevel >= dsp.metadataTestTolerance
}
// SetNodeInfo sets the planner's node descriptor.
// The first call to SetNodeInfo leads to the construction of the SpanResolver.
func (dsp *DistSQLPlanner) SetNodeInfo(desc roachpb.NodeDescriptor) {
dsp.gatewayNodeID = desc.NodeID
if dsp.spanResolver == nil {
sr := physicalplan.NewSpanResolver(dsp.st, dsp.distSender, dsp.nodeDescs, desc,
dsp.rpcCtx, ReplicaOraclePolicy)
dsp.SetSpanResolver(sr)
}
}
// 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.DOid:
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 && typ.Family() == types.OidFamily {
v.err = newQueryNotSupportedErrorf("cast to %s is not supported by distsql", t.Type)
return false, expr
}
}
return true, expr
}
func (v *distSQLExprCheckVisitor) VisitPost(expr tree.Expr) tree.Expr { return expr }
// checkExpr verifies that an expression doesn't contain things that are not yet
// supported by distSQL, like distSQL-blocklisted functions.
func checkExpr(expr tree.Expr) error {
if expr == nil {
return nil
}
v := distSQLExprCheckVisitor{}
tree.WalkExprConst(&v, expr)
return v.err
}
type distRecommendation int
const (
// cannotDistribute indicates that a plan cannot be distributed.
cannotDistribute distRecommendation = iota
// shouldNotDistribute indicates that a plan could suffer if distributed.
shouldNotDistribute
// canDistribute indicates that a plan will probably not benefit but will
// probably not suffer if distributed.
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: if we shouldNotDistribute either part, then we
// shouldNotDistribute the overall plan either.
func (a distRecommendation) compose(b distRecommendation) distRecommendation {
if a == cannotDistribute || b == cannotDistribute {
return cannotDistribute
}
if a == shouldNotDistribute || b == shouldNotDistribute {
return shouldNotDistribute
}
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 *unaryNode:
case *unionNode:
case *valuesNode:
return mustWrapValuesNode(planCtx, n.specifiedInQuery)
case *windowNode:
case *zeroNode:
case *zigzagJoinNode:
default:
return true
}
return false
}
// 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.
//
// Finally, if noEvalSubqueries is set, it means that nothing has replaced
// the subqueries with their results yet, which again means that we can't
// plan a DistSQL values node, which requires that all expressions be
// evaluatable.
if !specifiedInQuery || planCtx.isLocal || planCtx.noEvalSubqueries {
return true
}
return false
}
// 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) (distRecommendation, error) {
switch n := node.(type) {
// Keep these cases alphabetized, please!
case *distinctNode:
return checkSupportForPlanNode(n.plan)
case *exportNode:
return checkSupportForPlanNode(n.source)
case *filterNode:
if err := checkExpr(n.filter); err != nil {
return cannotDistribute, err
}
return checkSupportForPlanNode(n.source.plan)
case *groupNode:
rec, err := checkSupportForPlanNode(n.plan)
if err != nil {
return cannotDistribute, err
}
// Distribute aggregations if possible.
return rec.compose(shouldDistribute), nil
case *indexJoinNode:
// n.table doesn't have meaningful spans, but we need to check support (e.g.
// for any filtering expression).
if _, err := checkSupportForPlanNode(n.table); err != nil {
return cannotDistribute, err
}
return checkSupportForPlanNode(n.input)
case *invertedFilterNode:
return checkSupportForInvertedFilterNode(n)
case *invertedJoinNode:
if err := checkExpr(n.onExpr); err != nil {
return cannotDistribute, err
}
if _, err := checkSupportForPlanNode(n.input); err != nil {
return cannotDistribute, err
}
return shouldDistribute, nil
case *joinNode:
if err := checkExpr(n.pred.onCond); err != nil {
return cannotDistribute, err
}
recLeft, err := checkSupportForPlanNode(n.left.plan)
if err != nil {
return cannotDistribute, err
}
recRight, err := checkSupportForPlanNode(n.right.plan)
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)
case *lookupJoinNode:
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 := checkExpr(n.onCond); err != nil {
return cannotDistribute, err
}
if _, err := checkSupportForPlanNode(n.input); err != nil {
return cannotDistribute, err
}
return shouldDistribute, 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:
return checkSupportForPlanNode(n.source)
case *renderNode:
for _, e := range n.render {
if err := checkExpr(e); err != nil {
return cannotDistribute, err
}
}
return checkSupportForPlanNode(n.source.plan)
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
}
// 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.
rec := canDistribute
// Check if we are doing a full scan.
if n.isFull {
rec = rec.compose(shouldDistribute)
}
return rec, nil
case *sortNode:
rec, err := checkSupportForPlanNode(n.plan)
if err != nil {
return cannotDistribute, err
}
// If we have to sort, distribute the query.
rec = rec.compose(shouldDistribute)
return rec, nil
case *unaryNode:
return canDistribute, nil
case *unionNode:
recLeft, err := checkSupportForPlanNode(n.left)
if err != nil {
return cannotDistribute, err
}
recRight, err := checkSupportForPlanNode(n.right)
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 := checkExpr(expr); err != nil {
return cannotDistribute, err
}
}
}
return canDistribute, nil
case *windowNode:
return checkSupportForPlanNode(n.plan)
case *zeroNode:
return canDistribute, nil
case *zigzagJoinNode:
if err := checkExpr(n.onCond); err != nil {
return cannotDistribute, err
}
return shouldDistribute, nil
default:
return cannotDistribute, planNodeNotSupportedErr
}
}
func checkSupportForInvertedFilterNode(n *invertedFilterNode) (distRecommendation, error) {
rec, err := checkSupportForPlanNode(n.input)
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
// InvertedExpressions 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
// NodeDistSQLVersionIncompatible means that the node should be avoided
// because it's DistSQL version is not compatible.
NodeDistSQLVersionIncompatible
)
// PlanningCtx contains data used and updated throughout the planning process of
// a single query.
type PlanningCtx struct {
ctx context.Context
ExtendedEvalCtx *extendedEvalContext
spanIter physicalplan.SpanResolverIterator
// NodesStatuses contains info for all NodeIDs that are referenced by any
// PhysicalPlan we generate with this context.
NodeStatuses map[roachpb.NodeID]NodeStatus
// isLocal is set to true if we're planning this query on a single node.
isLocal bool
planner *planner
// ignoreClose, when set to true, will prevent the closing of the planner's
// current plan. Only the top-level query needs to close it, but everything
// else (like sub- and postqueries, or EXPLAIN ANALYZE) should set this to
// true to avoid double closes of the planNode tree.
ignoreClose bool
stmtType tree.StatementType
// 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
// noEvalSubqueries indicates that the plan expects any subqueries to not
// be replaced by evaluation. Should only be set by EXPLAIN.
noEvalSubqueries bool
// If set, a diagram for the plan will be generated and passed to this
// function.
saveDiagram func(execinfrapb.FlowDiagram)
// If set, the diagram passed to saveDiagram will show the types of each
// stream.
saveDiagramShowInputTypes bool
}
var _ physicalplan.ExprContext = &PlanningCtx{}
// EvalContext returns the associated EvalContext, or nil if there isn't one.
func (p *PlanningCtx) EvalContext() *tree.EvalContext {
if p.ExtendedEvalCtx == nil {
return nil
}
return &p.ExtendedEvalCtx.EvalContext
}
// 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
}
// EvaluateSubqueries returns true if this plan requires subqueries be fully
// executed before trying to marshal. This is normally true except for in the
// case of EXPLAIN queries, which ultimately want to describe the subquery that
// will run, without actually running it.
func (p *PlanningCtx) EvaluateSubqueries() bool {
return !p.noEvalSubqueries
}
// PhysicalPlan is a partial physical plan which corresponds to a planNode
// (partial in that it can correspond to a planNode subtree and not necessarily
// to the entire planNode for a given query).
//
// It augments physicalplan.PhysicalPlan with information relating the physical
// plan to a planNode subtree.
//
// These plans are built recursively on a planNode tree.
type PhysicalPlan struct {
physicalplan.PhysicalPlan
// PlanToStreamColMap maps planNode columns (see planColumns()) to columns in
// the result streams. These stream indices correspond to the streams
// referenced in ResultTypes.
//
// Note that in some cases, not all columns in the result streams are
// referenced in the map; for example, columns that are only required for
// stream merges in downstream input synchronizers are not included here.
// (This is due to some processors not being configurable to output only
// certain columns and will be fixed.)
//
// Conversely, in some cases not all planNode columns have a corresponding
// result stream column (these map to index -1); this is the case for scanNode
// and indexJoinNode where not all columns in the table are actually used in
// the plan, but are kept for possible use downstream (e.g., sorting).
//
// Before the query is run, the physical plan must be finalized, and during
// the finalization a projection is added to the plan so that
// DistSQLReceiver gets rows of the desired schema from the output
// processor.
PlanToStreamColMap []int
}
// MakePhysicalPlan returns a new PhysicalPlan.
func MakePhysicalPlan(gatewayNodeID roachpb.NodeID) PhysicalPlan {
return PhysicalPlan{PhysicalPlan: physicalplan.PhysicalPlan{GatewayNodeID: gatewayNodeID}}
}
// makePlanToStreamColMap initializes a new PhysicalPlan.PlanToStreamColMap. The
// columns that are present in the result stream(s) should be set in the map.
func makePlanToStreamColMap(numCols int) []int {
m := make([]int, numCols)
for i := 0; i < numCols; i++ {
m[i] = -1
}
return m
}
// identityMap returns the slice {0, 1, 2, ..., numCols-1}.
// buf can be optionally provided as a buffer.
func identityMap(buf []int, numCols int) []int {
buf = buf[:0]
for i := 0; i < numCols; i++ {
buf = append(buf, i)
}
return buf
}
// identityMapInPlace returns the modified slice such that it contains
// {0, 1, ..., len(slice)-1}.
func identityMapInPlace(slice []int) []int {
for i := range slice {
slice[i] = i
}
return slice
}
// SpanPartition is the intersection between a set of spans for a certain
// operation (e.g table scan) and the set of ranges owned by a given node.
type SpanPartition struct {
Node roachpb.NodeID
Spans roachpb.Spans
}
type distSQLNodeHealth struct {
gossip gossip.OptionalGossip
isLive func(roachpb.NodeID) (bool, error)
connHealth func(roachpb.NodeID, rpc.ConnectionClass) error
}
func (h *distSQLNodeHealth) check(ctx context.Context, nodeID roachpb.NodeID) error {
{
// NB: as of #22658, ConnHealth does not work as expected; see the
// comment within. We still keep this code for now because in
// practice, once the node is down it will prevent using this node
// 90% of the time (it gets used around once per second as an
// artifact of rpcContext's reconnection mechanism at the time of
// writing). This is better than having it used in 100% of cases
// (until the liveness check below kicks in).
err := h.connHealth(nodeID, rpc.DefaultClass)
if err != nil && !errors.Is(err, rpc.ErrNotHeartbeated) {
// This host is known to be unhealthy. Don't use it (use the gateway
// instead). Note: this can never happen for our nodeID (which
// always has its address in the nodeMap).
log.VEventf(ctx, 1, "marking n%d as unhealthy for this plan: %v", nodeID, err)
return err
}
}
{
live, err := h.isLive(nodeID)
if err == nil && !live {
err = pgerror.Newf(pgcode.CannotConnectNow,
"node n%d is not live", errors.Safe(nodeID))
}
if err != nil {
return pgerror.Wrapf(err, pgcode.CannotConnectNow,
"not using n%d due to liveness", errors.Safe(nodeID))
}
}
// Check that the node is not draining.
if g, ok := h.gossip.Optional(distsql.MultiTenancyIssueNo); ok {
drainingInfo := &execinfrapb.DistSQLDrainingInfo{}
if err := g.GetInfoProto(gossip.MakeDistSQLDrainingKey(nodeID), drainingInfo); err != nil {
// Because draining info has no expiration, an error
// implies that we have not yet received a node's
// draining information. Since this information is
// written on startup, the most likely scenario is
// that the node is ready. We therefore return no
// error.
// TODO(ajwerner): Determine the expected error types and only filter those.
return nil //nolint:returnerrcheck
}
if drainingInfo.Draining {
err := errors.Newf("not using n%d because it is draining", log.Safe(nodeID))
log.VEventf(ctx, 1, "%v", err)
return err
}
}
return nil
}
// PartitionSpans finds out which nodes are owners for ranges touching the
// given spans, and splits the spans according to owning nodes. The result is a
// set of SpanPartitions (guaranteed one for each relevant node), which form a
// partitioning of the spans (i.e. they are non-overlapping and their union is
// exactly the original set of spans).
//
// PartitionSpans does its best to not assign ranges on nodes that are known to
// either be unhealthy or running an incompatible version. The ranges owned by
// such nodes are assigned to the gateway.
func (dsp *DistSQLPlanner) PartitionSpans(
planCtx *PlanningCtx, spans roachpb.Spans,
) ([]SpanPartition, error) {
if len(spans) == 0 {
panic("no spans")
}
ctx := planCtx.ctx
partitions := make([]SpanPartition, 0, 1)
if planCtx.isLocal {
// If we're planning locally, map all spans to the local node.
partitions = append(partitions,
SpanPartition{dsp.gatewayNodeID, spans})
return partitions, nil
}
// nodeMap maps a nodeID to an index inside the partitions array.
nodeMap := make(map[roachpb.NodeID]int)
it := planCtx.spanIter
for _, span := range spans {
// rSpan is the span we are currently partitioning.
rSpan, err := keys.SpanAddr(span)
if err != nil {
return nil, err
}
var lastNodeID roachpb.NodeID
// lastKey maintains the EndKey of the last piece of `span`.
lastKey := rSpan.Key
if log.V(1) {
log.Infof(ctx, "partitioning span %s", span)
}
// We break up rSpan into its individual ranges (which may or
// may not be on separate nodes). We then create "partitioned
// spans" using the end keys of these individual ranges.
for it.Seek(ctx, span, kvcoord.Ascending); ; it.Next(ctx) {
if !it.Valid() {
return nil, it.Error()
}
replDesc, err := it.ReplicaInfo(ctx)
if err != nil {
return nil, err
}
desc := it.Desc()
if log.V(1) {
descCpy := desc // don't let desc escape
log.Infof(ctx, "lastKey: %s desc: %s", lastKey, &descCpy)
}
if !desc.ContainsKey(lastKey) {
// This range must contain the last range's EndKey.
log.Fatalf(
ctx, "next range %v doesn't cover last end key %v. Partitions: %#v",
desc.RSpan(), lastKey, partitions,
)
}
// Limit the end key to the end of the span we are resolving.
endKey := desc.EndKey
if rSpan.EndKey.Less(endKey) {
endKey = rSpan.EndKey
}
nodeID := replDesc.NodeID
partitionIdx, inNodeMap := nodeMap[nodeID]
if !inNodeMap {
// This is the first time we are seeing nodeID for these spans. Check
// its health.
status := dsp.CheckNodeHealthAndVersion(planCtx, nodeID)
// If the node is unhealthy or its DistSQL version is incompatible, use
// the gateway to process this span instead of the unhealthy host.
// An empty address indicates an unhealthy host.
if status != NodeOK {
log.Eventf(ctx, "not planning on node %d: %s", nodeID, status)
nodeID = dsp.gatewayNodeID
partitionIdx, inNodeMap = nodeMap[nodeID]
}
if !inNodeMap {
partitionIdx = len(partitions)
partitions = append(partitions, SpanPartition{Node: nodeID})
nodeMap[nodeID] = partitionIdx
}
}
partition := &partitions[partitionIdx]
if lastNodeID == nodeID {
// Two consecutive ranges on the same node, merge the spans.
partition.Spans[len(partition.Spans)-1].EndKey = endKey.AsRawKey()
} else {
partition.Spans = append(partition.Spans, roachpb.Span{
Key: lastKey.AsRawKey(),
EndKey: endKey.AsRawKey(),
})
}
if !endKey.Less(rSpan.EndKey) {
// Done.
break
}
lastKey = endKey
lastNodeID = nodeID
}
}
return partitions, nil
}
// nodeVersionIsCompatible decides whether a particular node's DistSQL version
// is compatible with dsp.planVersion. It uses gossip to find out the node's
// version range.
func (dsp *DistSQLPlanner) nodeVersionIsCompatible(nodeID roachpb.NodeID) bool {
g, ok := dsp.gossip.Optional(distsql.MultiTenancyIssueNo)
if !ok {
return true // no gossip - always compatible; only a single gateway running in Phase 2
}
var v execinfrapb.DistSQLVersionGossipInfo
if err := g.GetInfoProto(gossip.MakeDistSQLNodeVersionKey(nodeID), &v); err != nil {
return false
}
return distsql.FlowVerIsCompatible(dsp.planVersion, v.MinAcceptedVersion, v.Version)
}
func getIndexIdx(index *descpb.IndexDescriptor, desc *tabledesc.Immutable) (uint32, error) {
if index.ID == desc.PrimaryIndex.ID {
return 0, nil
}
for i := range desc.Indexes {
if index.ID == desc.Indexes[i].ID {
// IndexIdx is 1 based (0 means primary index).
return uint32(i + 1), nil
}
}
return 0, errors.Errorf("invalid index %v (table %s)", index, desc.Name)
}
// initTableReaderSpec initializes a TableReaderSpec/PostProcessSpec that
// corresponds to a scanNode, except for the Spans and OutputColumns.
func initTableReaderSpec(
n *scanNode, planCtx *PlanningCtx, indexVarMap []int,
) (*execinfrapb.TableReaderSpec, execinfrapb.PostProcessSpec, error) {
s := physicalplan.NewTableReaderSpec()
*s = execinfrapb.TableReaderSpec{
Table: *n.desc.TableDesc(),
Reverse: n.reverse,
IsCheck: n.isCheck,
Visibility: n.colCfg.visibility,
LockingStrength: n.lockingStrength,
LockingWaitPolicy: n.lockingWaitPolicy,
// Retain the capacity of the spans slice.
Spans: s.Spans[:0],
HasSystemColumns: n.containsSystemColumns,
}
indexIdx, err := getIndexIdx(n.index, n.desc)
if err != nil {
return nil, execinfrapb.PostProcessSpec{}, err
}
s.IndexIdx = indexIdx
// When a TableReader is running scrub checks, do not allow a
// post-processor. This is because the outgoing stream is a fixed
// format (rowexec.ScrubTypes).
if n.isCheck {
return s, execinfrapb.PostProcessSpec{}, nil
}
var post execinfrapb.PostProcessSpec
if n.hardLimit != 0 {
post.Limit = uint64(n.hardLimit)
} else if n.softLimit != 0 {
s.LimitHint = n.softLimit
}
return s, post, nil
}
// tableOrdinal returns the index of a column with the given ID.
func tableOrdinal(
desc *tabledesc.Immutable, colID descpb.ColumnID, visibility execinfrapb.ScanVisibility,
) int {
for i := range desc.Columns {
if desc.Columns[i].ID == colID {
return i
}
}
if visibility == execinfra.ScanVisibilityPublicAndNotPublic {
offset := len(desc.Columns)
for i, col := range desc.MutationColumns() {
if col.ID == colID {
return offset + i
}
}
}
// The column is an implicit system column, so give it an ordinal based
// on its ID that is larger than physical columns. These ordinals are
// different for each system column kind. MVCCTimestampColumnID is the
// largest column ID, and all system columns are decreasing from it.
if colinfo.IsColIDSystemColumn(colID) {
return len(desc.Columns) + len(desc.MutationColumns()) + int(colinfo.MVCCTimestampColumnID-colID)
}
panic(errors.AssertionFailedf("column %d not in desc.Columns", colID))
}
func highestTableOrdinal(desc *tabledesc.Immutable, visibility execinfrapb.ScanVisibility) int {
highest := len(desc.Columns) - 1
if visibility == execinfra.ScanVisibilityPublicAndNotPublic {
highest = len(desc.Columns) + len(desc.MutationColumns()) - 1
}
return highest
}
// toTableOrdinals returns a mapping from column ordinals in cols to table
// reader column ordinals.
func toTableOrdinals(
cols []*descpb.ColumnDescriptor, desc *tabledesc.Immutable, visibility execinfrapb.ScanVisibility,
) []int {
res := make([]int, len(cols))
for i := range res {