-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathexecplan.go
1607 lines (1529 loc) · 60.5 KB
/
execplan.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 2019 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 colexec
import (
"context"
"fmt"
"math"
"reflect"
"github.com/cockroachdb/cockroach/pkg/col/coltypes"
"github.com/cockroachdb/cockroach/pkg/sql/colcontainer"
"github.com/cockroachdb/cockroach/pkg/sql/colexec/execerror"
"github.com/cockroachdb/cockroach/pkg/sql/colexec/typeconv"
"github.com/cockroachdb/cockroach/pkg/sql/execinfra"
"github.com/cockroachdb/cockroach/pkg/sql/execinfrapb"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/errors"
"github.com/marusama/semaphore"
)
func checkNumIn(inputs []Operator, numIn int) error {
if len(inputs) != numIn {
return errors.Errorf("expected %d input(s), got %d", numIn, len(inputs))
}
return nil
}
// wrapRowSources, given input Operators, integrates toWrap into a columnar
// execution flow and returns toWrap's output as an Operator.
func wrapRowSources(
ctx context.Context,
flowCtx *execinfra.FlowCtx,
inputs []Operator,
inputTypes [][]types.T,
acc *mon.BoundAccount,
newToWrap func([]execinfra.RowSource) (execinfra.RowSource, error),
) (*Columnarizer, error) {
var (
toWrapInputs []execinfra.RowSource
// TODO(asubiotto): Plumb proper processorIDs once we have stats.
processorID int32
)
for i, input := range inputs {
// Optimization: if the input is a Columnarizer, its input is necessarily a
// execinfra.RowSource, so remove the unnecessary conversion.
if c, ok := input.(*Columnarizer); ok {
// TODO(asubiotto): We might need to do some extra work to remove references
// to this operator (e.g. streamIDToOp).
toWrapInputs = append(toWrapInputs, c.input)
} else {
toWrapInput, err := NewMaterializer(
flowCtx,
processorID,
input,
inputTypes[i],
&execinfrapb.PostProcessSpec{},
nil, /* output */
nil, /* metadataSourcesQueue */
nil, /* outputStatsToTrace */
nil, /* cancelFlow */
)
if err != nil {
return nil, err
}
toWrapInputs = append(toWrapInputs, toWrapInput)
}
}
toWrap, err := newToWrap(toWrapInputs)
if err != nil {
return nil, err
}
return NewColumnarizer(ctx, NewAllocator(ctx, acc), flowCtx, processorID, toWrap)
}
// NewColOperatorArgs is a helper struct that encompasses all of the input
// arguments to NewColOperator call.
type NewColOperatorArgs struct {
Spec *execinfrapb.ProcessorSpec
Inputs []Operator
StreamingMemAccount *mon.BoundAccount
ProcessorConstructor execinfra.ProcessorConstructor
DiskQueueCfg colcontainer.DiskQueueCfg
FDSemaphore semaphore.Semaphore
TestingKnobs struct {
// UseStreamingMemAccountForBuffering specifies whether to use
// StreamingMemAccount when creating buffering operators and should only be
// set to 'true' in tests. The idea behind this flag is reducing the number
// of memory accounts and monitors we need to close, so we plumbed it into
// the planning code so that it doesn't create extra memory monitoring
// infrastructure (and so that we could use testMemAccount defined in
// main_test.go).
UseStreamingMemAccountForBuffering bool
// SpillingCallbackFn will be called when the spilling from an in-memory to
// disk-backed operator occurs. It should only be set in tests.
SpillingCallbackFn func()
// DiskSpillingDisabled specifies whether only in-memory operators should
// be created.
DiskSpillingDisabled bool
// MaxNumberPartitions determines the maximum number of "active"
// partitions for Partitioner interface.
MaxNumberPartitions int
}
}
// NewColOperatorResult is a helper struct that encompasses all of the return
// values of NewColOperator call.
type NewColOperatorResult struct {
Op Operator
ColumnTypes []types.T
InternalMemUsage int
MetadataSources []execinfrapb.MetadataSource
IsStreaming bool
// CanRunInAutoMode returns whether the result can be run in auto mode if
// IsStreaming is false. This applies to operators that can spill to disk, but
// also operators such as the hash aggregator that buffer, but not
// proportionally to the input size (in the hash aggregator's case, it is the
// number of distinct groups).
CanRunInAutoMode bool
BufferingOpMemMonitors []*mon.BytesMonitor
BufferingOpMemAccounts []*mon.BoundAccount
}
// isSupported checks whether we have a columnar operator equivalent to a
// processor described by spec. Note that it doesn't perform any other checks
// (like validity of the number of inputs).
func isSupported(spec *execinfrapb.ProcessorSpec) (bool, error) {
core := spec.Core
switch {
case core.Noop != nil:
return true, nil
case core.TableReader != nil:
if core.TableReader.IsCheck {
return false, errors.Newf("scrub table reader is unsupported in vectorized")
}
return true, nil
case core.Aggregator != nil:
aggSpec := core.Aggregator
for _, agg := range aggSpec.Aggregations {
if agg.Distinct {
return false, errors.Newf("distinct aggregation not supported")
}
if agg.FilterColIdx != nil {
return false, errors.Newf("filtering aggregation not supported")
}
if len(agg.Arguments) > 0 {
return false, errors.Newf("aggregates with arguments not supported")
}
var inputTypes []types.T
for _, colIdx := range agg.ColIdx {
inputTypes = append(inputTypes, spec.Input[0].ColumnTypes[colIdx])
}
if supported, err := isAggregateSupported(agg.Func, inputTypes); !supported {
return false, err
}
}
return true, nil
case core.Distinct != nil:
return true, nil
case core.Ordinality != nil:
return true, nil
case core.HashJoiner != nil:
if !core.HashJoiner.OnExpr.Empty() &&
core.HashJoiner.Type != sqlbase.JoinType_INNER {
return false, errors.Newf("can't plan non-inner hash join with on expressions")
}
return true, nil
case core.MergeJoiner != nil:
if !core.MergeJoiner.OnExpr.Empty() {
switch core.MergeJoiner.Type {
case sqlbase.JoinType_INNER, sqlbase.JoinType_LEFT_SEMI, sqlbase.JoinType_LEFT_ANTI:
default:
return false, errors.Errorf("can only plan INNER, LEFT SEMI, and LEFT ANTI merge joins with ON expressions")
}
}
return true, nil
case core.Sorter != nil:
// TODO(asubiotto): Do we have to add anything here regarding supporting the
// interval type.
return true, nil
case core.Windower != nil:
if len(core.Windower.WindowFns) != 1 {
return false, errors.Newf("only a single window function is currently supported")
}
wf := core.Windower.WindowFns[0]
if wf.Frame != nil &&
(wf.Frame.Mode != execinfrapb.WindowerSpec_Frame_RANGE ||
wf.Frame.Bounds.Start.BoundType != execinfrapb.WindowerSpec_Frame_UNBOUNDED_PRECEDING ||
(wf.Frame.Bounds.End != nil && wf.Frame.Bounds.End.BoundType != execinfrapb.WindowerSpec_Frame_CURRENT_ROW)) {
return false, errors.Newf("window functions with non-default window frames are not supported")
}
if wf.Func.AggregateFunc != nil {
return false, errors.Newf("aggregate functions used as window functions are not supported")
}
switch *wf.Func.WindowFunc {
case execinfrapb.WindowerSpec_ROW_NUMBER:
case execinfrapb.WindowerSpec_RANK:
case execinfrapb.WindowerSpec_DENSE_RANK:
default:
return false, errors.Newf("window function %s is not supported", wf.String())
}
return true, nil
default:
return false, errors.Newf("unsupported processor core %q", core)
}
}
// NewColOperator creates a new columnar operator according to the given spec.
func NewColOperator(
ctx context.Context, flowCtx *execinfra.FlowCtx, args NewColOperatorArgs,
) (result NewColOperatorResult, err error) {
// Make sure that we clean up memory monitoring infrastructure in case of an
// error or a panic.
defer func() {
returnedErr := err
panicErr := recover()
if returnedErr != nil || panicErr != nil {
for _, memAccount := range result.BufferingOpMemAccounts {
memAccount.Close(ctx)
}
result.BufferingOpMemAccounts = result.BufferingOpMemAccounts[:0]
for _, memMonitor := range result.BufferingOpMemMonitors {
memMonitor.Stop(ctx)
}
result.BufferingOpMemMonitors = result.BufferingOpMemMonitors[:0]
}
if panicErr != nil {
execerror.VectorizedInternalPanic(panicErr)
}
}()
spec := args.Spec
inputs := args.Inputs
streamingMemAccount := args.StreamingMemAccount
useStreamingMemAccountForBuffering := args.TestingKnobs.UseStreamingMemAccountForBuffering
processorConstructor := args.ProcessorConstructor
log.VEventf(ctx, 2, "planning col operator for spec %q", spec)
core := &spec.Core
post := &spec.Post
// By default, we safely assume that an operator is not streaming. Note that
// projections, renders, filters, limits, offsets as well as all internal
// operators (like stats collectors and cancel checkers) are streaming, so in
// order to determine whether the resulting chain of operators is streaming,
// it is sufficient to look only at the "core" operator.
result.IsStreaming = false
supported, err := isSupported(spec)
if !supported {
// We refuse to wrap LocalPlanNode processor (which is a DistSQL wrapper
// around a planNode) because it creates complications, and a flow with
// such processor probably will not benefit from the vectorization.
if core.LocalPlanNode != nil {
return result, errors.Newf("core.LocalPlanNode is not supported")
}
// We also do not wrap MetadataTest{Sender,Receiver} because of the way
// metadata is propagated through the vectorized flow - it is drained at
// the flow shutdown unlike these test processors expect.
if core.MetadataTestSender != nil {
return result, errors.Newf("core.MetadataTestSender is not supported")
}
if core.MetadataTestReceiver != nil {
return result, errors.Newf("core.MetadataTestReceiver is not supported")
}
log.VEventf(ctx, 1, "planning a wrapped processor because %s", err.Error())
var (
c *Columnarizer
inputTypes [][]types.T
)
for _, input := range spec.Input {
inputTypes = append(inputTypes, input.ColumnTypes)
}
c, err = wrapRowSources(
ctx,
flowCtx,
inputs,
inputTypes,
streamingMemAccount,
func(inputs []execinfra.RowSource) (execinfra.RowSource, error) {
// We provide a slice with a single nil as 'outputs' parameter because
// all processors expect a single output. Passing nil is ok here
// because when wrapping the processor, the materializer will be its
// output, and it will be set up in wrapRowSources.
proc, err := processorConstructor(
ctx, flowCtx, spec.ProcessorID, core, post, inputs,
[]execinfra.RowReceiver{nil}, /* outputs */
nil, /* localProcessors */
)
if err != nil {
return nil, err
}
var (
rs execinfra.RowSource
ok bool
)
if rs, ok = proc.(execinfra.RowSource); !ok {
return nil, errors.Newf(
"processor %s is not an execinfra.RowSource", core.String(),
)
}
// The wrapped processors need to be passed the post-process specs,
// since they inspect them to figure out information about needed
// columns. This means that we'll let those processors do any renders
// or filters, which isn't ideal. We could improve this.
post = &execinfrapb.PostProcessSpec{}
result.ColumnTypes = rs.OutputTypes()
return rs, nil
},
)
// We say that the wrapped processor is "streaming" because it is not a
// buffering operator (even if it is a buffering processor). This is not a
// problem for memory accounting because each processor does that on its
// own, so the used memory will be accounted for.
result.Op, result.IsStreaming = c, true
result.MetadataSources = append(result.MetadataSources, c)
} else {
switch {
case core.Noop != nil:
if err := checkNumIn(inputs, 1); err != nil {
return result, err
}
result.Op, result.IsStreaming = NewNoop(inputs[0]), true
result.ColumnTypes = spec.Input[0].ColumnTypes
case core.TableReader != nil:
if err := checkNumIn(inputs, 0); err != nil {
return result, err
}
var scanOp *colBatchScan
scanOp, err = newColBatchScan(NewAllocator(ctx, streamingMemAccount), flowCtx, core.TableReader, post)
if err != nil {
return result, err
}
result.Op, result.IsStreaming = scanOp, true
result.MetadataSources = append(result.MetadataSources, scanOp)
// colBatchScan is wrapped with a cancel checker below, so we need to
// log its creation separately.
log.VEventf(ctx, 1, "made op %T\n", result.Op)
// We want to check for cancellation once per input batch, and wrapping
// only colBatchScan with a CancelChecker allows us to do just that.
// It's sufficient for most of the operators since they are extremely fast.
// However, some of the long-running operators (for example, sorter) are
// still responsible for doing the cancellation check on their own while
// performing long operations.
result.Op = NewCancelChecker(result.Op)
returnMutations := core.TableReader.Visibility == execinfrapb.ScanVisibility_PUBLIC_AND_NOT_PUBLIC
result.ColumnTypes = core.TableReader.Table.ColumnTypesWithMutations(returnMutations)
case core.Aggregator != nil:
if err := checkNumIn(inputs, 1); err != nil {
return result, err
}
aggSpec := core.Aggregator
if len(aggSpec.Aggregations) == 0 {
// We can get an aggregator when no aggregate functions are present if
// HAVING clause is present, for example, with a query as follows:
// SELECT 1 FROM t HAVING true. In this case, we plan a special operator
// that outputs a batch of length 1 without actual columns once and then
// zero-length batches. The actual "data" will be added by projections
// below.
// TODO(solon): The distsql plan for this case includes a TableReader, so
// we end up creating an orphaned colBatchScan. We should avoid that.
// Ideally the optimizer would not plan a scan in this unusual case.
result.Op, result.IsStreaming, err = NewSingleTupleNoInputOp(NewAllocator(ctx, streamingMemAccount)), true, nil
// We make ColumnTypes non-nil so that sanity check doesn't panic.
result.ColumnTypes = make([]types.T, 0)
break
}
if len(aggSpec.GroupCols) == 0 &&
len(aggSpec.Aggregations) == 1 &&
aggSpec.Aggregations[0].FilterColIdx == nil &&
aggSpec.Aggregations[0].Func == execinfrapb.AggregatorSpec_COUNT_ROWS &&
!aggSpec.Aggregations[0].Distinct {
result.Op, result.IsStreaming, err = NewCountOp(NewAllocator(ctx, streamingMemAccount), inputs[0]), true, nil
result.ColumnTypes = []types.T{*types.Int}
break
}
var groupCols, orderedCols util.FastIntSet
for _, col := range aggSpec.OrderedGroupCols {
orderedCols.Add(int(col))
}
needHash := false
for _, col := range aggSpec.GroupCols {
if !orderedCols.Contains(int(col)) {
needHash = true
}
groupCols.Add(int(col))
}
if !orderedCols.SubsetOf(groupCols) {
return result, errors.AssertionFailedf("ordered cols must be a subset of grouping cols")
}
aggTyps := make([][]types.T, len(aggSpec.Aggregations))
aggCols := make([][]uint32, len(aggSpec.Aggregations))
aggFns := make([]execinfrapb.AggregatorSpec_Func, len(aggSpec.Aggregations))
result.ColumnTypes = make([]types.T, len(aggSpec.Aggregations))
for i, agg := range aggSpec.Aggregations {
aggTyps[i] = make([]types.T, len(agg.ColIdx))
for j, colIdx := range agg.ColIdx {
aggTyps[i][j] = spec.Input[0].ColumnTypes[colIdx]
}
aggCols[i] = agg.ColIdx
aggFns[i] = agg.Func
_, retType, err := execinfrapb.GetAggregateInfo(agg.Func, aggTyps[i]...)
if err != nil {
return result, err
}
result.ColumnTypes[i] = *retType
}
var typs []coltypes.T
typs, err = typeconv.FromColumnTypes(spec.Input[0].ColumnTypes)
if err != nil {
return result, err
}
if needHash {
hashAggregatorMemAccount := streamingMemAccount
if !useStreamingMemAccountForBuffering {
hashAggregatorMemAccount = result.createBufferingMemAccount(ctx, flowCtx, "hash-aggregator")
}
result.Op, err = NewHashAggregator(
NewAllocator(ctx, hashAggregatorMemAccount), inputs[0], typs, aggFns,
aggSpec.GroupCols, aggCols,
)
} else {
result.Op, err = NewOrderedAggregator(
NewAllocator(ctx, streamingMemAccount), inputs[0], typs, aggFns,
aggSpec.GroupCols, aggCols, execinfrapb.IsScalarAggregate(aggSpec),
)
result.IsStreaming = true
}
case core.Distinct != nil:
if err := checkNumIn(inputs, 1); err != nil {
return result, err
}
var distinctCols, orderedCols util.FastIntSet
allSorted := true
for _, col := range core.Distinct.OrderedColumns {
orderedCols.Add(int(col))
}
for _, col := range core.Distinct.DistinctColumns {
distinctCols.Add(int(col))
if !orderedCols.Contains(int(col)) {
allSorted = false
}
}
if !orderedCols.SubsetOf(distinctCols) {
return result, errors.AssertionFailedf("ordered cols must be a subset of distinct cols")
}
result.ColumnTypes = spec.Input[0].ColumnTypes
var typs []coltypes.T
typs, err = typeconv.FromColumnTypes(result.ColumnTypes)
if err != nil {
return result, err
}
// TODO(yuzefovich): implement the distinct on partially ordered columns.
if allSorted {
result.Op, err = NewOrderedDistinct(inputs[0], core.Distinct.OrderedColumns, typs)
result.IsStreaming = true
} else {
result.Op = NewUnorderedDistinct(
NewAllocator(ctx, streamingMemAccount), inputs[0],
core.Distinct.DistinctColumns, typs,
)
}
case core.Ordinality != nil:
if err := checkNumIn(inputs, 1); err != nil {
return result, err
}
outputIdx := len(spec.Input[0].ColumnTypes)
result.Op, result.IsStreaming = NewOrdinalityOp(NewAllocator(ctx, streamingMemAccount), inputs[0], outputIdx), true
result.ColumnTypes = append(spec.Input[0].ColumnTypes, *types.Int)
case core.HashJoiner != nil:
if err := checkNumIn(inputs, 2); err != nil {
return result, err
}
leftLogTypes := spec.Input[0].ColumnTypes
leftPhysTypes, err := typeconv.FromColumnTypes(leftLogTypes)
if err != nil {
return result, err
}
rightLogTypes := spec.Input[1].ColumnTypes
rightPhysTypes, err := typeconv.FromColumnTypes(rightLogTypes)
if err != nil {
return result, err
}
hashJoinerMemMonitorName := fmt.Sprintf("hash-joiner-%d", spec.ProcessorID)
var hashJoinerMemAccount *mon.BoundAccount
if useStreamingMemAccountForBuffering {
hashJoinerMemAccount = streamingMemAccount
} else {
hashJoinerMemAccount = result.createBufferingMemAccount(
ctx, flowCtx, hashJoinerMemMonitorName,
)
}
// It is valid for empty set of equality columns to be considered as
// "key" (for example, the input has at most 1 row). However, hash
// joiner, in order to handle NULL values correctly, needs to think
// that an empty set of equality columns doesn't form a key.
rightEqColsAreKey := core.HashJoiner.RightEqColumnsAreKey && len(core.HashJoiner.RightEqColumns) > 0
hjSpec, err := makeHashJoinerSpec(
core.HashJoiner.Type,
core.HashJoiner.LeftEqColumns,
core.HashJoiner.RightEqColumns,
leftPhysTypes,
rightPhysTypes,
rightEqColsAreKey,
)
if err != nil {
return result, err
}
inMemoryHashJoiner := newHashJoiner(
NewAllocator(ctx, hashJoinerMemAccount), hjSpec, inputs[0], inputs[1],
)
if args.TestingKnobs.DiskSpillingDisabled {
// We will not be creating a disk-backed hash joiner because we're
// running a test that explicitly asked for only in-memory hash
// joiner.
result.Op = inMemoryHashJoiner
} else {
result.Op = newTwoInputDiskSpiller(
inputs[0], inputs[1], inMemoryHashJoiner.(bufferingInMemoryOperator),
hashJoinerMemMonitorName,
func(inputOne, inputTwo Operator) Operator {
monitorNamePrefix := "external-hash-joiner"
allocator := NewAllocator(
// Pass in the default limit explicitly since we don't want to
// use the default memory limit of 1 if ForceDiskSpill is true, to
// allow for the external hash join to have a normal amount of
// memory (for initialization and internal joining).
ctx, result.createBufferingMemAccountWithLimit(
ctx, flowCtx, monitorNamePrefix, execinfra.GetWorkMemLimit(flowCtx.Cfg),
))
return newExternalHashJoiner(allocator, hjSpec, inputOne, inputTwo, args.DiskQueueCfg, args.FDSemaphore)
},
args.TestingKnobs.SpillingCallbackFn,
)
}
result.ColumnTypes = append(leftLogTypes, rightLogTypes...)
if !core.HashJoiner.OnExpr.Empty() && core.HashJoiner.Type == sqlbase.JoinType_INNER {
// We will plan other Operators on top of the hash joiner, so we need
// to account for the internal memory explicitly.
if internalMemOp, ok := result.Op.(InternalMemoryOperator); ok {
result.InternalMemUsage += internalMemOp.InternalMemoryUsage()
}
if err = result.planFilterExpr(
ctx, flowCtx.NewEvalCtx(), core.HashJoiner.OnExpr, streamingMemAccount,
); err != nil {
return result, err
}
}
case core.MergeJoiner != nil:
if err := checkNumIn(inputs, 2); err != nil {
return result, err
}
if core.MergeJoiner.Type.IsSetOpJoin() {
return result, errors.AssertionFailedf("unexpectedly %s merge join was planned", core.MergeJoiner.Type.String())
}
// Merge joiner is a streaming operator when equality columns form a key
// for both of the inputs.
result.IsStreaming = core.MergeJoiner.LeftEqColumnsAreKey && core.MergeJoiner.RightEqColumnsAreKey
leftLogTypes := spec.Input[0].ColumnTypes
leftPhysTypes, err := typeconv.FromColumnTypes(leftLogTypes)
if err != nil {
return result, err
}
rightLogTypes := spec.Input[1].ColumnTypes
rightPhysTypes, err := typeconv.FromColumnTypes(rightLogTypes)
if err != nil {
return result, err
}
var (
onExpr *execinfrapb.Expression
filterOnlyOnLeft bool
filterConstructor func(Operator) (Operator, error)
)
joinType := core.MergeJoiner.Type
if !core.MergeJoiner.OnExpr.Empty() {
// At the moment, we want to be on the conservative side and not run
// queries with ON expressions when vectorize=auto, so we say that the
// merge join is not streaming which will reject running such a query
// through vectorized engine with 'auto' setting.
// TODO(yuzefovich): remove this when we're confident in ON expression
// support.
result.IsStreaming = false
onExpr = &core.MergeJoiner.OnExpr
switch joinType {
case sqlbase.JoinType_LEFT_SEMI, sqlbase.JoinType_LEFT_ANTI:
onExprPlanning := makeFilterPlanningState(len(leftPhysTypes), len(rightPhysTypes))
filterOnlyOnLeft, err = onExprPlanning.isFilterOnlyOnLeft(*onExpr)
filterConstructor = func(op Operator) (Operator, error) {
r := NewColOperatorResult{
Op: op,
ColumnTypes: append(leftLogTypes, rightLogTypes...),
}
err := r.planFilterExpr(ctx, flowCtx.NewEvalCtx(), *onExpr, streamingMemAccount)
return r.Op, err
}
}
}
if err != nil {
return result, err
}
mergeJoinerMemAccount := streamingMemAccount
if !result.IsStreaming && !useStreamingMemAccountForBuffering {
// Whether the merge joiner is streaming is already set above.
mergeJoinerMemAccount = result.createBufferingMemAccount(ctx, flowCtx, "merge-joiner")
}
result.Op, err = NewMergeJoinOp(
NewAllocator(ctx, mergeJoinerMemAccount),
core.MergeJoiner.Type,
inputs[0],
inputs[1],
leftPhysTypes,
rightPhysTypes,
core.MergeJoiner.LeftOrdering.Columns,
core.MergeJoiner.RightOrdering.Columns,
filterConstructor,
filterOnlyOnLeft,
)
if err != nil {
return result, err
}
result.ColumnTypes = append(leftLogTypes, rightLogTypes...)
if onExpr != nil && joinType == sqlbase.JoinType_INNER {
// We will plan other Operators on top of the merge joiner, so we need
// to account for the internal memory explicitly.
if internalMemOp, ok := result.Op.(InternalMemoryOperator); ok {
result.InternalMemUsage += internalMemOp.InternalMemoryUsage()
}
if err = result.planFilterExpr(
ctx, flowCtx.NewEvalCtx(), *onExpr, streamingMemAccount,
); err != nil {
return result, err
}
}
case core.Sorter != nil:
if err := checkNumIn(inputs, 1); err != nil {
return result, err
}
input := inputs[0]
var (
inputTypes []coltypes.T
sorterMemMonitorName string
inMemorySorter Operator
)
inputTypes, err = typeconv.FromColumnTypes(spec.Input[0].ColumnTypes)
if err != nil {
return result, err
}
for _, t := range inputTypes {
if t == coltypes.Interval {
return result, errors.WithIssueLink(errors.Errorf("sort on interval type not supported"), errors.IssueLink{IssueURL: "https://github.com/cockroachdb/cockroach/issues/45392"})
}
}
orderingCols := core.Sorter.OutputOrdering.Columns
matchLen := core.Sorter.OrderingMatchLen
if len(orderingCols) == int(matchLen) {
// The input is already fully ordered, so there is nothing to sort.
result.Op = input
} else if matchLen > 0 {
// The input is already partially ordered. Use a chunks sorter to avoid
// loading all the rows into memory.
sorterMemMonitorName = fmt.Sprintf("sort-chunks-%d", spec.ProcessorID)
var sortChunksMemAccount *mon.BoundAccount
if useStreamingMemAccountForBuffering {
sortChunksMemAccount = streamingMemAccount
} else {
sortChunksMemAccount = result.createBufferingMemAccount(
ctx, flowCtx, sorterMemMonitorName,
)
}
inMemorySorter, err = NewSortChunks(
NewAllocator(ctx, sortChunksMemAccount), input, inputTypes,
orderingCols, int(matchLen),
)
} else if post.Limit != 0 && post.Filter.Empty() && post.Limit+post.Offset < math.MaxUint16 {
// There is a limit specified with no post-process filter, so we know
// exactly how many rows the sorter should output. Choose a top K sorter,
// which uses a heap to avoid storing more rows than necessary.
sorterMemMonitorName = fmt.Sprintf("topk-sort-%d", spec.ProcessorID)
var topKSorterMemAccount *mon.BoundAccount
if useStreamingMemAccountForBuffering {
topKSorterMemAccount = streamingMemAccount
} else {
topKSorterMemAccount = result.createBufferingMemAccount(
ctx, flowCtx, sorterMemMonitorName,
)
}
k := uint16(post.Limit + post.Offset)
inMemorySorter = NewTopKSorter(
NewAllocator(ctx, topKSorterMemAccount), input, inputTypes,
orderingCols, k,
)
} else {
// No optimizations possible. Default to the standard sort operator.
sorterMemMonitorName = fmt.Sprintf("sort-all-%d", spec.ProcessorID)
var sorterMemAccount *mon.BoundAccount
if useStreamingMemAccountForBuffering {
sorterMemAccount = streamingMemAccount
} else {
sorterMemAccount = result.createBufferingMemAccount(
ctx, flowCtx, sorterMemMonitorName,
)
}
inMemorySorter, err = NewSorter(
NewAllocator(ctx, sorterMemAccount), input, inputTypes, orderingCols,
)
}
if err != nil {
return result, err
}
if inMemorySorter != nil {
// NOTE: when spilling to disk, we're using the same general external
// sorter regardless of which sorter variant we have instantiated (i.e.
// we don't take advantage of the limits and of partial ordering). We
// could improve this.
result.Op = newOneInputDiskSpiller(
input, inMemorySorter.(bufferingInMemoryOperator),
sorterMemMonitorName,
func(input Operator) Operator {
monitorNamePrefix := "external-sorter"
// We are using an unlimited memory monitor here because external
// sort itself is responsible for making sure that we stay within
// the memory limit.
unlimitedAllocator := NewAllocator(
ctx, result.createBufferingUnlimitedMemAccount(
ctx, flowCtx, monitorNamePrefix,
))
standaloneAllocator := NewAllocator(
ctx, result.createStandaloneMemAccount(
ctx, flowCtx, monitorNamePrefix,
))
return newExternalSorter(
unlimitedAllocator,
standaloneAllocator,
input, inputTypes, core.Sorter.OutputOrdering,
execinfra.GetWorkMemLimit(flowCtx.Cfg),
args.TestingKnobs.MaxNumberPartitions,
args.DiskQueueCfg,
args.FDSemaphore,
)
},
args.TestingKnobs.SpillingCallbackFn,
)
}
result.ColumnTypes = spec.Input[0].ColumnTypes
// A sorter can run in auto mode because it falls back to disk if there
// is not enough memory available.
result.CanRunInAutoMode = true
case core.Windower != nil:
if err := checkNumIn(inputs, 1); err != nil {
return result, err
}
wf := core.Windower.WindowFns[0]
input := inputs[0]
var typs []coltypes.T
typs, err = typeconv.FromColumnTypes(spec.Input[0].ColumnTypes)
if err != nil {
return result, err
}
tempPartitionColOffset, partitionColIdx := 0, -1
if len(core.Windower.PartitionBy) > 0 {
// TODO(yuzefovich): add support for hashing partitioner (probably by
// leveraging hash routers once we can distribute). The decision about
// which kind of partitioner to use should come from the optimizer.
windowSortingPartitionerMemAccount := streamingMemAccount
if !useStreamingMemAccountForBuffering {
windowSortingPartitionerMemAccount = result.createBufferingMemAccount(ctx, flowCtx, "window-sorting-partitioner")
}
input, err = NewWindowSortingPartitioner(
NewAllocator(ctx, windowSortingPartitionerMemAccount), input, typs,
core.Windower.PartitionBy, wf.Ordering.Columns, int(wf.OutputColIdx),
)
tempPartitionColOffset, partitionColIdx = 1, int(wf.OutputColIdx)
} else {
if len(wf.Ordering.Columns) > 0 {
windowSorterMemAccount := streamingMemAccount
if !useStreamingMemAccountForBuffering {
windowSorterMemAccount = result.createBufferingMemAccount(ctx, flowCtx, "window-sorter")
}
input, err = NewSorter(
NewAllocator(ctx, windowSorterMemAccount), input, typs,
wf.Ordering.Columns,
)
}
// TODO(yuzefovich): when both PARTITION BY and ORDER BY clauses are
// omitted, the window function operator is actually streaming.
}
if err != nil {
return result, err
}
orderingCols := make([]uint32, len(wf.Ordering.Columns))
for i, col := range wf.Ordering.Columns {
orderingCols[i] = col.ColIdx
}
switch *wf.Func.WindowFunc {
case execinfrapb.WindowerSpec_ROW_NUMBER:
result.Op = NewRowNumberOperator(NewAllocator(ctx, streamingMemAccount), input, int(wf.OutputColIdx)+tempPartitionColOffset, partitionColIdx)
case execinfrapb.WindowerSpec_RANK:
result.Op, err = NewRankOperator(NewAllocator(ctx, streamingMemAccount), input, typs, false /* dense */, orderingCols, int(wf.OutputColIdx)+tempPartitionColOffset, partitionColIdx)
case execinfrapb.WindowerSpec_DENSE_RANK:
result.Op, err = NewRankOperator(NewAllocator(ctx, streamingMemAccount), input, typs, true /* dense */, orderingCols, int(wf.OutputColIdx)+tempPartitionColOffset, partitionColIdx)
}
if partitionColIdx != -1 {
// Window partitioner will append a temporary column to the batch which
// we want to project out.
projection := make([]uint32, 0, wf.OutputColIdx+1)
for i := uint32(0); i < wf.OutputColIdx; i++ {
projection = append(projection, i)
}
projection = append(projection, wf.OutputColIdx+1)
result.Op = NewSimpleProjectOp(result.Op, int(wf.OutputColIdx+1), projection)
}
result.ColumnTypes = append(spec.Input[0].ColumnTypes, *types.Int)
default:
return result, errors.Newf("unsupported processor core %q", core)
}
}
if err != nil {
return result, err
}
// After constructing the base operator, calculate its internal memory usage.
if sMem, ok := result.Op.(InternalMemoryOperator); ok {
result.InternalMemUsage += sMem.InternalMemoryUsage()
}
log.VEventf(ctx, 1, "made op %T\n", result.Op)
// Note: at this point, it is legal for ColumnTypes to be empty (it is
// legal for empty rows to be passed between processors).
if !post.Filter.Empty() {
if err = result.planFilterExpr(
ctx, flowCtx.NewEvalCtx(), post.Filter, streamingMemAccount,
); err != nil {
return result, err
}
}
if post.Projection {
result.addProjection(post.OutputColumns)
} else if post.RenderExprs != nil {
log.VEventf(ctx, 2, "planning render expressions %+v", post.RenderExprs)
var renderedCols []uint32
for _, expr := range post.RenderExprs {
var (
helper execinfra.ExprHelper
renderInternalMem int
)
err := helper.Init(expr, result.ColumnTypes, flowCtx.EvalCtx)
if err != nil {
return result, err
}
var outputIdx int
result.Op, outputIdx, result.ColumnTypes, renderInternalMem, err = planProjectionOperators(
ctx, flowCtx.NewEvalCtx(), helper.Expr, result.ColumnTypes, result.Op, streamingMemAccount,
)
if err != nil {
return result, errors.Wrapf(err, "unable to columnarize render expression %q", expr)
}
if outputIdx < 0 {
return result, errors.AssertionFailedf("missing outputIdx")
}
result.InternalMemUsage += renderInternalMem
renderedCols = append(renderedCols, uint32(outputIdx))
}
result.Op = NewSimpleProjectOp(result.Op, len(result.ColumnTypes), renderedCols)
newTypes := make([]types.T, 0, len(renderedCols))
for _, j := range renderedCols {
newTypes = append(newTypes, result.ColumnTypes[j])
}
result.ColumnTypes = newTypes
}
if post.Offset != 0 {
result.Op = NewOffsetOp(result.Op, post.Offset)
}
if post.Limit != 0 {
result.Op = NewLimitOp(result.Op, post.Limit)
}
return result, err
}
type filterPlanningState struct {
numLeftInputCols int
numRightInputCols int
}
func makeFilterPlanningState(numLeftInputCols, numRightInputCols int) filterPlanningState {
return filterPlanningState{
numLeftInputCols: numLeftInputCols,
numRightInputCols: numRightInputCols,
}
}
// isFilterOnlyOnLeft returns whether the filter expression doesn't use columns
// from the right side.
func (p *filterPlanningState) isFilterOnlyOnLeft(filter execinfrapb.Expression) (bool, error) {
// Find all needed columns for filter only from the right side.
neededColumnsForFilter, err := findIVarsInRange(
filter, p.numLeftInputCols, p.numLeftInputCols+p.numRightInputCols,
)
if err != nil {
return false, errors.Errorf("error parsing filter expression %q: %s", filter, err)
}
return len(neededColumnsForFilter) == 0, nil
}
// createBufferingUnlimitedMemMonitor instantiates an unlimited memory monitor.
// These should only be used when spilling to disk and an operator is made aware
// of a memory usage limit separately.
// The receiver is updated to have a reference to the unlimited memory monitor.
func (r *NewColOperatorResult) createBufferingUnlimitedMemMonitor(
ctx context.Context, flowCtx *execinfra.FlowCtx, name string,
) *mon.BytesMonitor {
bufferingOpUnlimitedMemMonitor := execinfra.NewMonitor(
ctx, flowCtx.EvalCtx.Mon, name+"-unlimited",
)
r.BufferingOpMemMonitors = append(r.BufferingOpMemMonitors, bufferingOpUnlimitedMemMonitor)
return bufferingOpUnlimitedMemMonitor
}
// createBufferingMemAccount instantiates a memory monitor and a memory account
// to be used with a buffering Operator with the default memory limit. The
// receiver is updated to have references to both objects.
func (r *NewColOperatorResult) createBufferingMemAccount(
ctx context.Context, flowCtx *execinfra.FlowCtx, name string,
) *mon.BoundAccount {
bufferingOpMemMonitor := execinfra.NewLimitedMonitor(
ctx, flowCtx.EvalCtx.Mon, flowCtx.Cfg, name+"-limited",
)
r.BufferingOpMemMonitors = append(r.BufferingOpMemMonitors, bufferingOpMemMonitor)
bufferingMemAccount := bufferingOpMemMonitor.MakeBoundAccount()
r.BufferingOpMemAccounts = append(r.BufferingOpMemAccounts, &bufferingMemAccount)
return &bufferingMemAccount
}
// createBufferingMemAccountWithLimit is identical to createBufferingMemAccount
// although it creates a monitor with the provided limit, rather than using the
// default limit. Only disk-aware operators should use this method, as it is
// useful to enforce different limits in testing scenarios.
func (r *NewColOperatorResult) createBufferingMemAccountWithLimit(
ctx context.Context, flowCtx *execinfra.FlowCtx, name string, limit int64,
) *mon.BoundAccount {
limitedMon := mon.MakeMonitorInheritWithLimit(name+"-limited", limit, flowCtx.EvalCtx.Mon)
r.BufferingOpMemMonitors = append(r.BufferingOpMemMonitors, &limitedMon)
limitedMon.Start(ctx, flowCtx.EvalCtx.Mon, mon.BoundAccount{})
bufferingMemAccount := limitedMon.MakeBoundAccount()