-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
execplan.go
1897 lines (1806 loc) · 72.2 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/sessiondata"
"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
// NumForcedRepartitions specifies a number of "repartitions" that a
// disk-backed operator should be forced to perform. "Repartition" can mean
// different things depending on the operator (for example, for hash joiner
// it is dividing original partition into multiple new partitions; for
// sorter it is merging already created partitions into new one before
// proceeding to the next partition from the input).
NumForcedRepartitions 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).
// NOTE: if you set this value to 'false' for some operator, make sure to
// make the corresponding adjustment to 'isSupported' check so that we can
// plan wrapped processor core in the vectorized flow rather than rejecting
// the vectorization entirely in 'auto' mode.
CanRunInAutoMode bool
BufferingOpMemMonitors []*mon.BytesMonitor
BufferingOpMemAccounts []*mon.BoundAccount
}
// resetToState resets r to the state specified in arg. arg may be a shallow
// copy made at a given point in time.
func (r *NewColOperatorResult) resetToState(ctx context.Context, arg NewColOperatorResult) {
// MetadataSources are left untouched since there is no need to do any
// cleaning there.
// Close BoundAccounts that are not present in arg.BufferingOpMemAccounts.
accs := make(map[*mon.BoundAccount]struct{})
for _, a := range arg.BufferingOpMemAccounts {
accs[a] = struct{}{}
}
for _, a := range r.BufferingOpMemAccounts {
if _, ok := accs[a]; !ok {
a.Close(ctx)
}
}
// Stop BytesMonitors that are not present in arg.BufferingOpMemMonitors.
mons := make(map[*mon.BytesMonitor]struct{})
for _, m := range arg.BufferingOpMemMonitors {
mons[m] = struct{}{}
}
for _, m := range r.BufferingOpMemMonitors {
if _, ok := mons[m]; !ok {
m.Stop(ctx)
}
}
// Shallow copy over the rest.
*r = arg
}
const noFilterIdx = -1
// 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(
mode sessiondata.VectorizeExecMode, 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:
if core.Distinct.NullsAreDistinct {
return false, errors.Newf("distinct with unique nulls not supported")
}
if core.Distinct.ErrorOnDup != "" {
return false, errors.Newf("distinct with error on duplicates not supported")
}
if mode != sessiondata.VectorizeExperimentalOn && mode != sessiondata.VectorizeExperimentalAlways {
if len(core.Distinct.OrderedColumns) < len(core.Distinct.DistinctColumns) {
return false, errors.Newf("unordered distinct can only run in 'experimental_on' vectorize mode")
}
}
return true, nil
case core.Ordinality != nil:
return true, nil
case core.HashJoiner != nil:
if !core.HashJoiner.OnExpr.Empty() && core.HashJoiner.Type != sqlbase.InnerJoin {
return false, errors.Newf("can't plan vectorized non-inner hash joins with ON expressions")
}
return true, nil
case core.MergeJoiner != nil:
if !core.MergeJoiner.OnExpr.Empty() &&
core.MergeJoiner.Type != sqlbase.JoinType_INNER {
return false, errors.Errorf("can't plan non-inner merge join with ON expressions")
}
return true, nil
case core.Sorter != nil:
return true, nil
case core.Windower != nil:
for _, wf := range core.Windower.WindowFns {
if wf.Frame != nil {
frame, err := wf.Frame.ConvertToAST()
if err != nil {
return false, err
}
if !frame.IsDefaultFrame() {
return false, errors.Newf("window functions with non-default window frames are not supported")
}
}
if wf.FilterColIdx != noFilterIdx {
return false, errors.Newf("window functions with FILTER clause are not supported")
}
if wf.Func.AggregateFunc != nil {
return false, errors.Newf("aggregate functions used as window functions are not supported")
}
if _, supported := SupportedWindowFns[*wf.Func.WindowFunc]; !supported {
return false, errors.Newf("window function %s is not supported", wf.String())
}
if mode != sessiondata.VectorizeExperimentalOn && mode != sessiondata.VectorizeExperimentalAlways {
switch *wf.Func.WindowFunc {
case execinfrapb.WindowerSpec_PERCENT_RANK, execinfrapb.WindowerSpec_CUME_DIST:
return false, errors.Newf("window function %s can only run in 'experimental_on' vectorize mode", wf.String())
}
}
}
return true, nil
default:
return false, errors.Newf("unsupported processor core %q", core)
}
}
// createDiskBackedSort creates a new disk-backed operator that sorts the input
// according to ordering.
// - matchLen specifies the length of the prefix of ordering columns the input
// is already ordered on.
// - maxNumberPartitions (when non-zero) overrides the semi-dynamically
// computed maximum number of partitions that the external sorter will have
// at once.
// - processorID is the ProcessorID of the processor core that requested
// creation of this operator. It is used only to distinguish memory monitors.
// - post describes the post-processing spec of the processor. It will be used
// to determine whether top K sort can be planned. If you want the general sort
// operator, then pass in empty struct.
func (r *NewColOperatorResult) createDiskBackedSort(
ctx context.Context,
flowCtx *execinfra.FlowCtx,
args NewColOperatorArgs,
input Operator,
inputTypes []coltypes.T,
ordering execinfrapb.Ordering,
matchLen uint32,
maxNumberPartitions int,
processorID int32,
post *execinfrapb.PostProcessSpec,
memMonitorNamePrefix string,
) (Operator, error) {
streamingMemAccount := args.StreamingMemAccount
useStreamingMemAccountForBuffering := args.TestingKnobs.UseStreamingMemAccountForBuffering
var (
sorterMemMonitorName string
inMemorySorter Operator
err error
)
if len(ordering.Columns) == int(matchLen) {
// The input is already fully ordered, so there is nothing to sort.
return input, nil
}
if matchLen > 0 {
// The input is already partially ordered. Use a chunks sorter to avoid
// loading all the rows into memory.
sorterMemMonitorName = fmt.Sprintf("%ssort-chunks-%d", memMonitorNamePrefix, processorID)
var sortChunksMemAccount *mon.BoundAccount
if useStreamingMemAccountForBuffering {
sortChunksMemAccount = streamingMemAccount
} else {
sortChunksMemAccount = r.createMemAccountForSpillStrategy(
ctx, flowCtx, sorterMemMonitorName,
)
}
inMemorySorter, err = NewSortChunks(
NewAllocator(ctx, sortChunksMemAccount), input, inputTypes,
ordering.Columns, 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("%stopk-sort-%d", memMonitorNamePrefix, processorID)
var topKSorterMemAccount *mon.BoundAccount
if useStreamingMemAccountForBuffering {
topKSorterMemAccount = streamingMemAccount
} else {
topKSorterMemAccount = r.createMemAccountForSpillStrategy(
ctx, flowCtx, sorterMemMonitorName,
)
}
k := uint16(post.Limit + post.Offset)
inMemorySorter = NewTopKSorter(
NewAllocator(ctx, topKSorterMemAccount), input, inputTypes,
ordering.Columns, k,
)
} else {
// No optimizations possible. Default to the standard sort operator.
sorterMemMonitorName = fmt.Sprintf("%ssort-all-%d", memMonitorNamePrefix, processorID)
var sorterMemAccount *mon.BoundAccount
if useStreamingMemAccountForBuffering {
sorterMemAccount = streamingMemAccount
} else {
sorterMemAccount = r.createMemAccountForSpillStrategy(
ctx, flowCtx, sorterMemMonitorName,
)
}
inMemorySorter, err = NewSorter(
NewAllocator(ctx, sorterMemAccount), input, inputTypes, ordering.Columns,
)
}
if err != nil {
return nil, err
}
if inMemorySorter == nil {
return nil, errors.AssertionFailedf("unexpectedly inMemorySorter is 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.
return newOneInputDiskSpiller(
input, inMemorySorter.(bufferingInMemoryOperator),
sorterMemMonitorName,
func(input Operator) Operator {
monitorNamePrefix := fmt.Sprintf("%sexternal-sorter", memMonitorNamePrefix)
// 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, r.createBufferingUnlimitedMemAccount(
ctx, flowCtx, monitorNamePrefix,
))
standaloneMemAccount := r.createStandaloneMemAccount(
ctx, flowCtx, monitorNamePrefix,
)
// Make a copy of the DiskQueueCfg and set defaults for the sorter.
// The cache mode is chosen to reuse the cache to have a smaller
// cache per partition without affecting performance.
diskQueueCfg := args.DiskQueueCfg
diskQueueCfg.CacheMode = colcontainer.DiskQueueCacheModeReuseCache
diskQueueCfg.SetDefaultBufferSizeBytesForCacheMode()
if args.TestingKnobs.NumForcedRepartitions != 0 {
maxNumberPartitions = args.TestingKnobs.NumForcedRepartitions
}
return newExternalSorter(
ctx,
unlimitedAllocator,
standaloneMemAccount,
input, inputTypes, ordering,
execinfra.GetWorkMemLimit(flowCtx.Cfg),
maxNumberPartitions,
diskQueueCfg,
args.FDSemaphore,
)
},
args.TestingKnobs.SpillingCallbackFn,
), nil
}
// createAndWrapRowSource takes a processor spec, creating the row source and
// wrapping it using wrapRowSources. Note that the post process spec is included
// in the processor creation, so make sure to clear it if it will be inspected
// again. NewColOperatorResult is updated with the new OutputTypes and the
// resulting Columnarizer if there is no error. The result is also annotated as
// streaming because the resulting operator 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.
func (r *NewColOperatorResult) createAndWrapRowSource(
ctx context.Context,
flowCtx *execinfra.FlowCtx,
inputs []Operator,
inputTypes [][]types.T,
streamingMemAccount *mon.BoundAccount,
spec *execinfrapb.ProcessorSpec,
processorConstructor execinfra.ProcessorConstructor,
) error {
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, &spec.Core, &spec.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", spec.Core.String(),
)
}
r.ColumnTypes = rs.OutputTypes()
return rs, nil
},
)
if err != nil {
return err
}
// 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.
r.Op, r.IsStreaming = c, true
r.MetadataSources = append(r.MetadataSources, c)
return nil
}
// 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
// resultPreSpecPlanningStateShallowCopy is a shallow copy of the result
// before any specs are planned. Used if there is a need to backtrack.
resultPreSpecPlanningStateShallowCopy := result
supported, err := isSupported(flowCtx.EvalCtx.SessionData.VectorizeMode, 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())
inputTypes := make([][]types.T, 0, len(spec.Input))
for _, input := range spec.Input {
inputTypes = append(inputTypes, input.ColumnTypes)
}
err = result.createAndWrapRowSource(ctx, flowCtx, inputs, inputTypes, streamingMemAccount, spec, processorConstructor)
// 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{}
} 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 {
// Create an unlimited mem account explicitly even though there is no
// disk spilling because the memory usage of an aggregator is
// proportional to the number of groups, not the number of inputs.
// The row execution engine also gives an unlimited amount (that still
// needs to be approved by the upstream monitor, so not really
// "unlimited") amount of memory to the aggregator.
hashAggregatorMemAccount = result.createBufferingUnlimitedMemAccount(ctx, flowCtx, "hash-aggregator")
}
result.Op, err = NewHashAggregator(
NewAllocator(ctx, hashAggregatorMemAccount), inputs[0], typs, aggFns,
aggSpec.GroupCols, aggCols,
)
// Auto mode is enabled for hashAggregator since it performs online
// aggregation. This limits memory growth in the aggregator to be
// proportional to the number of distinct groups. hashAggregator does
// not spill to disk, but neither does the hashAggregator in the row
// execution engine.
result.CanRunInAutoMode = true
} 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
}
result.ColumnTypes = spec.Input[0].ColumnTypes
var typs []coltypes.T
typs, err = typeconv.FromColumnTypes(result.ColumnTypes)
if err != nil {
return result, err
}
if len(core.Distinct.OrderedColumns) == len(core.Distinct.DistinctColumns) {
result.Op, err = NewOrderedDistinct(inputs[0], core.Distinct.OrderedColumns, typs)
result.IsStreaming = true
} else {
distinctMemAccount := streamingMemAccount
if !useStreamingMemAccountForBuffering {
// Create an unlimited mem account explicitly even though there is no
// disk spilling because the memory usage of an unordered distinct
// operator is proportional to the number of distinct tuples, not the
// number of input tuples.
// The row execution engine also gives an unlimited amount (that still
// needs to be approved by the upstream monitor, so not really
// "unlimited") amount of memory to the unordered distinct operator.
distinctMemAccount = result.createBufferingUnlimitedMemAccount(ctx, flowCtx, "distinct")
}
// TODO(yuzefovich): we have an implementation of partially ordered
// distinct, and we should plan it when we have non-empty ordered
// columns and we think that the probability of distinct tuples in the
// input is about 0.01 or less.
result.Op = NewUnorderedDistinct(
NewAllocator(ctx, distinctMemAccount), inputs[0],
core.Distinct.DistinctColumns, typs, hashTableNumBuckets,
)
}
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.createMemAccountForSpillStrategy(
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"
unlimitedAllocator := NewAllocator(
ctx, result.createBufferingUnlimitedMemAccount(
ctx, flowCtx, monitorNamePrefix,
))
// Make a copy of the DiskQueueCfg and set defaults for the hash
// joiner. The cache mode is chosen to automatically close the cache
// belonging to partitions at a parent level when repartitioning.
diskQueueCfg := args.DiskQueueCfg
diskQueueCfg.CacheMode = colcontainer.DiskQueueCacheModeClearAndReuseCache
diskQueueCfg.SetDefaultBufferSizeBytesForCacheMode()
return newExternalHashJoiner(
unlimitedAllocator, hjSpec,
inputOne, inputTwo,
execinfra.GetWorkMemLimit(flowCtx.Cfg),
diskQueueCfg,
args.FDSemaphore,
func(input Operator, inputTypes []coltypes.T, orderingCols []execinfrapb.Ordering_Column, maxNumberPartitions int) (Operator, error) {
return result.createDiskBackedSort(
ctx, flowCtx, args, input, inputTypes,
execinfrapb.Ordering{Columns: orderingCols},
0 /* matchLen */, maxNumberPartitions, spec.ProcessorID,
&execinfrapb.PostProcessSpec{}, monitorNamePrefix+"-")
},
args.TestingKnobs.NumForcedRepartitions,
)
},
args.TestingKnobs.SpillingCallbackFn,
)
// A hash joiner can run in auto mode because it falls back to disk if
// there is not enough memory available.
result.CanRunInAutoMode = true
}
result.ColumnTypes = append(leftLogTypes, rightLogTypes...)
if !core.HashJoiner.OnExpr.Empty() && core.HashJoiner.Type == sqlbase.JoinType_INNER {
if err = result.planAndMaybeWrapOnExprAsFilter(ctx, flowCtx, core.HashJoiner.OnExpr, streamingMemAccount, processorConstructor); 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
}
joinType := core.MergeJoiner.Type
var onExpr *execinfrapb.Expression
if !core.MergeJoiner.OnExpr.Empty() {
if joinType != sqlbase.JoinType_INNER {
return result, errors.AssertionFailedf(
"ON expression (%s) was unexpectedly planned for merge joiner with join type %s",
core.MergeJoiner.OnExpr.String(), core.MergeJoiner.Type.String(),
)
}
onExpr = &core.MergeJoiner.OnExpr
}
// We are using an unlimited memory monitor here because merge joiner
// itself is responsible for making sure that we stay within the memory
// limit, and it will fall back to disk if necessary.
unlimitedAllocator := NewAllocator(
ctx, result.createBufferingUnlimitedMemAccount(
ctx, flowCtx, "merge-joiner",
))
result.Op, err = newMergeJoinOp(
unlimitedAllocator, execinfra.GetWorkMemLimit(flowCtx.Cfg),
args.DiskQueueCfg, args.FDSemaphore,
joinType, inputs[0], inputs[1], leftPhysTypes, rightPhysTypes,
core.MergeJoiner.LeftOrdering.Columns, core.MergeJoiner.RightOrdering.Columns,
)
if err != nil {
return result, err
}
result.ColumnTypes = append(leftLogTypes, rightLogTypes...)
if onExpr != nil {
if err = result.planAndMaybeWrapOnExprAsFilter(ctx, flowCtx, *onExpr, streamingMemAccount, processorConstructor); err != nil {
return result, err
}
}
// Merge joiner can run in auto mode because it falls back to disk if
// there is not enough memory available.
result.CanRunInAutoMode = true
case core.Sorter != nil:
if err := checkNumIn(inputs, 1); err != nil {
return result, err
}
input := inputs[0]
var inputTypes []coltypes.T
inputTypes, err = typeconv.FromColumnTypes(spec.Input[0].ColumnTypes)
if err != nil {
return result, err
}
ordering := core.Sorter.OutputOrdering
matchLen := core.Sorter.OrderingMatchLen
result.Op, err = result.createDiskBackedSort(
ctx, flowCtx, args, input, inputTypes, ordering, matchLen, 0, /* maxNumberPartitions */
spec.ProcessorID, post, "", /* memMonitorNamePrefix */
)
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
}
memMonitorsPrefix := "window-"
input := inputs[0]
result.ColumnTypes = spec.Input[0].ColumnTypes
// Most supported window functions can run in auto mode because they are
// streaming operators and internally they might use a sorter which can
// fall back to disk if needed.
canRunInAutoMode := true
for _, wf := range core.Windower.WindowFns {
var typs []coltypes.T
typs, err = typeconv.FromColumnTypes(result.ColumnTypes)
if err != nil {
return result, err
}
tempColOffset, partitionColIdx := uint32(0), columnOmitted
peersColIdx := columnOmitted
windowFn := *wf.Func.WindowFunc
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.
partitionColIdx = int(wf.OutputColIdx)
input, err = NewWindowSortingPartitioner(
NewAllocator(ctx, streamingMemAccount), input, typs,
core.Windower.PartitionBy, wf.Ordering.Columns, int(wf.OutputColIdx),
func(input Operator, inputTypes []coltypes.T, orderingCols []execinfrapb.Ordering_Column) (Operator, error) {
return result.createDiskBackedSort(
ctx, flowCtx, args, input, inputTypes,
execinfrapb.Ordering{Columns: orderingCols}, 0, /* matchLen */
0 /* maxNumberPartitions */, spec.ProcessorID,
&execinfrapb.PostProcessSpec{}, memMonitorsPrefix)
},
)
// Window partitioner will append a boolean column.
tempColOffset++
typs = append(typs, coltypes.Bool)
} else {
if len(wf.Ordering.Columns) > 0 {
input, err = result.createDiskBackedSort(
ctx, flowCtx, args, input, typs,
wf.Ordering, 0 /* matchLen */, 0, /* maxNumberPartitions */
spec.ProcessorID, &execinfrapb.PostProcessSpec{}, memMonitorsPrefix,
)
}
}
if err != nil {
return result, err
}
if windowFnNeedsPeersInfo(*wf.Func.WindowFunc) {
peersColIdx = int(wf.OutputColIdx + tempColOffset)
input, err = NewWindowPeerGrouper(
NewAllocator(ctx, streamingMemAccount),
input, typs, wf.Ordering.Columns,
partitionColIdx, peersColIdx,
)
// Window peer grouper will append a boolean column.
tempColOffset++
typs = append(typs, coltypes.Bool)
}
switch windowFn {
case execinfrapb.WindowerSpec_ROW_NUMBER:
result.Op = NewRowNumberOperator(
NewAllocator(ctx, streamingMemAccount), input, int(wf.OutputColIdx+tempColOffset), partitionColIdx,
)
case execinfrapb.WindowerSpec_RANK, execinfrapb.WindowerSpec_DENSE_RANK:
result.Op, err = NewRankOperator(
NewAllocator(ctx, streamingMemAccount), input, windowFn, wf.Ordering.Columns,
int(wf.OutputColIdx+tempColOffset), partitionColIdx, peersColIdx,
)
case execinfrapb.WindowerSpec_PERCENT_RANK, execinfrapb.WindowerSpec_CUME_DIST:
memAccount := streamingMemAccount
if !useStreamingMemAccountForBuffering {
// TODO(asubiotto): Once we support spilling to disk in these window
// functions, make this a limited account. Done this way so that we
// can still run plans that include these window functions with a
// low memory limit to test disk spilling of other components for
// the time being.
memAccount = result.createBufferingUnlimitedMemAccount(ctx, flowCtx, memMonitorsPrefix+"relative-rank")
}
result.Op, err = NewRelativeRankOperator(
NewAllocator(ctx, memAccount), input, typs, windowFn, wf.Ordering.Columns,
int(wf.OutputColIdx+tempColOffset), partitionColIdx, peersColIdx,
)