From fef1a6548b0e8b3a4fd29a95f63951d608a68be6 Mon Sep 17 00:00:00 2001 From: yuzefovich Date: Sat, 28 Jul 2018 19:20:02 -0400 Subject: [PATCH] distsql: add memory accounting and stats to windowers Adds memory accounting and stats collection to windowers. Related to: #24425. Release note: None --- pkg/sql/distsqlrun/api.pb.go | 1 + pkg/sql/distsqlrun/stats.pb.go | 228 +++++++++++++++--- pkg/sql/distsqlrun/stats.proto | 6 + pkg/sql/distsqlrun/windower.go | 134 +++++++++- .../testdata/planner_test/distsql_auto_mode | 6 + 5 files changed, 332 insertions(+), 43 deletions(-) diff --git a/pkg/sql/distsqlrun/api.pb.go b/pkg/sql/distsqlrun/api.pb.go index 8e16b018c87a..fc8e27fc07cb 100644 --- a/pkg/sql/distsqlrun/api.pb.go +++ b/pkg/sql/distsqlrun/api.pb.go @@ -70,6 +70,7 @@ JoinReaderStats OutboxStats RouterOutputStats + WindowerStats */ package distsqlrun diff --git a/pkg/sql/distsqlrun/stats.pb.go b/pkg/sql/distsqlrun/stats.pb.go index 202c98b28db8..82c1e99f734d 100644 --- a/pkg/sql/distsqlrun/stats.pb.go +++ b/pkg/sql/distsqlrun/stats.pb.go @@ -136,6 +136,17 @@ func (m *RouterOutputStats) String() string { return proto.CompactTex func (*RouterOutputStats) ProtoMessage() {} func (*RouterOutputStats) Descriptor() ([]byte, []int) { return fileDescriptorStats, []int{9} } +// WindowerStats are the stats collected during a windower run. +type WindowerStats struct { + InputStats InputStats `protobuf:"bytes,1,opt,name=input_stats,json=inputStats" json:"input_stats"` + MaxAllocatedMem int64 `protobuf:"varint,2,opt,name=max_allocated_mem,json=maxAllocatedMem,proto3" json:"max_allocated_mem,omitempty"` +} + +func (m *WindowerStats) Reset() { *m = WindowerStats{} } +func (m *WindowerStats) String() string { return proto.CompactTextString(m) } +func (*WindowerStats) ProtoMessage() {} +func (*WindowerStats) Descriptor() ([]byte, []int) { return fileDescriptorStats, []int{10} } + func init() { proto.RegisterType((*InputStats)(nil), "cockroach.sql.distsqlrun.InputStats") proto.RegisterType((*TableReaderStats)(nil), "cockroach.sql.distsqlrun.TableReaderStats") @@ -147,6 +158,7 @@ func init() { proto.RegisterType((*JoinReaderStats)(nil), "cockroach.sql.distsqlrun.JoinReaderStats") proto.RegisterType((*OutboxStats)(nil), "cockroach.sql.distsqlrun.OutboxStats") proto.RegisterType((*RouterOutputStats)(nil), "cockroach.sql.distsqlrun.RouterOutputStats") + proto.RegisterType((*WindowerStats)(nil), "cockroach.sql.distsqlrun.WindowerStats") } func (m *InputStats) Marshal() (dAtA []byte, err error) { size := m.Size() @@ -492,6 +504,37 @@ func (m *RouterOutputStats) MarshalTo(dAtA []byte) (int, error) { return i, nil } +func (m *WindowerStats) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalTo(dAtA) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *WindowerStats) MarshalTo(dAtA []byte) (int, error) { + var i int + _ = i + var l int + _ = l + dAtA[i] = 0xa + i++ + i = encodeVarintStats(dAtA, i, uint64(m.InputStats.Size())) + n13, err := m.InputStats.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n13 + if m.MaxAllocatedMem != 0 { + dAtA[i] = 0x10 + i++ + i = encodeVarintStats(dAtA, i, uint64(m.MaxAllocatedMem)) + } + return i, nil +} + func encodeVarintStats(dAtA []byte, offset int, v uint64) int { for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) @@ -627,6 +670,17 @@ func (m *RouterOutputStats) Size() (n int) { return n } +func (m *WindowerStats) Size() (n int) { + var l int + _ = l + l = m.InputStats.Size() + n += 1 + l + sovStats(uint64(l)) + if m.MaxAllocatedMem != 0 { + n += 1 + sovStats(uint64(m.MaxAllocatedMem)) + } + return n +} + func sovStats(x uint64) (n int) { for { n++ @@ -1760,6 +1814,105 @@ func (m *RouterOutputStats) Unmarshal(dAtA []byte) error { } return nil } +func (m *WindowerStats) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowStats + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: WindowerStats: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WindowerStats: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field InputStats", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowStats + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthStats + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.InputStats.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MaxAllocatedMem", wireType) + } + m.MaxAllocatedMem = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowStats + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MaxAllocatedMem |= (int64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipStats(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthStats + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func skipStats(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 @@ -1868,41 +2021,42 @@ var ( func init() { proto.RegisterFile("sql/distsqlrun/stats.proto", fileDescriptorStats) } var fileDescriptorStats = []byte{ - // 572 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xd4, 0x95, 0x4f, 0x8f, 0xd2, 0x4e, - 0x18, 0xc7, 0x19, 0xd8, 0xdf, 0x4f, 0x78, 0x1a, 0x05, 0x1a, 0x13, 0xbb, 0x24, 0x16, 0xd2, 0xec, - 0x81, 0x98, 0x4d, 0x49, 0xd6, 0x57, 0xb0, 0x84, 0x83, 0xab, 0x6e, 0x36, 0x29, 0xc4, 0x18, 0x2f, - 0xcd, 0x40, 0x67, 0xcb, 0x84, 0x69, 0x07, 0x66, 0xa6, 0x59, 0xf6, 0x1d, 0x18, 0x4f, 0x1e, 0x4d, - 0x7c, 0x1b, 0x9e, 0x7c, 0x05, 0x1c, 0x3d, 0x7a, 0xf2, 0x0f, 0x5e, 0x7d, 0x11, 0xa6, 0x53, 0x10, - 0xd6, 0x40, 0xb2, 0x6a, 0xc8, 0xc6, 0x5b, 0xfb, 0xf4, 0xdb, 0xcf, 0xf7, 0x79, 0xe6, 0x79, 0x66, - 0x06, 0x6a, 0x72, 0xc2, 0x5a, 0x01, 0x95, 0x4a, 0x4e, 0x98, 0x48, 0xe2, 0x96, 0x54, 0x58, 0x49, - 0x77, 0x2c, 0xb8, 0xe2, 0xa6, 0x35, 0xe0, 0x83, 0x91, 0xe0, 0x78, 0x30, 0x74, 0xe5, 0x84, 0xb9, - 0x2b, 0x55, 0xed, 0x6e, 0xc8, 0x43, 0xae, 0x45, 0xad, 0xf4, 0x29, 0xd3, 0xd7, 0xec, 0x90, 0xf3, - 0x90, 0x91, 0x96, 0x7e, 0xeb, 0x27, 0xe7, 0xad, 0x20, 0x11, 0x58, 0x51, 0x1e, 0x67, 0xdf, 0x9d, - 0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b6, 0xb6, 0x0f, - 0x66, 0x5f, 0xed, 0xdc, 0x6c, 0x6e, 0xa3, 0x0f, 0x73, 0x1b, 0x7d, 0x9c, 0xdb, 0xe8, 0xcb, 0xdc, - 0x46, 0xaf, 0xbf, 0xd9, 0xb9, 0x17, 0xb0, 0x5a, 0x82, 0xfe, 0xff, 0xfa, 0x02, 0x7a, 0xf8, 0x23, - 0x00, 0x00, 0xff, 0xff, 0xca, 0xc7, 0x62, 0xb6, 0x3a, 0x07, 0x00, 0x00, + // 581 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xd4, 0x95, 0xcf, 0x6e, 0xd3, 0x40, + 0x10, 0xc6, 0xbb, 0x49, 0x81, 0x76, 0x2c, 0x48, 0x62, 0x21, 0xe1, 0x46, 0xc2, 0x89, 0xac, 0x1e, + 0x22, 0x54, 0x39, 0x52, 0x79, 0x82, 0x46, 0x39, 0x50, 0xa0, 0xaa, 0xe4, 0x44, 0x80, 0xb8, 0x58, + 0x9b, 0x78, 0xeb, 0xac, 0x62, 0xef, 0x26, 0xbb, 0x6b, 0x25, 0x7d, 0x03, 0xc4, 0x89, 0x23, 0x12, + 0xaf, 0xc1, 0x89, 0x27, 0xc8, 0x91, 0x23, 0x27, 0xfe, 0x84, 0x2b, 0x0f, 0x81, 0xbc, 0x4e, 0x48, + 0x8a, 0x12, 0xa9, 0x80, 0xa2, 0x88, 0x9b, 0x3d, 0xfe, 0xfc, 0xfb, 0x66, 0x3c, 0xe3, 0x59, 0x28, + 0xcb, 0x61, 0x54, 0x0f, 0xa8, 0x54, 0x72, 0x18, 0x89, 0x84, 0xd5, 0xa5, 0xc2, 0x4a, 0xba, 0x03, + 0xc1, 0x15, 0x37, 0xad, 0x2e, 0xef, 0xf6, 0x05, 0xc7, 0xdd, 0x9e, 0x2b, 0x87, 0x91, 0xbb, 0x50, + 0x95, 0xef, 0x86, 0x3c, 0xe4, 0x5a,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x92, 0x30, 0x35, 0xdb, 0xf4, 0xfb, 0x3a, 0xd2, 0x22, 0x4c, 0xa5, 0x3f, 0x5f, + 0xc9, 0xe3, 0x89, 0x22, 0xe2, 0x3c, 0x51, 0xd7, 0x39, 0x1c, 0x36, 0xd7, 0xd6, 0x74, 0x0f, 0x3c, + 0xa7, 0x2c, 0xe0, 0xa3, 0x6d, 0xcf, 0x63, 0xe3, 0x70, 0xf2, 0xcd, 0xde, 0x99, 0x4c, 0x6d, 0xf4, + 0x71, 0x6a, 0xa3, 0x4f, 0x53, 0x1b, 0x7d, 0x9d, 0xda, 0xe8, 0xcd, 0x77, 0x7b, 0xe7, 0x25, 0x2c, + 0xec, 0x3a, 0x37, 0xf5, 0x59, 0xf8, 0xf0, 0x67, 0x00, 0x00, 0x00, 0xff, 0xff, 0xcf, 0xc7, 0xa7, + 0xbf, 0xc5, 0x07, 0x00, 0x00, } diff --git a/pkg/sql/distsqlrun/stats.proto b/pkg/sql/distsqlrun/stats.proto index 99a7edd7b67d..45a98f4ce85a 100644 --- a/pkg/sql/distsqlrun/stats.proto +++ b/pkg/sql/distsqlrun/stats.proto @@ -86,3 +86,9 @@ message RouterOutputStats { int64 max_allocated_mem = 2; int64 max_allocated_disk = 3; } + +// WindowerStats are the stats collected during a windower run. +message WindowerStats { + InputStats input_stats = 1 [(gogoproto.nullable) = false]; + int64 max_allocated_mem = 2; +} diff --git a/pkg/sql/distsqlrun/windower.go b/pkg/sql/distsqlrun/windower.go index f318f84d7f3b..81c9ef9173ed 100644 --- a/pkg/sql/distsqlrun/windower.go +++ b/pkg/sql/distsqlrun/windower.go @@ -19,12 +19,17 @@ import ( "fmt" "sort" "strings" + "unsafe" "github.com/cockroachdb/cockroach/pkg/sql/sem/builtins" "github.com/cockroachdb/cockroach/pkg/sql/sem/tree" "github.com/cockroachdb/cockroach/pkg/sql/sem/types" "github.com/cockroachdb/cockroach/pkg/sql/sqlbase" + "github.com/cockroachdb/cockroach/pkg/util/humanizeutil" "github.com/cockroachdb/cockroach/pkg/util/log" + "github.com/cockroachdb/cockroach/pkg/util/mon" + "github.com/cockroachdb/cockroach/pkg/util/tracing" + "github.com/opentracing/opentracing-go" "github.com/pkg/errors" ) @@ -123,8 +128,15 @@ type windower struct { datumAlloc sqlbase.DatumAlloc rowAlloc sqlbase.EncDatumRowAlloc - scratch []byte + // We choose to not track certain slices (like outputTypes, windowFns and + // a couple of slices within computeWindowFunctions) since they are likely + // to have very low (although varible) memory usage. + accumulationAcc mon.BoundAccount + decodingAcc mon.BoundAccount + resultsAcc mon.BoundAccount + partitionsAcc mon.BoundAccount + scratch []byte cancelChecker *sqlbase.CancelChecker partitionBy []uint32 @@ -157,6 +169,16 @@ func newWindower( input: input, } w.inputTypes = input.OutputTypes() + ctx := flowCtx.EvalCtx.Ctx() + memMonitor := newMonitor(ctx, flowCtx.EvalCtx.Mon, "windower-mem") + w.accumulationAcc = memMonitor.MakeBoundAccount() + w.decodingAcc = memMonitor.MakeBoundAccount() + w.resultsAcc = memMonitor.MakeBoundAccount() + w.partitionsAcc = memMonitor.MakeBoundAccount() + if sp := opentracing.SpanFromContext(ctx); sp != nil && tracing.IsRecording(sp) { + w.input = NewInputStatCollector(w.input) + w.finishTrace = w.outputStatsToTrace + } windowFns := spec.WindowFns w.encodedPartitions = make(map[string][]sqlbase.EncDatumRow) @@ -208,8 +230,12 @@ func newWindower( flowCtx, processorID, output, - nil, /* memMonitor */ - procStateOpts{inputsToDrain: []RowSource{w.input}}, + memMonitor, + procStateOpts{inputsToDrain: []RowSource{w.input}, + trailingMetaCallback: func() []ProducerMetadata { + w.close() + return nil + }}, ); err != nil { return nil, err } @@ -256,7 +282,17 @@ func (w *windower) ConsumerDone() { // ConsumerClosed is part of the RowSource interface. func (w *windower) ConsumerClosed() { // The consumer is done, Next() will not be called again. + w.close() +} + +func (w *windower) close() { + // Need to close the mem accounting while the context is still valid. + w.accumulationAcc.Close(w.ctx) + w.decodingAcc.Close(w.ctx) + w.resultsAcc.Close(w.ctx) + w.partitionsAcc.Close(w.ctx) w.internalClose() + w.memMonitor.Stop(w.ctx) } // accumulateRows continually reads rows from the input and accumulates them @@ -280,6 +316,10 @@ func (w *windower) accumulateRows() (windowerState, sqlbase.EncDatumRow, *Produc break } + if err := w.accumulationAcc.Grow(w.ctx, int64(row.Size())); err != nil { + w.moveToDraining(err) + return windowerStateUnknown, nil, nil + } if len(w.partitionBy) == 0 { w.encodedPartitions[""] = append(w.encodedPartitions[""], w.rowAlloc.CopyRow(row)) } else { @@ -313,6 +353,9 @@ func (w *windower) decodePartitions() error { if err := encRow[i].EnsureDecoded(&w.inputTypes[i], &w.datumAlloc); err != nil { return err } + if err := w.decodingAcc.Grow(w.ctx, int64(encRow[i].Datum.Size())); err != nil { + return err + } } } } @@ -366,7 +409,16 @@ func (w *windower) emitRow() (windowerState, sqlbase.EncDatumRow, *ProducerMetad // are also simply appended to corresponding rows in outputRows. func (w *windower) computeWindowFunctions(ctx context.Context, evalCtx *tree.EvalContext) error { var peerGrouper peerGroupChecker + usage := sliceOfRowsSliceOverhead + sizeOfSliceOfRows*int64(len(w.windowFns)) + if err := w.resultsAcc.Grow(w.ctx, usage); err != nil { + return err + } w.windowValues = make([][][]tree.Datum, len(w.windowFns)) + + usage = indexedRowsStructSliceOverhead + sizeOfIndexedRowsStruct*int64(len(w.encodedPartitions)) + if err := w.partitionsAcc.Grow(w.ctx, usage); err != nil { + return err + } partitions := make([]indexedRows, len(w.encodedPartitions)) w.buckets = make([]string, 0, len(w.encodedPartitions)) @@ -377,6 +429,10 @@ func (w *windower) computeWindowFunctions(ctx context.Context, evalCtx *tree.Eva // to be consistent. w.buckets = append(w.buckets, bucket) w.bucketToPartitionIdx = append(w.bucketToPartitionIdx, partitionIdx) + usage = indexedRowStructSliceOverhead + sizeOfIndexedRowStruct*int64(len(encodedPartition)) + if err := w.partitionsAcc.Grow(w.ctx, usage); err != nil { + return err + } rows := make([]indexedRow, 0, len(encodedPartition)) for idx := 0; idx < len(encodedPartition); idx++ { rows = append(rows, indexedRow{idx: idx, row: encodedPartition[idx]}) @@ -388,11 +444,15 @@ func (w *windower) computeWindowFunctions(ctx context.Context, evalCtx *tree.Eva // partitionPreviouslySortedFuncIdx maps index of a window function f1 // to the index of another window function f2 with the same ORDER BY // clause such that f2 will have been processed before f1. + usage = sliceOfIndexedRowsSliceOverhead + sizeOfSliceOfIndexedRows*int64(len(w.windowFns)) + if err := w.partitionsAcc.Grow(w.ctx, usage); err != nil { + return err + } + sortedPartitionsCache := make([][]indexedRows, len(w.windowFns)) partitionPreviouslySortedFuncIdx := make([]int, len(w.windowFns)) for i := 0; i < len(w.windowFns); i++ { partitionPreviouslySortedFuncIdx[i] = -1 } - sortedPartitionsCache := make([][]indexedRows, len(w.windowFns)) shouldCacheSortedPartitions := make([]bool, len(w.windowFns)) for windowFnIdx, windowFn := range w.windowFns { for laterFnIdx := windowFnIdx + 1; laterFnIdx < len(w.windowFns); laterFnIdx++ { @@ -409,6 +469,10 @@ func (w *windower) computeWindowFunctions(ctx context.Context, evalCtx *tree.Eva } for windowFnIdx, windowFn := range w.windowFns { + usage = rowSliceOverhead + sizeOfRow*int64(len(w.encodedPartitions)) + if err := w.resultsAcc.Grow(w.ctx, usage); err != nil { + return err + } w.windowValues[windowFnIdx] = make([][]tree.Datum, len(w.encodedPartitions)) frameRun := &tree.WindowFrameRun{ @@ -437,6 +501,10 @@ func (w *windower) computeWindowFunctions(ctx context.Context, evalCtx *tree.Eva defer builtin.Close(ctx, evalCtx) partition := partitions[partitionIdx] + usage = datumSliceOverhead + sizeOfDatum*int64(partition.Len()) + if err := w.resultsAcc.Grow(w.ctx, usage); err != nil { + return err + } w.windowValues[windowFnIdx][partitionIdx] = make([]tree.Datum, partition.Len()) if len(windowFn.ordering.Columns) > 0 { @@ -462,10 +530,17 @@ func (w *windower) computeWindowFunctions(ctx context.Context, evalCtx *tree.Eva // Later window functions will need rows in the same order, // so we cache copies of all sorted partitions. if sortedPartitionsCache[windowFnIdx] == nil { + usage = indexedRowsStructSliceOverhead + sizeOfIndexedRowsStruct*int64(len(partitions)) + if err := w.partitionsAcc.Grow(w.ctx, usage); err != nil { + return err + } sortedPartitionsCache[windowFnIdx] = make([]indexedRows, len(partitions)) } - // TODO(yuzefovich): we should figure out how to avoid making this - // deep copy. + // TODO(yuzefovich): figure out how to avoid making this deep copy. + usage = indexedRowStructSliceOverhead + sizeOfIndexedRowStruct*int64(partition.Len()) + if err := w.partitionsAcc.Grow(w.ctx, usage); err != nil { + return err + } sortedPartitionsCache[windowFnIdx][partitionIdx] = partition.makeCopy() } } @@ -599,6 +674,19 @@ type peerGroupChecker interface { InSameGroup(i, j int) bool } +const sizeOfIndexedRowsStruct = int64(unsafe.Sizeof(indexedRows{})) +const indexedRowsStructSliceOverhead = int64(unsafe.Sizeof([]indexedRows{})) +const sizeOfSliceOfIndexedRows = int64(unsafe.Sizeof([]indexedRows{})) +const sliceOfIndexedRowsSliceOverhead = int64(unsafe.Sizeof([][]indexedRows{})) +const sizeOfIndexedRowStruct = int64(unsafe.Sizeof(indexedRow{})) +const indexedRowStructSliceOverhead = int64(unsafe.Sizeof([]indexedRow{})) +const sizeOfSliceOfRows = int64(unsafe.Sizeof([][]tree.Datum{})) +const sliceOfRowsSliceOverhead = int64(unsafe.Sizeof([][][]tree.Datum{})) +const sizeOfRow = int64(unsafe.Sizeof([]tree.Datum{})) +const rowSliceOverhead = int64(unsafe.Sizeof([][]tree.Datum{})) +const sizeOfDatum = int64(unsafe.Sizeof(tree.Datum(nil))) +const datumSliceOverhead = int64(unsafe.Sizeof([]tree.Datum(nil))) + // indexedRows are rows with the corresponding indices. type indexedRows struct { rows []indexedRow @@ -644,3 +732,37 @@ func (ir indexedRow) GetDatums(startColIdx, endColIdx int) tree.Datums { } return datums } + +var _ DistSQLSpanStats = &WindowerStats{} + +const windowerTagPrefix = "windower." + +// Stats implements the SpanStats interface. +func (ws *WindowerStats) Stats() map[string]string { + inputStatsMap := ws.InputStats.Stats(windowerTagPrefix) + inputStatsMap[windowerTagPrefix+maxMemoryTagSuffix] = humanizeutil.IBytes(ws.MaxAllocatedMem) + return inputStatsMap +} + +// StatsForQueryPlan implements the DistSQLSpanStats interface. +func (ws *WindowerStats) StatsForQueryPlan() []string { + return append( + ws.InputStats.StatsForQueryPlan("" /* prefix */), + fmt.Sprintf("%s: %s", maxMemoryQueryPlanSuffix, humanizeutil.IBytes(ws.MaxAllocatedMem)), + ) +} +func (w *windower) outputStatsToTrace() { + is, ok := getInputStats(w.flowCtx, w.input) + if !ok { + return + } + if sp := opentracing.SpanFromContext(w.ctx); sp != nil { + tracing.SetSpanStats( + sp, + &WindowerStats{ + InputStats: is, + MaxAllocatedMem: w.memMonitor.MaximumBytes(), + }, + ) + } +} diff --git a/pkg/sql/logictest/testdata/planner_test/distsql_auto_mode b/pkg/sql/logictest/testdata/planner_test/distsql_auto_mode index 674e7be6857b..311babf02744 100644 --- a/pkg/sql/logictest/testdata/planner_test/distsql_auto_mode +++ b/pkg/sql/logictest/testdata/planner_test/distsql_auto_mode @@ -156,3 +156,9 @@ query B SELECT automatic FROM [EXPLAIN (DISTSQL) SELECT sum(k) FROM kv WHERE FALSE] ---- true + +# This query verifies stat collection for the tableReader and windower. +query T +SELECT url FROM [EXPLAIN ANALYZE (DISTSQL) SELECT avg(k) OVER () FROM kv] +---- +https://cockroachdb.github.io/distsqlplan/decode.html#eJyUkUFLMzEQhu_frwjv6RMC3RRPOVUvUgQrRfQge4iboQQ3m2Uma1vK_nfp5qAVKvU47-SZ94Ec0CVPDy6SwL7CoNboOTUkkvgYlQdLv4OtNELXD_kY1xpNYoI9IIfcEiye3FtLa3KeeFZBw1N2oZ3O9hyi4_3i_QManLaimJy3ykBDsmtblUMkqyqBxmrIVi0M6lEjDfmrULLbEKwZ9eVSL6HzaUs8M6dGN893_xfm6gKd6HYqUky8V4OQt-q6Uvfh9qze_C96a5I-dUIncucuV2OtQX5D5V8kDdzQI6dmqinjauKmwJPksjVlWHZldRT8Dptf4fkPuB7_fQYAAP__QWu4Ow==