-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
vectorized_flow.go
1333 lines (1249 loc) · 47.8 KB
/
vectorized_flow.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 colflow
import (
"context"
"fmt"
"math"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"github.com/cockroachdb/cockroach/pkg/col/coldata"
"github.com/cockroachdb/cockroach/pkg/col/coldataext"
"github.com/cockroachdb/cockroach/pkg/rpc/nodedialer"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/sql/colcontainer"
"github.com/cockroachdb/cockroach/pkg/sql/colexec"
"github.com/cockroachdb/cockroach/pkg/sql/colexec/colbuilder"
"github.com/cockroachdb/cockroach/pkg/sql/colexecbase"
"github.com/cockroachdb/cockroach/pkg/sql/colexecbase/colexecerror"
"github.com/cockroachdb/cockroach/pkg/sql/colflow/colrpc"
"github.com/cockroachdb/cockroach/pkg/sql/colmem"
"github.com/cockroachdb/cockroach/pkg/sql/execinfra"
"github.com/cockroachdb/cockroach/pkg/sql/execinfrapb"
"github.com/cockroachdb/cockroach/pkg/sql/flowinfra"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/rowexec"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"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/metric"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/logtags"
"github.com/marusama/semaphore"
opentracing "github.com/opentracing/opentracing-go"
)
// countingSemaphore is a semaphore that keeps track of the semaphore count from
// its perspective.
type countingSemaphore struct {
semaphore.Semaphore
globalCount *metric.Gauge
count int64
}
func (s *countingSemaphore) Acquire(ctx context.Context, n int) error {
if err := s.Semaphore.Acquire(ctx, n); err != nil {
return err
}
atomic.AddInt64(&s.count, int64(n))
s.globalCount.Inc(int64(n))
return nil
}
func (s *countingSemaphore) TryAcquire(n int) bool {
success := s.Semaphore.TryAcquire(n)
if !success {
return false
}
atomic.AddInt64(&s.count, int64(n))
s.globalCount.Inc(int64(n))
return success
}
func (s *countingSemaphore) Release(n int) int {
atomic.AddInt64(&s.count, int64(-n))
s.globalCount.Dec(int64(n))
return s.Semaphore.Release(n)
}
type vectorizedFlow struct {
*flowinfra.FlowBase
// operatorConcurrency is set if any operators are executed in parallel.
operatorConcurrency bool
// countingSemaphore is a wrapper over a semaphore.Semaphore that keeps track
// of the number of resources held in a semaphore.Semaphore requested from the
// context of this flow so that these can be released unconditionally upon
// Cleanup.
countingSemaphore *countingSemaphore
// streamingMemAccounts are the memory accounts that are tracking the static
// memory usage of the whole vectorized flow as well as all dynamic memory of
// the streaming components.
streamingMemAccounts []*mon.BoundAccount
// monitors are the monitors (of both memory and disk usage) of the
// buffering components.
monitors []*mon.BytesMonitor
// accounts are the accounts that are tracking the dynamic memory and disk
// usage of the buffering components.
accounts []*mon.BoundAccount
tempStorage struct {
// path is the path to this flow's temporary storage directory.
path string
createdStateMu struct {
syncutil.Mutex
// created is a protected boolean that is true when the flow's temporary
// storage directory has been created.
created bool
}
}
testingInfo struct {
// numClosers is the number of components in the flow that implement
// Close. This is used for testing assertions.
numClosers int32
// numClosed is a pointer to an int32 that is updated atomically when a
// component's Close method is called. This is used for testing
// assertions.
numClosed *int32
}
testingKnobs struct {
// onSetupFlow is a testing knob that is called before calling
// creator.setupFlow with the given creator.
onSetupFlow func(*vectorizedFlowCreator)
}
}
var _ flowinfra.Flow = &vectorizedFlow{}
var vectorizedFlowPool = sync.Pool{
New: func() interface{} {
return &vectorizedFlow{}
},
}
// NewVectorizedFlow creates a new vectorized flow given the flow base.
func NewVectorizedFlow(base *flowinfra.FlowBase) flowinfra.Flow {
vf := vectorizedFlowPool.Get().(*vectorizedFlow)
vf.FlowBase = base
return vf
}
// VectorizeTestingBatchSize is a testing cluster setting that sets the default
// batch size used by the vectorized execution engine. A low batch size is
// useful to test batch reuse.
var VectorizeTestingBatchSize = settings.RegisterValidatedIntSetting(
"sql.testing.vectorize.batch_size",
fmt.Sprintf("the size of a batch of rows in the vectorized engine (0=default, value must be less than %d)", coldata.MaxBatchSize),
0,
func(newBatchSize int64) error {
if newBatchSize > coldata.MaxBatchSize {
return pgerror.Newf(pgcode.InvalidParameterValue, "batch size %d may not be larger than %d", newBatchSize, coldata.MaxBatchSize)
}
return nil
},
)
// Setup is part of the flowinfra.Flow interface.
func (f *vectorizedFlow) Setup(
ctx context.Context, spec *execinfrapb.FlowSpec, opt flowinfra.FuseOpt,
) (context.Context, error) {
var err error
ctx, err = f.FlowBase.Setup(ctx, spec, opt)
if err != nil {
return ctx, err
}
log.VEventf(ctx, 1, "setting up vectorize flow %s", f.ID.Short())
recordingStats := false
if sp := opentracing.SpanFromContext(ctx); sp != nil && tracing.IsRecording(sp) {
recordingStats = true
}
helper := &vectorizedFlowCreatorHelper{f: f.FlowBase}
testingBatchSize := int64(0)
if f.FlowCtx.Cfg.Settings != nil {
testingBatchSize = VectorizeTestingBatchSize.Get(&f.FlowCtx.Cfg.Settings.SV)
}
if testingBatchSize != 0 {
if err := coldata.SetBatchSizeForTests(int(testingBatchSize)); err != nil {
return ctx, err
}
} else {
coldata.ResetBatchSizeForTests()
}
// Create a name for this flow's temporary directory. Note that this directory
// is lazily created when necessary and cleaned up in Cleanup(). The directory
// name is the flow's ID in most cases apart from when the flow's ID is unset
// (in the case of local flows). In this case the directory will be prefixed
// with "local-flow" and a uuid is generated on the spot to provide a unique
// name.
tempDirName := f.GetID().String()
if f.GetID().Equal(uuid.Nil) {
tempDirName = "local-flow" + uuid.FastMakeV4().String()
}
f.tempStorage.path = filepath.Join(f.Cfg.TempStoragePath, tempDirName)
diskQueueCfg := colcontainer.DiskQueueCfg{
FS: f.Cfg.TempFS,
Path: f.tempStorage.path,
OnNewDiskQueueCb: func() {
f.tempStorage.createdStateMu.Lock()
defer f.tempStorage.createdStateMu.Unlock()
if f.tempStorage.createdStateMu.created {
// The temporary storage directory has already been created.
return
}
log.VEventf(ctx, 1, "flow %s spilled to disk, stack trace: %s", f.ID, util.GetSmallTrace(2))
if err := f.Cfg.TempFS.MkdirAll(f.tempStorage.path); err != nil {
colexecerror.InternalError(errors.Errorf("unable to create temporary storage directory: %v", err))
}
f.tempStorage.createdStateMu.created = true
},
}
if err := diskQueueCfg.EnsureDefaults(); err != nil {
return ctx, err
}
f.countingSemaphore = &countingSemaphore{Semaphore: f.Cfg.VecFDSemaphore, globalCount: f.Cfg.Metrics.VecOpenFDs}
creator := newVectorizedFlowCreator(
helper,
vectorizedRemoteComponentCreator{},
recordingStats,
f.GetWaitGroup(),
f.GetSyncFlowConsumer(),
f.GetFlowCtx().Cfg.NodeDialer,
f.GetID(),
diskQueueCfg,
f.countingSemaphore,
colexec.DefaultExprDeserialization,
)
if f.testingKnobs.onSetupFlow != nil {
f.testingKnobs.onSetupFlow(creator)
}
_, err = creator.setupFlow(ctx, f.GetFlowCtx(), spec.Processors, opt)
if err == nil {
f.testingInfo.numClosers = creator.numClosers
f.testingInfo.numClosed = &creator.numClosed
f.operatorConcurrency = creator.operatorConcurrency
f.streamingMemAccounts = append(f.streamingMemAccounts, creator.streamingMemAccounts...)
f.monitors = append(f.monitors, creator.monitors...)
f.accounts = append(f.accounts, creator.accounts...)
log.VEventf(ctx, 1, "vectorized flow setup succeeded")
return ctx, nil
}
// It is (theoretically) possible that some of the memory monitoring
// infrastructure was created even in case of an error, and we need to clean
// that up.
for _, acc := range creator.streamingMemAccounts {
acc.Close(ctx)
}
for _, acc := range creator.accounts {
acc.Close(ctx)
}
for _, mon := range creator.monitors {
mon.Stop(ctx)
}
log.VEventf(ctx, 1, "failed to vectorize: %s", err)
return ctx, err
}
// IsVectorized is part of the flowinfra.Flow interface.
func (f *vectorizedFlow) IsVectorized() bool {
return true
}
// ConcurrentTxnUse is part of the flowinfra.Flow interface. It is conservative
// in that it returns that there is concurrent txn use as soon as any operator
// concurrency is detected. This should be inconsequential for local flows that
// use the RootTxn (which are the cases in which we care about this return
// value), because only unordered synchronizers introduce operator concurrency
// at the time of writing.
func (f *vectorizedFlow) ConcurrentTxnUse() bool {
return f.operatorConcurrency || f.FlowBase.ConcurrentTxnUse()
}
// Release releases this vectorizedFlow back to the pool.
func (f *vectorizedFlow) Release() {
*f = vectorizedFlow{}
vectorizedFlowPool.Put(f)
}
// Cleanup is part of the flowinfra.Flow interface.
func (f *vectorizedFlow) Cleanup(ctx context.Context) {
// This cleans up all the memory and disk monitoring of the vectorized flow.
for _, acc := range f.streamingMemAccounts {
acc.Close(ctx)
}
for _, acc := range f.accounts {
acc.Close(ctx)
}
for _, mon := range f.monitors {
mon.Stop(ctx)
}
if f.Cfg.TestingKnobs.CheckVectorizedFlowIsClosedCorrectly {
if numClosed := atomic.LoadInt32(f.testingInfo.numClosed); numClosed != f.testingInfo.numClosers {
colexecerror.InternalError(errors.AssertionFailedf("expected %d components to be closed, but found that only %d were", f.testingInfo.numClosers, numClosed))
}
}
f.tempStorage.createdStateMu.Lock()
created := f.tempStorage.createdStateMu.created
f.tempStorage.createdStateMu.Unlock()
if created {
if err := f.Cfg.TempFS.RemoveAll(f.tempStorage.path); err != nil {
// Log error as a Warning but keep on going to close the memory
// infrastructure.
log.Warningf(
ctx,
"unable to remove flow %s's temporary directory at %s, files may be left over: %v",
f.GetID().Short(),
f.tempStorage.path,
err,
)
}
}
// Release any leftover temporary storage file descriptors from this flow.
if unreleased := atomic.LoadInt64(&f.countingSemaphore.count); unreleased > 0 {
f.countingSemaphore.Release(int(unreleased))
}
f.FlowBase.Cleanup(ctx)
f.Release()
}
// wrapWithVectorizedStatsCollector creates a new
// colexec.VectorizedStatsCollector that wraps op and connects the newly
// created wrapper with those corresponding to operators in inputs (the latter
// must have already been wrapped).
func (s *vectorizedFlowCreator) wrapWithVectorizedStatsCollector(
op colexecbase.Operator,
ioReader execinfra.IOReader,
inputs []colexecbase.Operator,
id int32,
idTagKey string,
monitors []*mon.BytesMonitor,
) (*colexec.VectorizedStatsCollector, error) {
inputWatch := timeutil.NewStopWatch()
var memMonitors, diskMonitors []*mon.BytesMonitor
for _, m := range monitors {
if m.Resource() == mon.DiskResource {
diskMonitors = append(diskMonitors, m)
} else {
memMonitors = append(memMonitors, m)
}
}
inputStatsCollectors := make([]*colexec.VectorizedStatsCollector, len(inputs))
for i, input := range inputs {
sc, ok := input.(*colexec.VectorizedStatsCollector)
if !ok {
return nil, errors.New("unexpectedly an input is not collecting stats")
}
inputStatsCollectors[i] = sc
}
vsc := colexec.NewVectorizedStatsCollector(
op, ioReader, id, idTagKey, inputWatch,
memMonitors, diskMonitors, inputStatsCollectors,
)
s.vectorizedStatsCollectorsQueue = append(s.vectorizedStatsCollectorsQueue, vsc)
return vsc, nil
}
// finishVectorizedStatsCollectors finishes the given stats collectors and
// outputs their stats to the trace contained in the ctx's span.
func finishVectorizedStatsCollectors(
ctx context.Context,
flowID execinfrapb.FlowID,
deterministicStats bool,
vectorizedStatsCollectors []*colexec.VectorizedStatsCollector,
) {
flowIDString := flowID.String()
for _, vsc := range vectorizedStatsCollectors {
vsc.OutputStats(ctx, flowIDString, deterministicStats)
}
}
type runFn func(_ context.Context, flowCtxCancel context.CancelFunc)
// flowCreatorHelper contains all the logic needed to add the vectorized
// infrastructure to be run asynchronously as well as to perform some sanity
// checks.
type flowCreatorHelper interface {
// addStreamEndpoint stores information about an inbound stream.
addStreamEndpoint(execinfrapb.StreamID, *colrpc.Inbox, *sync.WaitGroup)
// checkInboundStreamID checks that the provided stream ID has not been seen
// yet.
checkInboundStreamID(execinfrapb.StreamID) error
// accumulateAsyncComponent stores a component (either a router or an outbox)
// to be run asynchronously.
accumulateAsyncComponent(runFn)
// addMaterializer adds a materializer to the flow.
addMaterializer(*colexec.Materializer)
// getCancelFlowFn returns a flow cancellation function.
getCancelFlowFn() context.CancelFunc
}
// opDAGWithMetaSources is a helper struct that stores an operator DAG as well
// as the metadataSources and closers in this DAG that need to be drained and
// closed.
type opDAGWithMetaSources struct {
rootOperator colexecbase.Operator
metadataSources []execinfrapb.MetadataSource
toClose []colexec.Closer
}
// remoteComponentCreator is an interface that abstracts the constructors for
// several components in a remote flow. Mostly for testing purposes.
type remoteComponentCreator interface {
newOutbox(
allocator *colmem.Allocator,
input colexecbase.Operator,
typs []*types.T,
metadataSources []execinfrapb.MetadataSource,
toClose []colexec.Closer,
) (*colrpc.Outbox, error)
newInbox(ctx context.Context, allocator *colmem.Allocator, typs []*types.T, streamID execinfrapb.StreamID) (*colrpc.Inbox, error)
}
type vectorizedRemoteComponentCreator struct{}
func (vectorizedRemoteComponentCreator) newOutbox(
allocator *colmem.Allocator,
input colexecbase.Operator,
typs []*types.T,
metadataSources []execinfrapb.MetadataSource,
toClose []colexec.Closer,
) (*colrpc.Outbox, error) {
return colrpc.NewOutbox(allocator, input, typs, metadataSources, toClose)
}
func (vectorizedRemoteComponentCreator) newInbox(
ctx context.Context, allocator *colmem.Allocator, typs []*types.T, streamID execinfrapb.StreamID,
) (*colrpc.Inbox, error) {
return colrpc.NewInbox(ctx, allocator, typs, streamID)
}
// vectorizedFlowCreator performs all the setup of vectorized flows. Depending
// on embedded flowCreatorHelper, it can either do the actual setup in order
// to run the flow or do the setup needed to check that the flow is supported
// through the vectorized engine.
type vectorizedFlowCreator struct {
flowCreatorHelper
remoteComponentCreator
streamIDToInputOp map[execinfrapb.StreamID]opDAGWithMetaSources
recordingStats bool
vectorizedStatsCollectorsQueue []*colexec.VectorizedStatsCollector
waitGroup *sync.WaitGroup
syncFlowConsumer execinfra.RowReceiver
nodeDialer *nodedialer.Dialer
flowID execinfrapb.FlowID
exprHelper colexec.ExprHelper
// numOutboxes counts how many exec.Outboxes have been set up on this node.
// It must be accessed atomically.
numOutboxes int32
materializerAdded bool
// leaves accumulates all operators that have no further outputs on the
// current node, for the purposes of EXPLAIN output.
leaves []execinfra.OpNode
// operatorConcurrency is set if any operators are executed in parallel.
operatorConcurrency bool
// streamingMemAccounts contains all memory accounts of the non-buffering
// components in the vectorized flow.
streamingMemAccounts []*mon.BoundAccount
// monitors contains all monitors (for both memory and disk usage) of the
// buffering components in the vectorized flow.
monitors []*mon.BytesMonitor
// accounts contains all monitors (for both memory and disk usage) of the
// buffering components in the vectorized flow.
accounts []*mon.BoundAccount
diskQueueCfg colcontainer.DiskQueueCfg
fdSemaphore semaphore.Semaphore
// numClosers and numClosed are used to assert during testing that the
// expected number of components are closed.
numClosers int32
numClosed int32
}
func newVectorizedFlowCreator(
helper flowCreatorHelper,
componentCreator remoteComponentCreator,
recordingStats bool,
waitGroup *sync.WaitGroup,
syncFlowConsumer execinfra.RowReceiver,
nodeDialer *nodedialer.Dialer,
flowID execinfrapb.FlowID,
diskQueueCfg colcontainer.DiskQueueCfg,
fdSemaphore semaphore.Semaphore,
exprDeserialization colexec.ExprDeserialization,
) *vectorizedFlowCreator {
return &vectorizedFlowCreator{
flowCreatorHelper: helper,
remoteComponentCreator: componentCreator,
streamIDToInputOp: make(map[execinfrapb.StreamID]opDAGWithMetaSources),
recordingStats: recordingStats,
vectorizedStatsCollectorsQueue: make([]*colexec.VectorizedStatsCollector, 0, 2),
waitGroup: waitGroup,
syncFlowConsumer: syncFlowConsumer,
nodeDialer: nodeDialer,
flowID: flowID,
diskQueueCfg: diskQueueCfg,
fdSemaphore: fdSemaphore,
exprHelper: colexec.NewExprHelper(exprDeserialization),
}
}
// 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.
// TODO(asubiotto): This identical to the helper function in
// NewColOperatorResult, meaning that we should probably find a way to refactor
// this.
func (s *vectorizedFlowCreator) createBufferingUnlimitedMemMonitor(
ctx context.Context, flowCtx *execinfra.FlowCtx, name string,
) *mon.BytesMonitor {
bufferingOpUnlimitedMemMonitor := execinfra.NewMonitor(
ctx, flowCtx.EvalCtx.Mon, name+"-unlimited",
)
s.monitors = append(s.monitors, bufferingOpUnlimitedMemMonitor)
return bufferingOpUnlimitedMemMonitor
}
// createDiskAccounts instantiates an unlimited disk monitor and disk accounts
// to be used for disk spilling infrastructure in vectorized engine.
// TODO(azhng): consolidate all allocation monitors/account management into one
// place after branch cut for 20.1.
func (s *vectorizedFlowCreator) createDiskAccounts(
ctx context.Context, flowCtx *execinfra.FlowCtx, name string, numAccounts int,
) (*mon.BytesMonitor, []*mon.BoundAccount) {
diskMonitor := execinfra.NewMonitor(ctx, flowCtx.Cfg.DiskMonitor, name)
s.monitors = append(s.monitors, diskMonitor)
diskAccounts := make([]*mon.BoundAccount, numAccounts)
for i := range diskAccounts {
diskAcc := diskMonitor.MakeBoundAccount()
diskAccounts[i] = &diskAcc
}
s.accounts = append(s.accounts, diskAccounts...)
return diskMonitor, diskAccounts
}
// newStreamingMemAccount creates a new memory account bound to the monitor in
// flowCtx and accumulates it into streamingMemAccounts slice.
func (s *vectorizedFlowCreator) newStreamingMemAccount(
flowCtx *execinfra.FlowCtx,
) *mon.BoundAccount {
streamingMemAccount := flowCtx.EvalCtx.Mon.MakeBoundAccount()
s.streamingMemAccounts = append(s.streamingMemAccounts, &streamingMemAccount)
return &streamingMemAccount
}
// setupRemoteOutputStream sets up an Outbox that will operate according to
// the given StreamEndpointSpec. It will also drain all MetadataSources in the
// metadataSourcesQueue.
func (s *vectorizedFlowCreator) setupRemoteOutputStream(
ctx context.Context,
flowCtx *execinfra.FlowCtx,
op colexecbase.Operator,
outputTyps []*types.T,
stream *execinfrapb.StreamEndpointSpec,
metadataSourcesQueue []execinfrapb.MetadataSource,
toClose []colexec.Closer,
factory coldata.ColumnFactory,
) (execinfra.OpNode, error) {
// TODO(yuzefovich): we should collect some statistics on the outbox (e.g.
// number of bytes sent).
outbox, err := s.remoteComponentCreator.newOutbox(
colmem.NewAllocator(ctx, s.newStreamingMemAccount(flowCtx), factory),
op, outputTyps, metadataSourcesQueue, toClose,
)
if err != nil {
return nil, err
}
atomic.AddInt32(&s.numOutboxes, 1)
run := func(ctx context.Context, flowCtxCancel context.CancelFunc) {
outbox.Run(
ctx,
s.nodeDialer,
stream.TargetNodeID,
s.flowID,
stream.StreamID,
flowCtxCancel,
flowinfra.SettingFlowStreamTimeout.Get(&flowCtx.Cfg.Settings.SV),
)
currentOutboxes := atomic.AddInt32(&s.numOutboxes, -1)
// When the last Outbox on this node exits, we want to make sure that
// everything is shutdown; namely, we need to call flowCtxCancel if:
// - it is the last Outbox
// - there is no root materializer on this node (if it were, it would take
// care of the cancellation itself)
// - flowCtxCancel is non-nil (it can be nil in tests).
// Calling flowCtxCancel will cancel the context that all infrastructure
// on this node is listening on, so it will shut everything down.
if currentOutboxes == 0 && !s.materializerAdded && flowCtxCancel != nil {
flowCtxCancel()
}
}
s.accumulateAsyncComponent(run)
return outbox, nil
}
// setupRouter sets up a vectorized hash router according to the output router
// spec. If the outputs are local, these are added to s.streamIDToInputOp to be
// used as inputs in further planning. metadataSourcesQueue is passed along to
// any outboxes created to be drained, or stored in streamIDToInputOp for any
// local outputs to pass that responsibility along. In any case,
// metadataSourcesQueue will always be fully consumed.
// NOTE: This method supports only BY_HASH routers. Callers should handle
// PASS_THROUGH routers separately.
func (s *vectorizedFlowCreator) setupRouter(
ctx context.Context,
flowCtx *execinfra.FlowCtx,
input colexecbase.Operator,
outputTyps []*types.T,
output *execinfrapb.OutputRouterSpec,
metadataSourcesQueue []execinfrapb.MetadataSource,
toClose []colexec.Closer,
factory coldata.ColumnFactory,
) error {
if output.Type != execinfrapb.OutputRouterSpec_BY_HASH {
return errors.Errorf("vectorized output router type %s unsupported", output.Type)
}
// HashRouter memory monitor names are the concatenated output stream IDs.
streamIDs := make([]string, len(output.Streams))
for i, s := range output.Streams {
streamIDs[i] = strconv.Itoa(int(s.StreamID))
}
mmName := "hash-router-[" + strings.Join(streamIDs, ",") + "]"
hashRouterMemMonitor := s.createBufferingUnlimitedMemMonitor(ctx, flowCtx, mmName)
allocators := make([]*colmem.Allocator, len(output.Streams))
for i := range allocators {
acc := hashRouterMemMonitor.MakeBoundAccount()
allocators[i] = colmem.NewAllocator(ctx, &acc, factory)
s.accounts = append(s.accounts, &acc)
}
limit := execinfra.GetWorkMemLimit(flowCtx.Cfg)
if flowCtx.Cfg.TestingKnobs.ForceDiskSpill {
limit = 1
}
diskMon, diskAccounts := s.createDiskAccounts(ctx, flowCtx, mmName, len(output.Streams))
router, outputs := colexec.NewHashRouter(allocators, input, outputTyps, output.HashColumns, limit, s.diskQueueCfg, s.fdSemaphore, diskAccounts, metadataSourcesQueue, toClose)
runRouter := func(ctx context.Context, _ context.CancelFunc) {
router.Run(logtags.AddTag(ctx, "hashRouterID", strings.Join(streamIDs, ",")))
}
s.accumulateAsyncComponent(runRouter)
foundLocalOutput := false
for i, op := range outputs {
stream := &output.Streams[i]
switch stream.Type {
case execinfrapb.StreamEndpointSpec_SYNC_RESPONSE:
return errors.Errorf("unexpected sync response output when setting up router")
case execinfrapb.StreamEndpointSpec_REMOTE:
// Note that here we pass in nil 'toClose' slice because hash
// router is responsible for closing all of the idempotent closers.
if _, err := s.setupRemoteOutputStream(
ctx, flowCtx, op, outputTyps, stream, []execinfrapb.MetadataSource{op}, nil /* toClose */, factory,
); err != nil {
return err
}
case execinfrapb.StreamEndpointSpec_LOCAL:
foundLocalOutput = true
localOp := colexecbase.Operator(op)
if s.recordingStats {
mons := []*mon.BytesMonitor{hashRouterMemMonitor, diskMon}
// Wrap local outputs with vectorized stats collectors when recording
// stats. This is mostly for compatibility but will provide some useful
// information (e.g. output stall time).
var err error
localOp, err = s.wrapWithVectorizedStatsCollector(
op, nil /* ioReadingOp */, nil, /* inputs */
int32(stream.StreamID), execinfrapb.StreamIDTagKey, mons,
)
if err != nil {
return err
}
}
s.streamIDToInputOp[stream.StreamID] = opDAGWithMetaSources{
rootOperator: localOp,
metadataSources: []execinfrapb.MetadataSource{op},
// toClose will be closed by the HashRouter.
toClose: nil,
}
}
}
if !foundLocalOutput {
// No local output means that our router is a leaf node.
s.leaves = append(s.leaves, router)
}
return nil
}
// setupInput sets up one or more input operators (local or remote) and a
// synchronizer to expose these separate streams as one exec.Operator which is
// returned. If s.recordingStats is true, these inputs and synchronizer are
// wrapped in stats collectors if not done so, although these stats are not
// exposed as of yet. Inboxes that are created are also returned as
// []distqlpb.MetadataSource so that any remote metadata can be read through
// calling DrainMeta.
func (s *vectorizedFlowCreator) setupInput(
ctx context.Context,
flowCtx *execinfra.FlowCtx,
input execinfrapb.InputSyncSpec,
opt flowinfra.FuseOpt,
factory coldata.ColumnFactory,
) (colexecbase.Operator, []execinfrapb.MetadataSource, []colexec.Closer, error) {
inputStreamOps := make([]colexec.SynchronizerInput, 0, len(input.Streams))
// Before we can safely use types we received over the wire in the
// operators, we need to make sure they are hydrated. In row execution
// engine it is done during the processor initialization, but operators
// don't do that. However, all operators (apart from the colBatchScan) get
// their types from InputSyncSpec, so this is a convenient place to do the
// hydration so that all operators get the valid types.
resolver := flowCtx.TypeResolverFactory.NewTypeResolver(flowCtx.EvalCtx.Txn)
if err := resolver.HydrateTypeSlice(ctx, input.ColumnTypes); err != nil {
return nil, nil, nil, err
}
for _, inputStream := range input.Streams {
switch inputStream.Type {
case execinfrapb.StreamEndpointSpec_LOCAL:
in := s.streamIDToInputOp[inputStream.StreamID]
inputStreamOps = append(inputStreamOps, colexec.SynchronizerInput{
Op: in.rootOperator,
MetadataSources: in.metadataSources,
ToClose: in.toClose,
})
case execinfrapb.StreamEndpointSpec_REMOTE:
// If the input is remote, the input operator does not exist in
// streamIDToInputOp. Create an inbox.
if err := s.checkInboundStreamID(inputStream.StreamID); err != nil {
return nil, nil, nil, err
}
inbox, err := s.remoteComponentCreator.newInbox(
ctx, colmem.NewAllocator(ctx, s.newStreamingMemAccount(flowCtx), factory), input.ColumnTypes, inputStream.StreamID,
)
if err != nil {
return nil, nil, nil, err
}
s.addStreamEndpoint(inputStream.StreamID, inbox, s.waitGroup)
op := colexecbase.Operator(inbox)
if s.recordingStats {
op, err = s.wrapWithVectorizedStatsCollector(
inbox, nil /* ioReadingOp */, nil /* inputs */, int32(inputStream.StreamID),
execinfrapb.StreamIDTagKey, nil, /* monitors */
)
if err != nil {
return nil, nil, nil, err
}
}
inputStreamOps = append(inputStreamOps, colexec.SynchronizerInput{Op: op, MetadataSources: []execinfrapb.MetadataSource{inbox}})
default:
return nil, nil, nil, errors.Errorf("unsupported input stream type %s", inputStream.Type)
}
}
op := inputStreamOps[0].Op
metaSources := inputStreamOps[0].MetadataSources
toClose := inputStreamOps[0].ToClose
if len(inputStreamOps) > 1 {
statsInputs := inputStreamOps
if input.Type == execinfrapb.InputSyncSpec_ORDERED {
os, err := colexec.NewOrderedSynchronizer(
colmem.NewAllocator(ctx, s.newStreamingMemAccount(flowCtx), factory),
execinfra.GetWorkMemLimit(flowCtx.Cfg), inputStreamOps,
input.ColumnTypes, execinfrapb.ConvertToColumnOrdering(input.Ordering),
)
if err != nil {
return nil, nil, nil, err
}
op = os
metaSources = []execinfrapb.MetadataSource{os}
toClose = []colexec.Closer{os}
} else {
if opt == flowinfra.FuseAggressively {
sync := colexec.NewSerialUnorderedSynchronizer(inputStreamOps)
op = sync
metaSources = []execinfrapb.MetadataSource{sync}
toClose = []colexec.Closer{sync}
} else {
sync := colexec.NewParallelUnorderedSynchronizer(inputStreamOps, s.waitGroup)
op = sync
metaSources = []execinfrapb.MetadataSource{sync}
// toClose is set to nil because the ParallelUnorderedSynchronizer takes
// care of closing these components itself since they need to be closed
// from the same goroutine as Next.
toClose = nil
s.operatorConcurrency = true
}
// Don't use the unordered synchronizer's inputs for stats collection
// given that they run concurrently. The stall time will be collected
// instead.
statsInputs = nil
}
if s.recordingStats {
statsInputsAsOps := make([]colexecbase.Operator, len(statsInputs))
for i := range statsInputs {
statsInputsAsOps[i] = statsInputs[i].Op
}
// TODO(asubiotto): Once we have IDs for synchronizers, plumb them into
// this stats collector to display stats.
var err error
op, err = s.wrapWithVectorizedStatsCollector(
op, nil /* ioReadingOp */, statsInputsAsOps, -1, /* id */
"" /* idTagKey */, nil, /* monitors */
)
if err != nil {
return nil, nil, nil, err
}
}
}
return op, metaSources, toClose, nil
}
// setupOutput sets up any necessary infrastructure according to the output
// spec of pspec. The metadataSourcesQueue and toClose slices are fully consumed
// by either passing them to an outbox or HashRouter to be drained/closed, or
// storing them in streamIDToInputOp with the given op to be processed later.
// NOTE: The caller must not reuse the metadataSourcesQueue.
func (s *vectorizedFlowCreator) setupOutput(
ctx context.Context,
flowCtx *execinfra.FlowCtx,
pspec *execinfrapb.ProcessorSpec,
op colexecbase.Operator,
opOutputTypes []*types.T,
metadataSourcesQueue []execinfrapb.MetadataSource,
toClose []colexec.Closer,
factory coldata.ColumnFactory,
) error {
output := &pspec.Output[0]
if output.Type != execinfrapb.OutputRouterSpec_PASS_THROUGH {
return s.setupRouter(
ctx,
flowCtx,
op,
opOutputTypes,
output,
// Pass in a copy of the queue to reset metadataSourcesQueue for
// further appends without overwriting.
metadataSourcesQueue,
toClose,
factory,
)
}
if len(output.Streams) != 1 {
return errors.Errorf("unsupported multi outputstream proc (%d streams)", len(output.Streams))
}
outputStream := &output.Streams[0]
switch outputStream.Type {
case execinfrapb.StreamEndpointSpec_LOCAL:
s.streamIDToInputOp[outputStream.StreamID] = opDAGWithMetaSources{
rootOperator: op, metadataSources: metadataSourcesQueue, toClose: toClose,
}
case execinfrapb.StreamEndpointSpec_REMOTE:
// Set up an Outbox. Note that we pass in a copy of metadataSourcesQueue
// so that we can reset it below and keep on writing to it.
if s.recordingStats {
// If recording stats, we add a metadata source that will generate all
// stats data as metadata for the stats collectors created so far.
vscs := append([]*colexec.VectorizedStatsCollector(nil), s.vectorizedStatsCollectorsQueue...)
s.vectorizedStatsCollectorsQueue = s.vectorizedStatsCollectorsQueue[:0]
metadataSourcesQueue = append(
metadataSourcesQueue,
execinfrapb.CallbackMetadataSource{
DrainMetaCb: func(ctx context.Context) []execinfrapb.ProducerMetadata {
// Start a separate recording so that GetRecording will return
// the recordings for only the child spans containing stats.
ctx, span := tracing.ChildSpanSeparateRecording(ctx, "")
finishVectorizedStatsCollectors(
ctx, flowCtx.ID, flowCtx.Cfg.TestingKnobs.DeterministicStats, vscs,
)
return []execinfrapb.ProducerMetadata{{TraceData: tracing.GetRecording(span)}}
},
},
)
}
outbox, err := s.setupRemoteOutputStream(
ctx, flowCtx, op, opOutputTypes, outputStream, metadataSourcesQueue, toClose, factory,
)
if err != nil {
return err
}
// An outbox is a leaf: there's nothing that sees it as an input on this
// node.
s.leaves = append(s.leaves, outbox)
case execinfrapb.StreamEndpointSpec_SYNC_RESPONSE:
if s.syncFlowConsumer == nil {
return errors.New("syncFlowConsumer unset, unable to create materializer")
}
// Make the materializer, which will write to the given receiver.
columnTypes := s.syncFlowConsumer.Types()
if err := assertTypesMatch(columnTypes, opOutputTypes); err != nil {
return err
}
var outputStatsToTrace func()
if s.recordingStats {
// Make a copy given that vectorizedStatsCollectorsQueue is reset and
// appended to.
vscq := append([]*colexec.VectorizedStatsCollector(nil), s.vectorizedStatsCollectorsQueue...)
outputStatsToTrace = func() {
finishVectorizedStatsCollectors(
ctx, flowCtx.ID, flowCtx.Cfg.TestingKnobs.DeterministicStats, vscq,
)
}
}
proc, err := colexec.NewMaterializer(
flowCtx,
pspec.ProcessorID,
op,
columnTypes,
s.syncFlowConsumer,
metadataSourcesQueue,
toClose,
outputStatsToTrace,
s.getCancelFlowFn,
)
if err != nil {
return err
}
s.vectorizedStatsCollectorsQueue = s.vectorizedStatsCollectorsQueue[:0]
// A materializer is a leaf.
s.leaves = append(s.leaves, proc)
s.addMaterializer(proc)
s.materializerAdded = true
default:
return errors.Errorf("unsupported output stream type %s", outputStream.Type)
}
return nil
}
func (s *vectorizedFlowCreator) setupFlow(
ctx context.Context,
flowCtx *execinfra.FlowCtx,
processorSpecs []execinfrapb.ProcessorSpec,
opt flowinfra.FuseOpt,
) (leaves []execinfra.OpNode, err error) {
if vecErr := colexecerror.CatchVectorizedRuntimeError(func() {
streamIDToSpecIdx := make(map[execinfrapb.StreamID]int)
factory := coldataext.NewExtendedColumnFactory(flowCtx.NewEvalCtx())
// queue is a queue of indices into processorSpecs, for topologically
// ordered processing.
queue := make([]int, 0, len(processorSpecs))
for i := range processorSpecs {
hasLocalInput := false
for j := range processorSpecs[i].Input {
input := &processorSpecs[i].Input[j]
for k := range input.Streams {
stream := &input.Streams[k]
streamIDToSpecIdx[stream.StreamID] = i
if stream.Type != execinfrapb.StreamEndpointSpec_REMOTE {
hasLocalInput = true
}
}
}
if hasLocalInput {
continue
}
// Queue all processors with either no inputs or remote inputs.
queue = append(queue, i)
}
inputs := make([]colexecbase.Operator, 0, 2)
for len(queue) > 0 {
pspec := &processorSpecs[queue[0]]
queue = queue[1:]
if len(pspec.Output) > 1 {
err = errors.Errorf("unsupported multi-output proc (%d outputs)", len(pspec.Output))
return
}
// metadataSourcesQueue contains all the MetadataSources that need to be
// drained. If in a given loop iteration no component that can drain
// metadata from these sources is found, the metadataSourcesQueue should be
// added as part of one of the last unconnected inputDAGs in
// streamIDToInputOp. This is to avoid cycles.
metadataSourcesQueue := make([]execinfrapb.MetadataSource, 0, 1)
// toClose is similar to metadataSourcesQueue with the difference that these
// components do not produce metadata and should be Closed even during
// non-graceful termination.
toClose := make([]colexec.Closer, 0, 1)
inputs = inputs[:0]
for i := range pspec.Input {
input, metadataSources, closers, localErr := s.setupInput(ctx, flowCtx, pspec.Input[i], opt, factory)
if localErr != nil {