-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathkhashaggregate.go
More file actions
408 lines (354 loc) · 11.2 KB
/
khashaggregate.go
File metadata and controls
408 lines (354 loc) · 11.2 KB
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
// Copyright (c) The Thanos Community Authors.
// Licensed under the Apache License 2.0.
package aggregate
import (
"container/heap"
"context"
"fmt"
"math"
"sort"
"sync"
"github.com/thanos-io/promql-engine/execution/model"
"github.com/thanos-io/promql-engine/execution/telemetry"
"github.com/thanos-io/promql-engine/query"
"github.com/thanos-io/promql-engine/warnings"
"github.com/efficientgo/core/errors"
"github.com/prometheus/prometheus/model/histogram"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/promql/parser"
"github.com/prometheus/prometheus/promql/parser/posrange"
"github.com/prometheus/prometheus/util/annotations"
"golang.org/x/exp/slices"
)
type kAggregate struct {
next model.VectorOperator
paramOp model.VectorOperator
by bool
labels []string
aggregation parser.ItemType
stepsBatch int
compare func(float64, float64) bool
once sync.Once
series []labels.Labels
inputToHeap []*samplesHeap
heaps []*samplesHeap
params []float64
tempBuf []model.StepVector
paramBuf []model.StepVector
}
func NewKHashAggregate(
next model.VectorOperator,
paramOp model.VectorOperator,
aggregation parser.ItemType,
by bool,
labels []string,
opts *query.Options,
) (model.VectorOperator, error) {
var compare func(float64, float64) bool
if aggregation == parser.TOPK {
compare = func(f float64, s float64) bool {
return f < s
}
} else if aggregation == parser.BOTTOMK {
compare = func(f float64, s float64) bool {
return s < f
}
} else if aggregation != parser.LIMITK && aggregation != parser.LIMIT_RATIO {
return nil, errors.Newf("Unsupported aggregate expression: %v", aggregation)
}
// Grouping labels need to be sorted in order for metric hashing to work.
// https://github.com/prometheus/prometheus/blob/8ed39fdab1ead382a354e45ded999eb3610f8d5f/model/labels/labels.go#L162-L181
slices.Sort(labels)
op := &kAggregate{
next: next,
by: by,
aggregation: aggregation,
labels: labels,
paramOp: paramOp,
compare: compare,
params: make([]float64, opts.StepsBatch),
stepsBatch: opts.StepsBatch,
}
return telemetry.NewOperator(telemetry.NewTelemetry(op, opts.EnableAnalysis, opts.EnablePerStepStats, opts.Start.UnixMilli(), opts.End.UnixMilli(), opts.Step, opts.SampleLimiter), op), nil
}
func (a *kAggregate) Next(ctx context.Context, buf []model.StepVector) (int, error) {
select {
case <-ctx.Done():
return 0, ctx.Err()
default:
}
var err error
a.once.Do(func() { err = a.init(ctx) })
if err != nil {
return 0, err
}
nIn, err := a.next.Next(ctx, a.tempBuf)
if err != nil {
return 0, err
}
if nIn == 0 {
return 0, nil
}
in := a.tempBuf[:nIn]
nParam, err := a.paramOp.Next(ctx, a.paramBuf)
if err != nil {
return 0, err
}
for i := range nParam {
a.params[i] = a.paramBuf[i].Samples[0]
val := a.params[i]
switch a.aggregation {
case parser.TOPK, parser.BOTTOMK, parser.LIMITK:
if math.IsNaN(val) {
return 0, errors.New("Parameter value is NaN")
}
if val > math.MaxInt64 {
return 0, errors.Newf("Scalar value %v overflows int64", val)
}
if val < math.MinInt64 {
return 0, errors.Newf("Scalar value %v underflows int64", val)
}
case parser.LIMIT_RATIO:
if math.IsNaN(val) {
return 0, errors.Newf("Ratio value is NaN")
}
switch {
case val < -1.0:
val = -1.0
warnings.AddToContext(annotations.NewInvalidRatioWarning(a.params[i], val, posrange.PositionRange{}), ctx)
case val > 1.0:
val = 1.0
warnings.AddToContext(annotations.NewInvalidRatioWarning(a.params[i], val, posrange.PositionRange{}), ctx)
}
a.params[i] = val
}
}
n := 0
for i := 0; i < nIn && n < len(buf); i++ {
vector := in[i]
// Skip steps where the argument is less than or equal to 0, limit_ratio is an exception.
if (a.aggregation != parser.LIMIT_RATIO && int(a.params[i]) <= 0) || (a.aggregation == parser.LIMIT_RATIO && a.params[i] == 0) {
buf[n] = model.StepVector{T: vector.T}
n++
continue
}
if a.aggregation != parser.LIMITK && a.aggregation != parser.LIMIT_RATIO && len(vector.Histograms) > 0 {
warnings.AddToContext(annotations.NewHistogramIgnoredInAggregationInfo(a.aggregation.String(), posrange.PositionRange{}), ctx)
}
var k int
var ratio float64
if a.aggregation == parser.LIMIT_RATIO {
ratio = a.params[i]
} else {
k = int(a.params[i])
}
buf[n].Reset(vector.T)
a.aggregate(&buf[n], k, ratio, vector.SampleIDs, vector.Samples, vector.HistogramIDs, vector.Histograms)
n++
}
return n, nil
}
func (a *kAggregate) Series(ctx context.Context) ([]labels.Labels, error) {
var err error
a.once.Do(func() { err = a.init(ctx) })
if err != nil {
return nil, err
}
return a.series, nil
}
func (a *kAggregate) String() string {
if a.by {
return fmt.Sprintf("[kaggregate] %v by (%v)", a.aggregation.String(), a.labels)
}
return fmt.Sprintf("[kaggregate] %v without (%v)", a.aggregation.String(), a.labels)
}
func (a *kAggregate) Explain() (next []model.VectorOperator) {
return []model.VectorOperator{a.paramOp, a.next}
}
func (a *kAggregate) init(ctx context.Context) error {
series, err := a.next.Series(ctx)
if err != nil {
return err
}
var (
// heapsHash is a map of hash of the series to output samples heap for that series.
heapsHash = make(map[uint64]*samplesHeap)
// hashingBuf is a buffer used for metric hashing.
hashingBuf = make([]byte, 1024)
// builder is a scratch builder used for creating output series.
builder labels.ScratchBuilder
)
labelsMap := make(map[string]struct{})
for _, lblName := range a.labels {
labelsMap[lblName] = struct{}{}
}
for i := range series {
hash, _ := hashMetric(builder, series[i], !a.by, a.labels, labelsMap, hashingBuf)
h, ok := heapsHash[hash]
if !ok {
h = &samplesHeap{compare: a.compare}
heapsHash[hash] = h
a.heaps = append(a.heaps, h)
}
a.inputToHeap = append(a.inputToHeap, h)
}
a.series = series
// Allocate outer slice for buffers; inner slices will be allocated by child operators
// or grow on demand. This avoids over-allocation when aggregating many series to few.
a.tempBuf = make([]model.StepVector, a.stepsBatch)
a.paramBuf = make([]model.StepVector, a.stepsBatch)
return nil
}
// aggregates based on the given parameter k (or ratio for limit_ratio) and timeseries, supported aggregation are
// topk: gives the 'k' largest element based on the sample values
// bottomk: gives the 'k' smallest element based on the sample values
// limitk: samples the first 'k' element from the given timeseries (has native histogram support)
// limit_ratio: deterministically samples out the 'ratio' amount of the samples from the given timeseries (also has native histogram support).
func (a *kAggregate) aggregate(out *model.StepVector, k int, ratio float64, sampleIDs []uint64, samples []float64, histogramIDs []uint64, histograms []*histogram.FloatHistogram) {
groupsRemaining := len(a.heaps)
switch a.aggregation {
case parser.TOPK, parser.BOTTOMK:
for i, sId := range sampleIDs {
sampleHeap := a.inputToHeap[sId]
switch {
case sampleHeap.Len() < k:
heap.Push(sampleHeap, &entry{sId: sId, total: samples[i]})
case sampleHeap.compare(sampleHeap.entries[0].total, samples[i]) || (math.IsNaN(sampleHeap.entries[0].total) && !math.IsNaN(samples[i])):
sampleHeap.entries[0].sId = sId
sampleHeap.entries[0].total = samples[i]
if k > 1 {
heap.Fix(sampleHeap, 0)
}
}
}
case parser.LIMITK:
if len(histogramIDs) == 0 {
for i, sId := range sampleIDs {
sampleHeap := a.inputToHeap[sId]
if sampleHeap.Len() < k {
heap.Push(sampleHeap, &entry{sId: sId, total: samples[i]})
if sampleHeap.Len() == k {
groupsRemaining--
}
if groupsRemaining == 0 {
break
}
}
}
} else {
histogramIndex := 0
sampleIndex := 0
// pick the first 'k' samples based on the increasing order of their ids
for histogramIndex < len(histogramIDs) || sampleIndex < len(sampleIDs) {
var currentID uint64
haveSample := sampleIndex < len(sampleIDs)
haveHistogram := histogramIndex < len(histogramIDs)
if haveSample && haveHistogram {
currentID = uint64(min(sampleIDs[sampleIndex], histogramIDs[histogramIndex]))
} else if haveHistogram {
currentID = histogramIDs[histogramIndex]
} else {
currentID = sampleIDs[sampleIndex]
}
sampleHeap := a.inputToHeap[currentID]
if sampleHeap.Len() < k {
if haveHistogram && histogramIDs[histogramIndex] == currentID {
heap.Push(sampleHeap, &entry{histId: currentID, histogramSample: histograms[histogramIndex]})
histogramIndex++
} else if haveSample && sampleIDs[sampleIndex] == currentID {
heap.Push(sampleHeap, &entry{sId: currentID, total: samples[sampleIndex]})
sampleIndex++
}
if sampleHeap.Len() == k {
groupsRemaining--
}
if groupsRemaining == 0 {
break
}
} else {
if haveHistogram && histogramIDs[histogramIndex] == currentID {
histogramIndex++
} else if haveSample && sampleIDs[sampleIndex] == currentID {
sampleIndex++
}
}
}
}
case parser.LIMIT_RATIO:
for i, sId := range sampleIDs {
sampleHeap := a.inputToHeap[sId]
if addRatioSample(ratio, a.series[sId]) {
heap.Push(sampleHeap, &entry{sId: sId, total: samples[i]})
}
}
for i, histId := range histogramIDs {
sampleHeap := a.inputToHeap[histId]
if addRatioSample(ratio, a.series[histId]) {
heap.Push(sampleHeap, &entry{histId: histId, histogramSample: histograms[i]})
}
}
}
// Add results from all heaps to the output step vector.
inputSize := len(sampleIDs) + len(histogramIDs)
hint := inputSize
if k > 0 && k*len(a.heaps) < inputSize {
hint = k * len(a.heaps)
} else if ratio != 0 {
estimated := int(float64(inputSize) * math.Abs(ratio))
if estimated < hint {
hint = estimated
}
}
for _, sampleHeap := range a.heaps {
// for topk and bottomk the heap keeps the lowest value on top, so reverse it.
if a.aggregation == parser.TOPK || a.aggregation == parser.BOTTOMK {
sort.Sort(sort.Reverse(sampleHeap))
}
sampleHeap.addSamplesToPool(out, hint)
}
}
type entry struct {
sId uint64
histId uint64
total float64
histogramSample *histogram.FloatHistogram
}
type samplesHeap struct {
entries []entry
compare func(float64, float64) bool
}
func (s samplesHeap) Len() int {
return len(s.entries)
}
func (s *samplesHeap) addSamplesToPool(stepVector *model.StepVector, hint int) {
for _, e := range s.entries {
if e.histogramSample == nil {
stepVector.AppendSampleWithSizeHint(e.sId, e.total, hint)
} else {
stepVector.AppendHistogramWithSizeHint(e.histId, e.histogramSample, hint)
}
}
s.entries = s.entries[:0]
}
func (s samplesHeap) Less(i, j int) bool {
if math.IsNaN(s.entries[i].total) {
return true
}
if s.compare == nil { // this is case for limitk as it doesn't require any sorting logic
return false
}
return s.compare(s.entries[i].total, s.entries[j].total)
}
func (s samplesHeap) Swap(i, j int) {
s.entries[i], s.entries[j] = s.entries[j], s.entries[i]
}
func (s *samplesHeap) Push(x any) {
s.entries = append(s.entries, *(x.(*entry)))
}
func (s *samplesHeap) Pop() any {
old := (*s).entries
n := len(old)
el := old[n-1]
(*s).entries = old[0 : n-1]
return el
}