-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
distsql_physical_planner.go
4168 lines (3805 loc) · 145 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"
"math/rand"
"reflect"
"sort"
"github.com/cockroachdb/cockroach/pkg/base"
"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/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"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"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/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/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/sqlinstance"
"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/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/quotapool"
"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 SQLInstanceID of the gateway node that initiated this query.
gatewaySQLInstanceID base.SQLInstanceID
stopper *stop.Stopper
distSQLSrv *distsql.ServerImpl
spanResolver physicalplan.SpanResolver
// runnerChan is used to send out requests (for running SetupFlow RPCs) to a
// pool of workers.
runnerChan chan runnerRequest
// 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
// nodeDialer handles communication between SQL and KV nodes.
nodeDialer *nodedialer.Dialer
// podNodeDialer handles communication between SQL nodes/pods.
podNodeDialer *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
// distSender is used to construct the spanResolver upon SetSQLInstanceInfo.
distSender *kvcoord.DistSender
// nodeDescs is used to construct the spanResolver upon SetSQLInstanceInfo.
nodeDescs kvcoord.NodeDescStore
// rpcCtx is used to construct the spanResolver upon SetSQLInstanceInfo.
rpcCtx *rpc.Context
// sqlInstanceProvider has information about SQL instances in a non-system
// tenant environment.
sqlInstanceProvider sqlinstance.Provider
// 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 (
// DistributionTypeNone does not distribute a plan across multiple instances.
DistributionTypeNone = iota
// DistributionTypeAlways distributes a plan across multiple instances whether
// it is a system tenant or non-system tenant.
DistributionTypeAlways
// DistributionTypeSystemTenantOnly only distributes a plan if it is for a
// system tenant. Plans on non-system tenants are not distributed.
DistributionTypeSystemTenantOnly
)
// 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.
//
// 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,
planVersion execinfrapb.DistSQLVersion,
st *cluster.Settings,
sqlInstanceID base.SQLInstanceID,
rpcCtx *rpc.Context,
distSQLSrv *distsql.ServerImpl,
distSender *kvcoord.DistSender,
nodeDescs kvcoord.NodeDescStore,
gw gossip.OptionalGossip,
stopper *stop.Stopper,
isAvailable func(base.SQLInstanceID) bool,
nodeDialer *nodedialer.Dialer,
podNodeDialer *nodedialer.Dialer,
codec keys.SQLCodec,
sqlInstanceProvider sqlinstance.Provider,
clock *hlc.Clock,
) *DistSQLPlanner {
dsp := &DistSQLPlanner{
planVersion: planVersion,
st: st,
gatewaySQLInstanceID: sqlInstanceID,
stopper: stopper,
distSQLSrv: distSQLSrv,
gossip: gw,
nodeDialer: nodeDialer,
podNodeDialer: podNodeDialer,
nodeHealth: distSQLNodeHealth{
gossip: gw,
connHealth: nodeDialer.ConnHealthTryDial,
isAvailable: isAvailable,
},
distSender: distSender,
nodeDescs: nodeDescs,
rpcCtx: rpcCtx,
sqlInstanceProvider: sqlInstanceProvider,
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)))
})
if rpcCtx != nil {
// rpcCtx might be nil in some tests.
rpcCtx.Stopper.AddCloser(dsp.parallelLocalScansSem.Closer("stopper"))
}
dsp.initRunners(ctx)
dsp.initCancelingWorkers(ctx)
return dsp
}
// 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))
}
// SetSQLInstanceInfo sets the planner's node descriptor.
// The first call to SetSQLInstanceInfo leads to the construction of the SpanResolver.
func (dsp *DistSQLPlanner) SetSQLInstanceInfo(desc roachpb.NodeDescriptor) {
dsp.gatewaySQLInstanceID = base.SQLInstanceID(desc.NodeID)
if dsp.spanResolver == nil {
sr := physicalplan.NewSpanResolver(dsp.st, dsp.distSender, dsp.nodeDescs, desc,
dsp.clock, dsp.rpcCtx, ReplicaOraclePolicy)
dsp.SetSpanResolver(sr)
}
}
// 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.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 {
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() == types.AnyTuple {
v.err = newQueryNotSupportedErrorf("array %s cannot be executed with distsql", t)
return false, expr
}
case *tree.DTuple:
if t.ResolvedType() == 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 }
// 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 *topKNode:
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.
if !specifiedInQuery || planCtx.isLocal {
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 *createStatsNode:
if n.runAsJob {
return cannotDistribute, planNodeNotSupportedErr
}
return shouldDistribute, nil
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:
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); err != nil {
return cannotDistribute, err
}
return checkSupportForPlanNode(n.input)
case *invertedFilterNode:
return checkSupportForInvertedFilterNode(n)
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 := checkExpr(n.onExpr); err != nil {
return cannotDistribute, err
}
rec, err := checkSupportForPlanNode(n.input)
if err != nil {
return cannotDistribute, err
}
return rec.compose(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.lookupExpr); err != nil {
return cannotDistribute, err
}
if err := checkExpr(n.remoteLookupExpr); err != nil {
return cannotDistribute, err
}
if err := checkExpr(n.onCond); err != nil {
return cannotDistribute, err
}
rec, err := checkSupportForPlanNode(n.input)
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:
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
}
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)
if err != nil {
return cannotDistribute, err
}
return rec.compose(shouldDistribute), nil
case *topKNode:
rec, err := checkSupportForPlanNode(n.plan)
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)
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:
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 := 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
// 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
// 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 {
ExtendedEvalCtx *extendedEvalContext
spanIter physicalplan.SpanResolverIterator
// NodesStatuses 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
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.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 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 func(map[base.SQLInstanceID]*execinfrapb.FlowSpec, execopnode.OpChains) error
// If set, we will record the mapping from planNode to tracing metadata to
// later allow associating statistics with the planNode.
traceMetadata execNodeTraceMetadata
// 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
// 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 hold onto throughout the whole flow lifecycle.
onFlowCleanup []func()
}
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
}
// getDefaultSaveFlowsFunc returns the default function used to save physical
// plans and their diagrams.
func (p *PlanningCtx) getDefaultSaveFlowsFunc(
ctx context.Context, planner *planner, typ planComponentType,
) func(map[base.SQLInstanceID]*execinfrapb.FlowSpec, execopnode.OpChains) error {
return func(flows map[base.SQLInstanceID]*execinfrapb.FlowSpec, opChains execopnode.OpChains) error {
var diagram execinfrapb.FlowDiagram
if planner.instrumentation.shouldSaveDiagrams() {
diagramFlags := execinfrapb.DiagramFlags{
MakeDeterministic: planner.execCfg.TestingKnobs.DeterministicExplain,
}
var err error
diagram, err = p.flowSpecsToDiagram(ctx, flows, diagramFlags)
if err != nil {
return err
}
}
var explainVec []string
var explainVecVerbose []string
if planner.instrumentation.collectBundle && planner.curPlan.flags.IsSet(planFlagVectorized) {
flowCtx := newFlowCtxForExplainPurposes(p, planner)
getExplain := func(verbose bool) []string {
explain, cleanup, err := colflow.ExplainVec(
ctx, flowCtx, flows, p.infra.LocalProcessors, opChains,
planner.extendedEvalCtx.DistSQLPlanner.gatewaySQLInstanceID,
verbose, planner.curPlan.flags.IsDistributed(),
)
cleanup()
if err != nil {
// In some edge cases (like when subqueries are present or
// when certain component doesn't implement execopnode.OpNode
// interface) an error might occur. In such scenario, we
// don't want to fail the collection of the bundle, so we
// deliberately ignoring the error.
explain = nil
}
return explain
}
explainVec = getExplain(false /* verbose */)
explainVecVerbose = getExplain(true /* verbose */)
}
planner.curPlan.distSQLFlowInfos = append(
planner.curPlan.distSQLFlowInfos,
flowInfo{
typ: typ,
diagram: diagram,
explainVec: explainVec,
explainVecVerbose: explainVecVerbose,
flowsMetadata: execstats.NewFlowsMetadata(flows),
},
)
return nil
}
}
// flowSpecsToDiagram is a helper function used to convert flowSpecs into a
// FlowDiagram using this PlanningCtx's information.
func (p *PlanningCtx) flowSpecsToDiagram(
ctx context.Context,
flows map[base.SQLInstanceID]*execinfrapb.FlowSpec,
diagramFlags execinfrapb.DiagramFlags,
) (execinfrapb.FlowDiagram, error) {
log.VEvent(ctx, 1, "creating plan diagram")
var stmtStr string
if p.planner != nil && p.planner.stmt.AST != nil {
stmtStr = p.planner.stmt.String()
}
diagram, err := execinfrapb.GeneratePlanDiagram(
stmtStr, flows, diagramFlags,
)
if err != nil {
return nil, err
}
return diagram, nil
}
// getCleanupFunc returns a non-nil function that needs to be called after the
// local flow finished running. This can be called only after the physical
// planning has been completed.
func (p *PlanningCtx) getCleanupFunc() func() {
return func() {
for _, r := range p.onFlowCleanup {
r()
}
}
}
// 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
}
// 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 associates a subset of spans with a specific SQL instance,
// chosen to have the most efficient access to those spans. In the single-tenant
// case, the instance is the one running on the same node as the leaseholder for
// those spans.
type SpanPartition struct {
SQLInstanceID base.SQLInstanceID
Spans roachpb.Spans
}
type distSQLNodeHealth struct {
gossip gossip.OptionalGossip
isAvailable func(base.SQLInstanceID) bool
connHealth func(roachpb.NodeID, rpc.ConnectionClass) error
}
func (h *distSQLNodeHealth) check(ctx context.Context, sqlInstanceID base.SQLInstanceID) 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(roachpb.NodeID(sqlInstanceID), 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 sqlInstanceID (which
// always has its address in the nodeMap).
log.VEventf(ctx, 1, "marking n%d as unhealthy for this plan: %v", sqlInstanceID, err)
return err
}
}
if !h.isAvailable(sqlInstanceID) {
return pgerror.Newf(pgcode.CannotConnectNow, "not using n%d since it is not available", sqlInstanceID)
}
// 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(sqlInstanceID), 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", sqlInstanceID)
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).