-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathweighted_finder.go
177 lines (157 loc) · 4.67 KB
/
weighted_finder.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
// Copyright 2022 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 split
import (
"fmt"
"math"
"sort"
"time"
"github.com/cockroachdb/cockroach/pkg/roachpb"
)
type weightedSample struct {
key roachpb.Key
weight float64
left, right float64
count int
}
type RandSource interface {
Float64() float64
Intn(n int) int
}
type WeightedFinder struct {
samples [splitKeySampleSize]weightedSample
count int
totalWeight float64
startTime time.Time
randSource RandSource
}
func NewWeightedFinder(startTime time.Time, randSource RandSource) *WeightedFinder {
return &WeightedFinder{
startTime: startTime,
randSource: randSource,
}
}
// Ready checks if the WeightedFinder has been initialized with a sufficient
// sample duration.
func (f *WeightedFinder) Ready(nowTime time.Time) bool {
return nowTime.Sub(f.startTime) > RecordDurationThreshold
}
func (f *WeightedFinder) record(key roachpb.Key, weight float64) {
if f == nil {
return
}
var idx int
count := f.count
f.count++
f.totalWeight += weight
if count < splitKeySampleSize {
idx = count
} else if f.randSource.Float64() > splitKeySampleSize*weight/f.totalWeight {
for i := range f.samples {
if comp := key.Compare(f.samples[i].key); comp < 0 {
// Case key < f.samples[i].Key (left is exclusive to split key).
f.samples[i].left += weight
} else {
// Case key >= f.samples[i].Key (right is inclusive to split key).
f.samples[i].right += weight
}
f.samples[i].count++
}
return
} else {
idx = f.randSource.Intn(splitKeySampleSize)
}
// Note we always use the start key of the span. We could
// take the average of the byte slices, but that seems
// unnecessarily complex for practical usage.
f.samples[idx] = weightedSample{key: key, weight: weight}
}
func (f *WeightedFinder) Record(span roachpb.Span, weight float64) {
if span.EndKey == nil {
f.record(span.Key, weight)
} else {
f.record(span.Key, weight/2)
f.record(span.EndKey, weight/2)
}
}
// Key finds an appropriate split point based on the Reservoir sampling method.
// Returns a nil key if no appropriate key was found.
func (f *WeightedFinder) Key() roachpb.Key {
if f == nil {
return nil
}
var bestIdx = -1
var bestScore float64 = 1
for i, s := range f.samples {
if s.count < splitKeyMinCounter {
continue
}
balanceScore := math.Abs(s.left-s.right) / (s.left + s.right)
if balanceScore >= splitKeyThreshold {
continue
}
if balanceScore < bestScore {
bestIdx = i
bestScore = balanceScore
}
}
if bestIdx == -1 {
return nil
}
return f.samples[bestIdx].key
}
// noSplitKeyCause iterates over all sampled candidate split keys and
// determines the number of samples that don't pass each split key requirement
// (e.g. insufficient counters, imbalance in left and right counters).
func (f *WeightedFinder) noSplitKeyCause() (insufficientCounters, imbalance int) {
for _, s := range f.samples {
if s.count < splitKeyMinCounter {
insufficientCounters++
} else if balanceScore := math.Abs(s.left-s.right) / (s.left + s.right); balanceScore >= splitKeyThreshold {
imbalance++
}
}
return
}
// NoSplitKeyCauseLogMsg returns a log message containing all of this
// information if not all samples are invalid due to insufficient counters,
// otherwise returns an empty string.
func (f *WeightedFinder) NoSplitKeyCauseLogMsg() string {
insufficientCounters, imbalance := f.noSplitKeyCause()
if insufficientCounters == splitKeySampleSize {
return ""
}
noSplitKeyCauseLogMsg := fmt.Sprintf("No split key found: insufficient counters = %d, imbalance = %d", insufficientCounters, imbalance)
return noSplitKeyCauseLogMsg
}
// PopularKeyFrequency returns the percentage of the total weight that the most
// popular key (as measured by weight) appears in f.samples.
func (f *WeightedFinder) PopularKeyFrequency() float64 {
sort.Slice(f.samples[:], func(i, j int) bool {
return f.samples[i].key.Compare(f.samples[j].key) < 0
})
weight := f.samples[0].weight
currentKeyWeight := weight
popularKeyWeight := weight
totalWeight := weight
for i := 1; i < len(f.samples); i++ {
weight := f.samples[i].weight
if f.samples[i].key.Equal(f.samples[i-1].key) {
currentKeyWeight += weight
} else {
currentKeyWeight = weight
}
if popularKeyWeight < currentKeyWeight {
popularKeyWeight = currentKeyWeight
}
totalWeight += weight
}
return popularKeyWeight / totalWeight
}