Line data Source code
1 : // Copyright 2018 The LevelDB-Go and Pebble Authors. All rights reserved. Use
2 : // of this source code is governed by a BSD-style license that can be found in
3 : // the LICENSE file.
4 :
5 : package pebble
6 :
7 : import (
8 : "bytes"
9 : "fmt"
10 : "math"
11 : "sort"
12 : "strings"
13 :
14 : "github.com/cockroachdb/pebble/internal/base"
15 : "github.com/cockroachdb/pebble/internal/humanize"
16 : "github.com/cockroachdb/pebble/internal/manifest"
17 : )
18 :
19 : // The minimum count for an intra-L0 compaction. This matches the RocksDB
20 : // heuristic.
21 : const minIntraL0Count = 4
22 :
23 : type compactionEnv struct {
24 : // diskAvailBytes holds a statistic on the number of bytes available on
25 : // disk, as reported by the filesystem. It's used to be more restrictive in
26 : // expanding compactions if available disk space is limited.
27 : //
28 : // The cached value (d.diskAvailBytes) is updated whenever a file is deleted
29 : // and whenever a compaction or flush completes. Since file removal is the
30 : // primary means of reclaiming space, there is a rough bound on the
31 : // statistic's staleness when available bytes is growing. Compactions and
32 : // flushes are longer, slower operations and provide a much looser bound
33 : // when available bytes is decreasing.
34 : diskAvailBytes uint64
35 : earliestUnflushedSeqNum uint64
36 : earliestSnapshotSeqNum uint64
37 : inProgressCompactions []compactionInfo
38 : readCompactionEnv readCompactionEnv
39 : }
40 :
41 : type compactionPicker interface {
42 : getScores([]compactionInfo) [numLevels]float64
43 : getBaseLevel() int
44 : estimatedCompactionDebt(l0ExtraSize uint64) uint64
45 : pickAuto(env compactionEnv) (pc *pickedCompaction)
46 : pickElisionOnlyCompaction(env compactionEnv) (pc *pickedCompaction)
47 : pickRewriteCompaction(env compactionEnv) (pc *pickedCompaction)
48 : pickReadTriggeredCompaction(env compactionEnv) (pc *pickedCompaction)
49 : forceBaseLevel1()
50 : }
51 :
52 : // readCompactionEnv is used to hold data required to perform read compactions
53 : type readCompactionEnv struct {
54 : rescheduleReadCompaction *bool
55 : readCompactions *readCompactionQueue
56 : flushing bool
57 : }
58 :
59 : // Information about in-progress compactions provided to the compaction picker.
60 : // These are used to constrain the new compactions that will be picked.
61 : type compactionInfo struct {
62 : // versionEditApplied is true if this compaction's version edit has already
63 : // been committed. The compaction may still be in-progress deleting newly
64 : // obsolete files.
65 : versionEditApplied bool
66 : inputs []compactionLevel
67 : outputLevel int
68 : smallest InternalKey
69 : largest InternalKey
70 : }
71 :
72 1 : func (info compactionInfo) String() string {
73 1 : var buf bytes.Buffer
74 1 : var largest int
75 1 : for i, in := range info.inputs {
76 1 : if i > 0 {
77 1 : fmt.Fprintf(&buf, " -> ")
78 1 : }
79 1 : fmt.Fprintf(&buf, "L%d", in.level)
80 1 : in.files.Each(func(m *fileMetadata) {
81 1 : fmt.Fprintf(&buf, " %s", m.FileNum)
82 1 : })
83 1 : if largest < in.level {
84 1 : largest = in.level
85 1 : }
86 : }
87 1 : if largest != info.outputLevel || len(info.inputs) == 1 {
88 1 : fmt.Fprintf(&buf, " -> L%d", info.outputLevel)
89 1 : }
90 1 : return buf.String()
91 : }
92 :
93 : type sortCompactionLevelsByPriority []candidateLevelInfo
94 :
95 1 : func (s sortCompactionLevelsByPriority) Len() int {
96 1 : return len(s)
97 1 : }
98 :
99 : // A level should be picked for compaction if the compensatedScoreRatio is >= the
100 : // compactionScoreThreshold.
101 : const compactionScoreThreshold = 1
102 :
103 : // Less should return true if s[i] must be placed earlier than s[j] in the final
104 : // sorted list. The candidateLevelInfo for the level placed earlier is more likely
105 : // to be picked for a compaction.
106 1 : func (s sortCompactionLevelsByPriority) Less(i, j int) bool {
107 1 : iShouldCompact := s[i].compensatedScoreRatio >= compactionScoreThreshold
108 1 : jShouldCompact := s[j].compensatedScoreRatio >= compactionScoreThreshold
109 1 : // Ordering is defined as decreasing on (shouldCompact, uncompensatedScoreRatio)
110 1 : // where shouldCompact is 1 for true and 0 for false.
111 1 : if iShouldCompact && !jShouldCompact {
112 1 : return true
113 1 : }
114 1 : if !iShouldCompact && jShouldCompact {
115 1 : return false
116 1 : }
117 :
118 1 : if s[i].uncompensatedScoreRatio != s[j].uncompensatedScoreRatio {
119 1 : return s[i].uncompensatedScoreRatio > s[j].uncompensatedScoreRatio
120 1 : }
121 1 : return s[i].level < s[j].level
122 : }
123 :
124 1 : func (s sortCompactionLevelsByPriority) Swap(i, j int) {
125 1 : s[i], s[j] = s[j], s[i]
126 1 : }
127 :
128 : // sublevelInfo is used to tag a LevelSlice for an L0 sublevel with the
129 : // sublevel.
130 : type sublevelInfo struct {
131 : manifest.LevelSlice
132 : sublevel manifest.Level
133 : }
134 :
135 1 : func (cl sublevelInfo) Clone() sublevelInfo {
136 1 : return sublevelInfo{
137 1 : sublevel: cl.sublevel,
138 1 : LevelSlice: cl.LevelSlice.Reslice(func(start, end *manifest.LevelIterator) {}),
139 : }
140 : }
141 1 : func (cl sublevelInfo) String() string {
142 1 : return fmt.Sprintf(`Sublevel %s; Levels %s`, cl.sublevel, cl.LevelSlice)
143 1 : }
144 :
145 : // generateSublevelInfo will generate the level slices for each of the sublevels
146 : // from the level slice for all of L0.
147 1 : func generateSublevelInfo(cmp base.Compare, levelFiles manifest.LevelSlice) []sublevelInfo {
148 1 : sublevelMap := make(map[uint64][]*fileMetadata)
149 1 : it := levelFiles.Iter()
150 1 : for f := it.First(); f != nil; f = it.Next() {
151 1 : sublevelMap[uint64(f.SubLevel)] = append(sublevelMap[uint64(f.SubLevel)], f)
152 1 : }
153 :
154 1 : var sublevels []int
155 1 : for level := range sublevelMap {
156 1 : sublevels = append(sublevels, int(level))
157 1 : }
158 1 : sort.Ints(sublevels)
159 1 :
160 1 : var levelSlices []sublevelInfo
161 1 : for _, sublevel := range sublevels {
162 1 : metas := sublevelMap[uint64(sublevel)]
163 1 : levelSlices = append(
164 1 : levelSlices,
165 1 : sublevelInfo{
166 1 : manifest.NewLevelSliceKeySorted(cmp, metas),
167 1 : manifest.L0Sublevel(sublevel),
168 1 : },
169 1 : )
170 1 : }
171 1 : return levelSlices
172 : }
173 :
174 : // compactionPickerMetrics holds metrics related to the compaction picking process
175 : type compactionPickerMetrics struct {
176 : // scores contains the compensatedScoreRatio from the candidateLevelInfo.
177 : scores []float64
178 : singleLevelOverlappingRatio float64
179 : multiLevelOverlappingRatio float64
180 : }
181 :
182 : // pickedCompaction contains information about a compaction that has already
183 : // been chosen, and is being constructed. Compaction construction info lives in
184 : // this struct, and is copied over into the compaction struct when that's
185 : // created.
186 : type pickedCompaction struct {
187 : cmp Compare
188 : // score of the chosen compaction. This is the same as the
189 : // compensatedScoreRatio in the candidateLevelInfo.
190 : score float64
191 : // kind indicates the kind of compaction.
192 : kind compactionKind
193 : // startLevel is the level that is being compacted. Inputs from startLevel
194 : // and outputLevel will be merged to produce a set of outputLevel files.
195 : startLevel *compactionLevel
196 : // outputLevel is the level that files are being produced in. outputLevel is
197 : // equal to startLevel+1 except when:
198 : // - if startLevel is 0, the output level equals compactionPicker.baseLevel().
199 : // - in multilevel compaction, the output level is the lowest level involved in
200 : // the compaction
201 : outputLevel *compactionLevel
202 : // extraLevels contain additional levels in between the input and output
203 : // levels that get compacted in multi level compactions
204 : extraLevels []*compactionLevel
205 : inputs []compactionLevel
206 : // LBase at the time of compaction picking.
207 : baseLevel int
208 : // L0-specific compaction info. Set to a non-nil value for all compactions
209 : // where startLevel == 0 that were generated by L0Sublevels.
210 : lcf *manifest.L0CompactionFiles
211 : // maxOutputFileSize is the maximum size of an individual table created
212 : // during compaction.
213 : maxOutputFileSize uint64
214 : // maxOverlapBytes is the maximum number of bytes of overlap allowed for a
215 : // single output table with the tables in the grandparent level.
216 : maxOverlapBytes uint64
217 : // maxReadCompactionBytes is the maximum bytes a read compaction is allowed to
218 : // overlap in its output level with. If the overlap is greater than
219 : // maxReadCompaction bytes, then we don't proceed with the compaction.
220 : maxReadCompactionBytes uint64
221 : // The boundaries of the input data.
222 : smallest InternalKey
223 : largest InternalKey
224 : version *version
225 : pickerMetrics compactionPickerMetrics
226 : }
227 :
228 1 : func defaultOutputLevel(startLevel, baseLevel int) int {
229 1 : outputLevel := startLevel + 1
230 1 : if startLevel == 0 {
231 1 : outputLevel = baseLevel
232 1 : }
233 1 : if outputLevel >= numLevels-1 {
234 1 : outputLevel = numLevels - 1
235 1 : }
236 1 : return outputLevel
237 : }
238 :
239 : func newPickedCompaction(
240 : opts *Options, cur *version, startLevel, outputLevel, baseLevel int,
241 1 : ) *pickedCompaction {
242 1 : if startLevel > 0 && startLevel < baseLevel {
243 1 : panic(fmt.Sprintf("invalid compaction: start level %d should not be empty (base level %d)",
244 1 : startLevel, baseLevel))
245 : }
246 :
247 1 : adjustedLevel := adjustedOutputLevel(outputLevel, baseLevel)
248 1 : pc := &pickedCompaction{
249 1 : cmp: opts.Comparer.Compare,
250 1 : version: cur,
251 1 : baseLevel: baseLevel,
252 1 : inputs: []compactionLevel{{level: startLevel}, {level: outputLevel}},
253 1 : maxOutputFileSize: uint64(opts.Level(adjustedLevel).TargetFileSize),
254 1 : maxOverlapBytes: maxGrandparentOverlapBytes(opts, adjustedLevel),
255 1 : maxReadCompactionBytes: maxReadCompactionBytes(opts, adjustedLevel),
256 1 : }
257 1 : pc.startLevel = &pc.inputs[0]
258 1 : pc.outputLevel = &pc.inputs[1]
259 1 : return pc
260 : }
261 :
262 : // adjustedOutputLevel is the output level used for the purpose of
263 : // determining the target output file size, overlap bytes, and expanded
264 : // bytes, taking into account the base level.
265 1 : func adjustedOutputLevel(outputLevel int, baseLevel int) int {
266 1 : adjustedOutputLevel := outputLevel
267 1 : if adjustedOutputLevel > 0 {
268 1 : // Output level is in the range [baseLevel, numLevels]. For the purpose of
269 1 : // determining the target output file size, overlap bytes, and expanded
270 1 : // bytes, we want to adjust the range to [1,numLevels].
271 1 : adjustedOutputLevel = 1 + outputLevel - baseLevel
272 1 : }
273 1 : return adjustedOutputLevel
274 : }
275 :
276 : func newPickedCompactionFromL0(
277 : lcf *manifest.L0CompactionFiles, opts *Options, vers *version, baseLevel int, isBase bool,
278 1 : ) *pickedCompaction {
279 1 : outputLevel := baseLevel
280 1 : if !isBase {
281 1 : outputLevel = 0 // Intra L0
282 1 : }
283 :
284 1 : pc := newPickedCompaction(opts, vers, 0, outputLevel, baseLevel)
285 1 : pc.lcf = lcf
286 1 : pc.outputLevel.level = outputLevel
287 1 :
288 1 : // Manually build the compaction as opposed to calling
289 1 : // pickAutoHelper. This is because L0Sublevels has already added
290 1 : // any overlapping L0 SSTables that need to be added, and
291 1 : // because compactions built by L0SSTables do not necessarily
292 1 : // pick contiguous sequences of files in pc.version.Levels[0].
293 1 : files := make([]*manifest.FileMetadata, 0, len(lcf.Files))
294 1 : iter := vers.Levels[0].Iter()
295 1 : for f := iter.First(); f != nil; f = iter.Next() {
296 1 : if lcf.FilesIncluded[f.L0Index] {
297 1 : files = append(files, f)
298 1 : }
299 : }
300 1 : pc.startLevel.files = manifest.NewLevelSliceSeqSorted(files)
301 1 : return pc
302 : }
303 :
304 1 : func (pc *pickedCompaction) String() string {
305 1 : var builder strings.Builder
306 1 : builder.WriteString(fmt.Sprintf(`Score=%f, `, pc.score))
307 1 : builder.WriteString(fmt.Sprintf(`Kind=%s, `, pc.kind))
308 1 : builder.WriteString(fmt.Sprintf(`AdjustedOutputLevel=%d, `, adjustedOutputLevel(pc.outputLevel.level, pc.baseLevel)))
309 1 : builder.WriteString(fmt.Sprintf(`maxOutputFileSize=%d, `, pc.maxOutputFileSize))
310 1 : builder.WriteString(fmt.Sprintf(`maxReadCompactionBytes=%d, `, pc.maxReadCompactionBytes))
311 1 : builder.WriteString(fmt.Sprintf(`smallest=%s, `, pc.smallest))
312 1 : builder.WriteString(fmt.Sprintf(`largest=%s, `, pc.largest))
313 1 : builder.WriteString(fmt.Sprintf(`version=%s, `, pc.version))
314 1 : builder.WriteString(fmt.Sprintf(`inputs=%s, `, pc.inputs))
315 1 : builder.WriteString(fmt.Sprintf(`startlevel=%s, `, pc.startLevel))
316 1 : builder.WriteString(fmt.Sprintf(`outputLevel=%s, `, pc.outputLevel))
317 1 : builder.WriteString(fmt.Sprintf(`extraLevels=%s, `, pc.extraLevels))
318 1 : builder.WriteString(fmt.Sprintf(`l0SublevelInfo=%s, `, pc.startLevel.l0SublevelInfo))
319 1 : builder.WriteString(fmt.Sprintf(`lcf=%s`, pc.lcf))
320 1 : return builder.String()
321 1 : }
322 :
323 : // Clone creates a deep copy of the pickedCompaction
324 1 : func (pc *pickedCompaction) clone() *pickedCompaction {
325 1 :
326 1 : // Quickly copy over fields that do not require special deep copy care, and
327 1 : // set all fields that will require a deep copy to nil.
328 1 : newPC := &pickedCompaction{
329 1 : cmp: pc.cmp,
330 1 : score: pc.score,
331 1 : kind: pc.kind,
332 1 : baseLevel: pc.baseLevel,
333 1 : maxOutputFileSize: pc.maxOutputFileSize,
334 1 : maxOverlapBytes: pc.maxOverlapBytes,
335 1 : maxReadCompactionBytes: pc.maxReadCompactionBytes,
336 1 : smallest: pc.smallest.Clone(),
337 1 : largest: pc.largest.Clone(),
338 1 :
339 1 : // TODO(msbutler): properly clone picker metrics
340 1 : pickerMetrics: pc.pickerMetrics,
341 1 :
342 1 : // Both copies see the same manifest, therefore, it's ok for them to se
343 1 : // share the same pc. version.
344 1 : version: pc.version,
345 1 : }
346 1 :
347 1 : newPC.inputs = make([]compactionLevel, len(pc.inputs))
348 1 : newPC.extraLevels = make([]*compactionLevel, 0, len(pc.extraLevels))
349 1 : for i := range pc.inputs {
350 1 : newPC.inputs[i] = pc.inputs[i].Clone()
351 1 : if i == 0 {
352 1 : newPC.startLevel = &newPC.inputs[i]
353 1 : } else if i == len(pc.inputs)-1 {
354 1 : newPC.outputLevel = &newPC.inputs[i]
355 1 : } else {
356 1 : newPC.extraLevels = append(newPC.extraLevels, &newPC.inputs[i])
357 1 : }
358 : }
359 :
360 1 : if len(pc.startLevel.l0SublevelInfo) > 0 {
361 1 : newPC.startLevel.l0SublevelInfo = make([]sublevelInfo, len(pc.startLevel.l0SublevelInfo))
362 1 : for i := range pc.startLevel.l0SublevelInfo {
363 1 : newPC.startLevel.l0SublevelInfo[i] = pc.startLevel.l0SublevelInfo[i].Clone()
364 1 : }
365 : }
366 1 : if pc.lcf != nil {
367 1 : newPC.lcf = pc.lcf.Clone()
368 1 : }
369 1 : return newPC
370 : }
371 :
372 : // maybeExpandedBounds is a helper function for setupInputs which ensures the
373 : // pickedCompaction's smallest and largest internal keys are updated iff
374 : // the candidate keys expand the key span. This avoids a bug for multi-level
375 : // compactions: during the second call to setupInputs, the picked compaction's
376 : // smallest and largest keys should not decrease the key span.
377 1 : func (pc *pickedCompaction) maybeExpandBounds(smallest InternalKey, largest InternalKey) {
378 1 : emptyKey := InternalKey{}
379 1 : if base.InternalCompare(pc.cmp, smallest, emptyKey) == 0 {
380 1 : if base.InternalCompare(pc.cmp, largest, emptyKey) != 0 {
381 0 : panic("either both candidate keys are empty or neither are empty")
382 : }
383 1 : return
384 : }
385 1 : if base.InternalCompare(pc.cmp, pc.smallest, emptyKey) == 0 {
386 1 : if base.InternalCompare(pc.cmp, pc.largest, emptyKey) != 0 {
387 0 : panic("either both pc keys are empty or neither are empty")
388 : }
389 1 : pc.smallest = smallest
390 1 : pc.largest = largest
391 1 : return
392 : }
393 1 : if base.InternalCompare(pc.cmp, pc.smallest, smallest) >= 0 {
394 1 : pc.smallest = smallest
395 1 : }
396 1 : if base.InternalCompare(pc.cmp, pc.largest, largest) <= 0 {
397 1 : pc.largest = largest
398 1 : }
399 : }
400 :
401 : // setupInputs returns true if a compaction has been set up. It returns false if
402 : // a concurrent compaction is occurring on the start or output level files.
403 : func (pc *pickedCompaction) setupInputs(
404 : opts *Options, diskAvailBytes uint64, startLevel *compactionLevel,
405 1 : ) bool {
406 1 : // maxExpandedBytes is the maximum size of an expanded compaction. If
407 1 : // growing a compaction results in a larger size, the original compaction
408 1 : // is used instead.
409 1 : maxExpandedBytes := expandedCompactionByteSizeLimit(
410 1 : opts, adjustedOutputLevel(pc.outputLevel.level, pc.baseLevel), diskAvailBytes,
411 1 : )
412 1 :
413 1 : // Expand the initial inputs to a clean cut.
414 1 : var isCompacting bool
415 1 : startLevel.files, isCompacting = expandToAtomicUnit(pc.cmp, startLevel.files, false /* disableIsCompacting */)
416 1 : if isCompacting {
417 1 : return false
418 1 : }
419 1 : pc.maybeExpandBounds(manifest.KeyRange(pc.cmp, startLevel.files.Iter()))
420 1 :
421 1 : // Determine the sstables in the output level which overlap with the input
422 1 : // sstables, and then expand those tables to a clean cut. No need to do
423 1 : // this for intra-L0 compactions; outputLevel.files is left empty for those.
424 1 : if startLevel.level != pc.outputLevel.level {
425 1 : pc.outputLevel.files = pc.version.Overlaps(pc.outputLevel.level, pc.cmp, pc.smallest.UserKey,
426 1 : pc.largest.UserKey, pc.largest.IsExclusiveSentinel())
427 1 : pc.outputLevel.files, isCompacting = expandToAtomicUnit(pc.cmp, pc.outputLevel.files,
428 1 : false /* disableIsCompacting */)
429 1 : if isCompacting {
430 1 : return false
431 1 : }
432 1 : pc.maybeExpandBounds(manifest.KeyRange(pc.cmp,
433 1 : startLevel.files.Iter(), pc.outputLevel.files.Iter()))
434 : }
435 :
436 : // Grow the sstables in startLevel.level as long as it doesn't affect the number
437 : // of sstables included from pc.outputLevel.level.
438 1 : if pc.lcf != nil && startLevel.level == 0 && pc.outputLevel.level != 0 {
439 1 : // Call the L0-specific compaction extension method. Similar logic as
440 1 : // pc.grow. Additional L0 files are optionally added to the compaction at
441 1 : // this step. Note that the bounds passed in are not the bounds of the
442 1 : // compaction, but rather the smallest and largest internal keys that
443 1 : // the compaction cannot include from L0 without pulling in more Lbase
444 1 : // files. Consider this example:
445 1 : //
446 1 : // L0: c-d e+f g-h
447 1 : // Lbase: a-b e+f i-j
448 1 : // a b c d e f g h i j
449 1 : //
450 1 : // The e-f files have already been chosen in the compaction. As pulling
451 1 : // in more LBase files is undesirable, the logic below will pass in
452 1 : // smallest = b and largest = i to ExtendL0ForBaseCompactionTo, which
453 1 : // will expand the compaction to include c-d and g-h from L0. The
454 1 : // bounds passed in are exclusive; the compaction cannot be expanded
455 1 : // to include files that "touch" it.
456 1 : smallestBaseKey := base.InvalidInternalKey
457 1 : largestBaseKey := base.InvalidInternalKey
458 1 : if pc.outputLevel.files.Empty() {
459 1 : baseIter := pc.version.Levels[pc.outputLevel.level].Iter()
460 1 : if sm := baseIter.SeekLT(pc.cmp, pc.smallest.UserKey); sm != nil {
461 1 : smallestBaseKey = sm.Largest
462 1 : }
463 1 : if la := baseIter.SeekGE(pc.cmp, pc.largest.UserKey); la != nil {
464 1 : largestBaseKey = la.Smallest
465 1 : }
466 1 : } else {
467 1 : // NB: We use Reslice to access the underlying level's files, but
468 1 : // we discard the returned slice. The pc.outputLevel.files slice
469 1 : // is not modified.
470 1 : _ = pc.outputLevel.files.Reslice(func(start, end *manifest.LevelIterator) {
471 1 : if sm := start.Prev(); sm != nil {
472 1 : smallestBaseKey = sm.Largest
473 1 : }
474 1 : if la := end.Next(); la != nil {
475 1 : largestBaseKey = la.Smallest
476 1 : }
477 : })
478 : }
479 1 : oldLcf := pc.lcf.Clone()
480 1 : if pc.version.L0Sublevels.ExtendL0ForBaseCompactionTo(smallestBaseKey, largestBaseKey, pc.lcf) {
481 1 : var newStartLevelFiles []*fileMetadata
482 1 : iter := pc.version.Levels[0].Iter()
483 1 : var sizeSum uint64
484 1 : for j, f := 0, iter.First(); f != nil; j, f = j+1, iter.Next() {
485 1 : if pc.lcf.FilesIncluded[f.L0Index] {
486 1 : newStartLevelFiles = append(newStartLevelFiles, f)
487 1 : sizeSum += f.Size
488 1 : }
489 : }
490 1 : if sizeSum+pc.outputLevel.files.SizeSum() < maxExpandedBytes {
491 1 : startLevel.files = manifest.NewLevelSliceSeqSorted(newStartLevelFiles)
492 1 : pc.smallest, pc.largest = manifest.KeyRange(pc.cmp,
493 1 : startLevel.files.Iter(), pc.outputLevel.files.Iter())
494 1 : } else {
495 1 : *pc.lcf = *oldLcf
496 1 : }
497 : }
498 1 : } else if pc.grow(pc.smallest, pc.largest, maxExpandedBytes, startLevel) {
499 1 : pc.maybeExpandBounds(manifest.KeyRange(pc.cmp,
500 1 : startLevel.files.Iter(), pc.outputLevel.files.Iter()))
501 1 : }
502 :
503 1 : if pc.startLevel.level == 0 {
504 1 : // We don't change the input files for the compaction beyond this point.
505 1 : pc.startLevel.l0SublevelInfo = generateSublevelInfo(pc.cmp, pc.startLevel.files)
506 1 : }
507 :
508 1 : return true
509 : }
510 :
511 : // grow grows the number of inputs at c.level without changing the number of
512 : // c.level+1 files in the compaction, and returns whether the inputs grew. sm
513 : // and la are the smallest and largest InternalKeys in all of the inputs.
514 : func (pc *pickedCompaction) grow(
515 : sm, la InternalKey, maxExpandedBytes uint64, startLevel *compactionLevel,
516 1 : ) bool {
517 1 : if pc.outputLevel.files.Empty() {
518 1 : return false
519 1 : }
520 1 : grow0 := pc.version.Overlaps(startLevel.level, pc.cmp, sm.UserKey,
521 1 : la.UserKey, la.IsExclusiveSentinel())
522 1 : grow0, isCompacting := expandToAtomicUnit(pc.cmp, grow0, false /* disableIsCompacting */)
523 1 : if isCompacting {
524 0 : return false
525 0 : }
526 1 : if grow0.Len() <= startLevel.files.Len() {
527 1 : return false
528 1 : }
529 1 : if grow0.SizeSum()+pc.outputLevel.files.SizeSum() >= maxExpandedBytes {
530 1 : return false
531 1 : }
532 : // We need to include the outputLevel iter because without it, in a multiLevel scenario,
533 : // sm1 and la1 could shift the output level keyspace when pc.outputLevel.files is set to grow1.
534 1 : sm1, la1 := manifest.KeyRange(pc.cmp, grow0.Iter(), pc.outputLevel.files.Iter())
535 1 : grow1 := pc.version.Overlaps(pc.outputLevel.level, pc.cmp, sm1.UserKey,
536 1 : la1.UserKey, la1.IsExclusiveSentinel())
537 1 : grow1, isCompacting = expandToAtomicUnit(pc.cmp, grow1, false /* disableIsCompacting */)
538 1 : if isCompacting {
539 0 : return false
540 0 : }
541 1 : if grow1.Len() != pc.outputLevel.files.Len() {
542 1 : return false
543 1 : }
544 1 : startLevel.files = grow0
545 1 : pc.outputLevel.files = grow1
546 1 : return true
547 : }
548 :
549 1 : func (pc *pickedCompaction) compactionSize() uint64 {
550 1 : var bytesToCompact uint64
551 1 : for i := range pc.inputs {
552 1 : bytesToCompact += pc.inputs[i].files.SizeSum()
553 1 : }
554 1 : return bytesToCompact
555 : }
556 :
557 : // setupMultiLevelCandidated returns true if it successfully added another level
558 : // to the compaction.
559 1 : func (pc *pickedCompaction) setupMultiLevelCandidate(opts *Options, diskAvailBytes uint64) bool {
560 1 : pc.inputs = append(pc.inputs, compactionLevel{level: pc.outputLevel.level + 1})
561 1 :
562 1 : // Recalibrate startLevel and outputLevel:
563 1 : // - startLevel and outputLevel pointers may be obsolete after appending to pc.inputs.
564 1 : // - push outputLevel to extraLevels and move the new level to outputLevel
565 1 : pc.startLevel = &pc.inputs[0]
566 1 : pc.extraLevels = []*compactionLevel{&pc.inputs[1]}
567 1 : pc.outputLevel = &pc.inputs[2]
568 1 : return pc.setupInputs(opts, diskAvailBytes, pc.extraLevels[len(pc.extraLevels)-1])
569 1 : }
570 :
571 : // expandToAtomicUnit expands the provided level slice within its level both
572 : // forwards and backwards to its "atomic compaction unit" boundaries, if
573 : // necessary.
574 : //
575 : // While picking compaction inputs, this is required to maintain the invariant
576 : // that the versions of keys at level+1 are older than the versions of keys at
577 : // level. Tables are added to the right of the current slice tables such that
578 : // the rightmost table has a "clean cut". A clean cut is either a change in
579 : // user keys, or when the largest key in the left sstable is a range tombstone
580 : // sentinel key (InternalKeyRangeDeleteSentinel).
581 : //
582 : // In addition to maintaining the seqnum invariant, expandToAtomicUnit is used
583 : // to provide clean boundaries for range tombstone truncation during
584 : // compaction. In order to achieve these clean boundaries, expandToAtomicUnit
585 : // needs to find a "clean cut" on the left edge of the compaction as well.
586 : // This is necessary in order for "atomic compaction units" to always be
587 : // compacted as a unit. Failure to do this leads to a subtle bug with
588 : // truncation of range tombstones to atomic compaction unit boundaries.
589 : // Consider the scenario:
590 : //
591 : // L3:
592 : // 12:[a#2,15-b#1,1]
593 : // 13:[b#0,15-d#72057594037927935,15]
594 : //
595 : // These sstables contain a range tombstone [a-d)#2 which spans the two
596 : // sstables. The two sstables need to always be kept together. Compacting
597 : // sstable 13 independently of sstable 12 would result in:
598 : //
599 : // L3:
600 : // 12:[a#2,15-b#1,1]
601 : // L4:
602 : // 14:[b#0,15-d#72057594037927935,15]
603 : //
604 : // This state is still ok, but when sstable 12 is next compacted, its range
605 : // tombstones will be truncated at "b" (the largest key in its atomic
606 : // compaction unit). In the scenario here, that could result in b#1 becoming
607 : // visible when it should be deleted.
608 : //
609 : // isCompacting is returned true for any atomic units that contain files that
610 : // have in-progress compactions, i.e. FileMetadata.Compacting == true. If
611 : // disableIsCompacting is true, isCompacting always returns false. This helps
612 : // avoid spurious races from being detected when this method is used outside
613 : // of compaction picking code.
614 : //
615 : // TODO(jackson): Compactions and flushes no longer split a user key between two
616 : // sstables. We could perform a migration, re-compacting any sstables with split
617 : // user keys, which would allow us to remove atomic compaction unit expansion
618 : // code.
619 : func expandToAtomicUnit(
620 : cmp Compare, inputs manifest.LevelSlice, disableIsCompacting bool,
621 1 : ) (slice manifest.LevelSlice, isCompacting bool) {
622 1 : // NB: Inputs for L0 can't be expanded and *version.Overlaps guarantees
623 1 : // that we get a 'clean cut.' For L0, Overlaps will return a slice without
624 1 : // access to the rest of the L0 files, so it's OK to try to reslice.
625 1 : if inputs.Empty() {
626 1 : // Nothing to expand.
627 1 : return inputs, false
628 1 : }
629 :
630 : // TODO(jackson): Update to avoid use of LevelIterator.Current(). The
631 : // Reslice interface will require some tweaking, because we currently rely
632 : // on Reslice having already positioned the LevelIterator appropriately.
633 :
634 1 : inputs = inputs.Reslice(func(start, end *manifest.LevelIterator) {
635 1 : iter := start.Clone()
636 1 : iter.Prev()
637 1 : for cur, prev := start.Current(), iter.Current(); prev != nil; cur, prev = start.Prev(), iter.Prev() {
638 1 : if cur.IsCompacting() {
639 1 : isCompacting = true
640 1 : }
641 1 : if cmp(prev.Largest.UserKey, cur.Smallest.UserKey) < 0 {
642 1 : break
643 : }
644 1 : if prev.Largest.IsExclusiveSentinel() {
645 1 : // The table prev has a largest key indicating that the user key
646 1 : // prev.largest.UserKey doesn't actually exist in the table.
647 1 : break
648 : }
649 : // prev.Largest.UserKey == cur.Smallest.UserKey, so we need to
650 : // include prev in the compaction.
651 : }
652 :
653 1 : iter = end.Clone()
654 1 : iter.Next()
655 1 : for cur, next := end.Current(), iter.Current(); next != nil; cur, next = end.Next(), iter.Next() {
656 1 : if cur.IsCompacting() {
657 1 : isCompacting = true
658 1 : }
659 1 : if cmp(cur.Largest.UserKey, next.Smallest.UserKey) < 0 {
660 1 : break
661 : }
662 1 : if cur.Largest.IsExclusiveSentinel() {
663 1 : // The table cur has a largest key indicating that the user key
664 1 : // cur.largest.UserKey doesn't actually exist in the table.
665 1 : break
666 : }
667 : // cur.Largest.UserKey == next.Smallest.UserKey, so we need to
668 : // include next in the compaction.
669 : }
670 : })
671 1 : inputIter := inputs.Iter()
672 1 : isCompacting = !disableIsCompacting &&
673 1 : (isCompacting || inputIter.First().IsCompacting() || inputIter.Last().IsCompacting())
674 1 : return inputs, isCompacting
675 : }
676 :
677 : func newCompactionPicker(
678 : v *version, opts *Options, inProgressCompactions []compactionInfo,
679 1 : ) compactionPicker {
680 1 : p := &compactionPickerByScore{
681 1 : opts: opts,
682 1 : vers: v,
683 1 : }
684 1 : p.initLevelMaxBytes(inProgressCompactions)
685 1 : return p
686 1 : }
687 :
688 : // Information about a candidate compaction level that has been identified by
689 : // the compaction picker.
690 : type candidateLevelInfo struct {
691 : // The compensatedScore of the level after adjusting according to the other
692 : // levels' sizes. For L0, the compensatedScoreRatio is equivalent to the
693 : // uncompensatedScoreRatio as we don't account for level size compensation in
694 : // L0.
695 : compensatedScoreRatio float64
696 : // The score of the level after accounting for level size compensation before
697 : // adjusting according to other levels' sizes. For L0, the compensatedScore
698 : // is equivalent to the uncompensatedScore as we don't account for level
699 : // size compensation in L0.
700 : compensatedScore float64
701 : // The score of the level to be compacted, calculated using uncompensated file
702 : // sizes and without any adjustments.
703 : uncompensatedScore float64
704 : // uncompensatedScoreRatio is the uncompensatedScore adjusted according to
705 : // the other levels' sizes.
706 : uncompensatedScoreRatio float64
707 : level int
708 : // The level to compact to.
709 : outputLevel int
710 : // The file in level that will be compacted. Additional files may be
711 : // picked by the compaction, and a pickedCompaction created for the
712 : // compaction.
713 : file manifest.LevelFile
714 : }
715 :
716 1 : func (c *candidateLevelInfo) shouldCompact() bool {
717 1 : return c.compensatedScoreRatio >= compactionScoreThreshold
718 1 : }
719 :
720 1 : func fileCompensation(f *fileMetadata) uint64 {
721 1 : return uint64(f.Stats.PointDeletionsBytesEstimate) + f.Stats.RangeDeletionsBytesEstimate
722 1 : }
723 :
724 : // compensatedSize returns f's file size, inflated according to compaction
725 : // priorities.
726 1 : func compensatedSize(f *fileMetadata) uint64 {
727 1 : // Add in the estimate of disk space that may be reclaimed by compacting the
728 1 : // file's tombstones.
729 1 : return f.Size + fileCompensation(f)
730 1 : }
731 :
732 : // compensatedSizeAnnotator implements manifest.Annotator, annotating B-Tree
733 : // nodes with the sum of the files' compensated sizes. Its annotation type is
734 : // a *uint64. Compensated sizes may change once a table's stats are loaded
735 : // asynchronously, so its values are marked as cacheable only if a file's
736 : // stats have been loaded.
737 : type compensatedSizeAnnotator struct {
738 : }
739 :
740 : var _ manifest.Annotator = compensatedSizeAnnotator{}
741 :
742 1 : func (a compensatedSizeAnnotator) Zero(dst interface{}) interface{} {
743 1 : if dst == nil {
744 1 : return new(uint64)
745 1 : }
746 1 : v := dst.(*uint64)
747 1 : *v = 0
748 1 : return v
749 : }
750 :
751 : func (a compensatedSizeAnnotator) Accumulate(
752 : f *fileMetadata, dst interface{},
753 1 : ) (v interface{}, cacheOK bool) {
754 1 : vptr := dst.(*uint64)
755 1 : *vptr = *vptr + compensatedSize(f)
756 1 : return vptr, f.StatsValid()
757 1 : }
758 :
759 1 : func (a compensatedSizeAnnotator) Merge(src interface{}, dst interface{}) interface{} {
760 1 : srcV := src.(*uint64)
761 1 : dstV := dst.(*uint64)
762 1 : *dstV = *dstV + *srcV
763 1 : return dstV
764 1 : }
765 :
766 : // totalCompensatedSize computes the compensated size over a file metadata
767 : // iterator. Note that this function is linear in the files available to the
768 : // iterator. Use the compensatedSizeAnnotator if querying the total
769 : // compensated size of a level.
770 1 : func totalCompensatedSize(iter manifest.LevelIterator) uint64 {
771 1 : var sz uint64
772 1 : for f := iter.First(); f != nil; f = iter.Next() {
773 1 : sz += compensatedSize(f)
774 1 : }
775 1 : return sz
776 : }
777 :
778 : // compactionPickerByScore holds the state and logic for picking a compaction. A
779 : // compaction picker is associated with a single version. A new compaction
780 : // picker is created and initialized every time a new version is installed.
781 : type compactionPickerByScore struct {
782 : opts *Options
783 : vers *version
784 : // The level to target for L0 compactions. Levels L1 to baseLevel must be
785 : // empty.
786 : baseLevel int
787 : // levelMaxBytes holds the dynamically adjusted max bytes setting for each
788 : // level.
789 : levelMaxBytes [numLevels]int64
790 : }
791 :
792 : var _ compactionPicker = &compactionPickerByScore{}
793 :
794 1 : func (p *compactionPickerByScore) getScores(inProgress []compactionInfo) [numLevels]float64 {
795 1 : var scores [numLevels]float64
796 1 : for _, info := range p.calculateLevelScores(inProgress) {
797 1 : scores[info.level] = info.compensatedScoreRatio
798 1 : }
799 1 : return scores
800 : }
801 :
802 1 : func (p *compactionPickerByScore) getBaseLevel() int {
803 1 : if p == nil {
804 0 : return 1
805 0 : }
806 1 : return p.baseLevel
807 : }
808 :
809 : // estimatedCompactionDebt estimates the number of bytes which need to be
810 : // compacted before the LSM tree becomes stable.
811 1 : func (p *compactionPickerByScore) estimatedCompactionDebt(l0ExtraSize uint64) uint64 {
812 1 : if p == nil {
813 0 : return 0
814 0 : }
815 :
816 : // We assume that all the bytes in L0 need to be compacted to Lbase. This is
817 : // unlike the RocksDB logic that figures out whether L0 needs compaction.
818 1 : bytesAddedToNextLevel := l0ExtraSize + p.vers.Levels[0].Size()
819 1 : lbaseSize := p.vers.Levels[p.baseLevel].Size()
820 1 :
821 1 : var compactionDebt uint64
822 1 : if bytesAddedToNextLevel > 0 && lbaseSize > 0 {
823 1 : // We only incur compaction debt if both L0 and Lbase contain data. If L0
824 1 : // is empty, no compaction is necessary. If Lbase is empty, a move-based
825 1 : // compaction from L0 would occur.
826 1 : compactionDebt += bytesAddedToNextLevel + lbaseSize
827 1 : }
828 :
829 : // loop invariant: At the beginning of the loop, bytesAddedToNextLevel is the
830 : // bytes added to `level` in the loop.
831 1 : for level := p.baseLevel; level < numLevels-1; level++ {
832 1 : levelSize := p.vers.Levels[level].Size() + bytesAddedToNextLevel
833 1 : nextLevelSize := p.vers.Levels[level+1].Size()
834 1 : if levelSize > uint64(p.levelMaxBytes[level]) {
835 1 : bytesAddedToNextLevel = levelSize - uint64(p.levelMaxBytes[level])
836 1 : if nextLevelSize > 0 {
837 1 : // We only incur compaction debt if the next level contains data. If the
838 1 : // next level is empty, a move-based compaction would be used.
839 1 : levelRatio := float64(nextLevelSize) / float64(levelSize)
840 1 : // The current level contributes bytesAddedToNextLevel to compactions.
841 1 : // The next level contributes levelRatio * bytesAddedToNextLevel.
842 1 : compactionDebt += uint64(float64(bytesAddedToNextLevel) * (levelRatio + 1))
843 1 : }
844 1 : } else {
845 1 : // We're not moving any bytes to the next level.
846 1 : bytesAddedToNextLevel = 0
847 1 : }
848 : }
849 1 : return compactionDebt
850 : }
851 :
852 1 : func (p *compactionPickerByScore) initLevelMaxBytes(inProgressCompactions []compactionInfo) {
853 1 : // The levelMaxBytes calculations here differ from RocksDB in two ways:
854 1 : //
855 1 : // 1. The use of dbSize vs maxLevelSize. RocksDB uses the size of the maximum
856 1 : // level in L1-L6, rather than determining the size of the bottom level
857 1 : // based on the total amount of data in the dB. The RocksDB calculation is
858 1 : // problematic if L0 contains a significant fraction of data, or if the
859 1 : // level sizes are roughly equal and thus there is a significant fraction
860 1 : // of data outside of the largest level.
861 1 : //
862 1 : // 2. Not adjusting the size of Lbase based on L0. RocksDB computes
863 1 : // baseBytesMax as the maximum of the configured LBaseMaxBytes and the
864 1 : // size of L0. This is problematic because baseBytesMax is used to compute
865 1 : // the max size of lower levels. A very large baseBytesMax will result in
866 1 : // an overly large value for the size of lower levels which will caused
867 1 : // those levels not to be compacted even when they should be
868 1 : // compacted. This often results in "inverted" LSM shapes where Ln is
869 1 : // larger than Ln+1.
870 1 :
871 1 : // Determine the first non-empty level and the total DB size.
872 1 : firstNonEmptyLevel := -1
873 1 : var dbSize uint64
874 1 : for level := 1; level < numLevels; level++ {
875 1 : if p.vers.Levels[level].Size() > 0 {
876 1 : if firstNonEmptyLevel == -1 {
877 1 : firstNonEmptyLevel = level
878 1 : }
879 1 : dbSize += p.vers.Levels[level].Size()
880 : }
881 : }
882 1 : for _, c := range inProgressCompactions {
883 1 : if c.outputLevel == 0 || c.outputLevel == -1 {
884 1 : continue
885 : }
886 1 : if c.inputs[0].level == 0 && (firstNonEmptyLevel == -1 || c.outputLevel < firstNonEmptyLevel) {
887 1 : firstNonEmptyLevel = c.outputLevel
888 1 : }
889 : }
890 :
891 : // Initialize the max-bytes setting for each level to "infinity" which will
892 : // disallow compaction for that level. We'll fill in the actual value below
893 : // for levels we want to allow compactions from.
894 1 : for level := 0; level < numLevels; level++ {
895 1 : p.levelMaxBytes[level] = math.MaxInt64
896 1 : }
897 :
898 1 : if dbSize == 0 {
899 1 : // No levels for L1 and up contain any data. Target L0 compactions for the
900 1 : // last level or to the level to which there is an ongoing L0 compaction.
901 1 : p.baseLevel = numLevels - 1
902 1 : if firstNonEmptyLevel >= 0 {
903 1 : p.baseLevel = firstNonEmptyLevel
904 1 : }
905 1 : return
906 : }
907 :
908 1 : dbSize += p.vers.Levels[0].Size()
909 1 : bottomLevelSize := dbSize - dbSize/uint64(p.opts.Experimental.LevelMultiplier)
910 1 :
911 1 : curLevelSize := bottomLevelSize
912 1 : for level := numLevels - 2; level >= firstNonEmptyLevel; level-- {
913 1 : curLevelSize = uint64(float64(curLevelSize) / float64(p.opts.Experimental.LevelMultiplier))
914 1 : }
915 :
916 : // Compute base level (where L0 data is compacted to).
917 1 : baseBytesMax := uint64(p.opts.LBaseMaxBytes)
918 1 : p.baseLevel = firstNonEmptyLevel
919 1 : for p.baseLevel > 1 && curLevelSize > baseBytesMax {
920 1 : p.baseLevel--
921 1 : curLevelSize = uint64(float64(curLevelSize) / float64(p.opts.Experimental.LevelMultiplier))
922 1 : }
923 :
924 1 : smoothedLevelMultiplier := 1.0
925 1 : if p.baseLevel < numLevels-1 {
926 1 : smoothedLevelMultiplier = math.Pow(
927 1 : float64(bottomLevelSize)/float64(baseBytesMax),
928 1 : 1.0/float64(numLevels-p.baseLevel-1))
929 1 : }
930 :
931 1 : levelSize := float64(baseBytesMax)
932 1 : for level := p.baseLevel; level < numLevels; level++ {
933 1 : if level > p.baseLevel && levelSize > 0 {
934 1 : levelSize *= smoothedLevelMultiplier
935 1 : }
936 : // Round the result since test cases use small target level sizes, which
937 : // can be impacted by floating-point imprecision + integer truncation.
938 1 : roundedLevelSize := math.Round(levelSize)
939 1 : if roundedLevelSize > float64(math.MaxInt64) {
940 0 : p.levelMaxBytes[level] = math.MaxInt64
941 1 : } else {
942 1 : p.levelMaxBytes[level] = int64(roundedLevelSize)
943 1 : }
944 : }
945 : }
946 :
947 : type levelSizeAdjust struct {
948 : incomingActualBytes uint64
949 : outgoingActualBytes uint64
950 : outgoingCompensatedBytes uint64
951 : }
952 :
953 1 : func (a levelSizeAdjust) compensated() uint64 {
954 1 : return a.incomingActualBytes - a.outgoingCompensatedBytes
955 1 : }
956 :
957 1 : func (a levelSizeAdjust) actual() uint64 {
958 1 : return a.incomingActualBytes - a.outgoingActualBytes
959 1 : }
960 :
961 1 : func calculateSizeAdjust(inProgressCompactions []compactionInfo) [numLevels]levelSizeAdjust {
962 1 : // Compute size adjustments for each level based on the in-progress
963 1 : // compactions. We sum the file sizes of all files leaving and entering each
964 1 : // level in in-progress compactions. For outgoing files, we also sum a
965 1 : // separate sum of 'compensated file sizes', which are inflated according
966 1 : // to deletion estimates.
967 1 : //
968 1 : // When we adjust a level's size according to these values during score
969 1 : // calculation, we subtract the compensated size of start level inputs to
970 1 : // account for the fact that score calculation uses compensated sizes.
971 1 : //
972 1 : // Since compensated file sizes may be compensated because they reclaim
973 1 : // space from the output level's files, we only add the real file size to
974 1 : // the output level.
975 1 : //
976 1 : // This is slightly different from RocksDB's behavior, which simply elides
977 1 : // compacting files from the level size calculation.
978 1 : var sizeAdjust [numLevels]levelSizeAdjust
979 1 : for i := range inProgressCompactions {
980 1 : c := &inProgressCompactions[i]
981 1 : // If this compaction's version edit has already been applied, there's
982 1 : // no need to adjust: The LSM we'll examine will already reflect the
983 1 : // new LSM state.
984 1 : if c.versionEditApplied {
985 1 : continue
986 : }
987 :
988 1 : for _, input := range c.inputs {
989 1 : actualSize := input.files.SizeSum()
990 1 : compensatedSize := totalCompensatedSize(input.files.Iter())
991 1 :
992 1 : if input.level != c.outputLevel {
993 1 : sizeAdjust[input.level].outgoingCompensatedBytes += compensatedSize
994 1 : sizeAdjust[input.level].outgoingActualBytes += actualSize
995 1 : if c.outputLevel != -1 {
996 1 : sizeAdjust[c.outputLevel].incomingActualBytes += actualSize
997 1 : }
998 : }
999 : }
1000 : }
1001 1 : return sizeAdjust
1002 : }
1003 :
1004 1 : func levelCompensatedSize(lm manifest.LevelMetadata) uint64 {
1005 1 : return *lm.Annotation(compensatedSizeAnnotator{}).(*uint64)
1006 1 : }
1007 :
1008 : func (p *compactionPickerByScore) calculateLevelScores(
1009 : inProgressCompactions []compactionInfo,
1010 1 : ) [numLevels]candidateLevelInfo {
1011 1 : var scores [numLevels]candidateLevelInfo
1012 1 : for i := range scores {
1013 1 : scores[i].level = i
1014 1 : scores[i].outputLevel = i + 1
1015 1 : }
1016 1 : l0UncompensatedScore := calculateL0UncompensatedScore(p.vers, p.opts, inProgressCompactions)
1017 1 : scores[0] = candidateLevelInfo{
1018 1 : outputLevel: p.baseLevel,
1019 1 : uncompensatedScore: l0UncompensatedScore,
1020 1 : compensatedScore: l0UncompensatedScore, /* No level size compensation for L0 */
1021 1 : }
1022 1 : sizeAdjust := calculateSizeAdjust(inProgressCompactions)
1023 1 : for level := 1; level < numLevels; level++ {
1024 1 : compensatedLevelSize := levelCompensatedSize(p.vers.Levels[level]) + sizeAdjust[level].compensated()
1025 1 : scores[level].compensatedScore = float64(compensatedLevelSize) / float64(p.levelMaxBytes[level])
1026 1 : scores[level].uncompensatedScore = float64(p.vers.Levels[level].Size()+sizeAdjust[level].actual()) / float64(p.levelMaxBytes[level])
1027 1 : }
1028 :
1029 : // Adjust each level's {compensated, uncompensated}Score by the uncompensatedScore
1030 : // of the next level to get a {compensated, uncompensated}ScoreRatio. If the
1031 : // next level has a high uncompensatedScore, and is thus a priority for compaction,
1032 : // this reduces the priority for compacting the current level. If the next level
1033 : // has a low uncompensatedScore (i.e. it is below its target size), this increases
1034 : // the priority for compacting the current level.
1035 : //
1036 : // The effect of this adjustment is to help prioritize compactions in lower
1037 : // levels. The following example shows the compensatedScoreRatio and the
1038 : // compensatedScore. In this scenario, L0 has 68 sublevels. L3 (a.k.a. Lbase)
1039 : // is significantly above its target size. The original score prioritizes
1040 : // compactions from those two levels, but doing so ends up causing a future
1041 : // problem: data piles up in the higher levels, starving L5->L6 compactions,
1042 : // and to a lesser degree starving L4->L5 compactions.
1043 : //
1044 : // Note that in the example shown there is no level size compensation so the
1045 : // compensatedScore and the uncompensatedScore is the same for each level.
1046 : //
1047 : // compensatedScoreRatio compensatedScore uncompensatedScore size max-size
1048 : // L0 3.2 68.0 68.0 2.2 G -
1049 : // L3 3.2 21.1 21.1 1.3 G 64 M
1050 : // L4 3.4 6.7 6.7 3.1 G 467 M
1051 : // L5 3.4 2.0 2.0 6.6 G 3.3 G
1052 : // L6 0.6 0.6 0.6 14 G 24 G
1053 1 : var prevLevel int
1054 1 : for level := p.baseLevel; level < numLevels; level++ {
1055 1 : // The compensated scores, and uncompensated scores will be turned into
1056 1 : // ratios as they're adjusted according to other levels' sizes.
1057 1 : scores[prevLevel].compensatedScoreRatio = scores[prevLevel].compensatedScore
1058 1 : scores[prevLevel].uncompensatedScoreRatio = scores[prevLevel].uncompensatedScore
1059 1 :
1060 1 : // Avoid absurdly large scores by placing a floor on the score that we'll
1061 1 : // adjust a level by. The value of 0.01 was chosen somewhat arbitrarily.
1062 1 : const minScore = 0.01
1063 1 : if scores[prevLevel].compensatedScoreRatio >= compactionScoreThreshold {
1064 1 : if scores[level].uncompensatedScore >= minScore {
1065 1 : scores[prevLevel].compensatedScoreRatio /= scores[level].uncompensatedScore
1066 1 : } else {
1067 1 : scores[prevLevel].compensatedScoreRatio /= minScore
1068 1 : }
1069 : }
1070 1 : if scores[prevLevel].uncompensatedScoreRatio >= compactionScoreThreshold {
1071 1 : if scores[level].uncompensatedScore >= minScore {
1072 1 : scores[prevLevel].uncompensatedScoreRatio /= scores[level].uncompensatedScore
1073 1 : } else {
1074 1 : scores[prevLevel].uncompensatedScoreRatio /= minScore
1075 1 : }
1076 : }
1077 1 : prevLevel = level
1078 : }
1079 : // Set the score ratios for the lowest level.
1080 : // INVARIANT: prevLevel == numLevels-1
1081 1 : scores[prevLevel].compensatedScoreRatio = scores[prevLevel].compensatedScore
1082 1 : scores[prevLevel].uncompensatedScoreRatio = scores[prevLevel].uncompensatedScore
1083 1 :
1084 1 : sort.Sort(sortCompactionLevelsByPriority(scores[:]))
1085 1 : return scores
1086 : }
1087 :
1088 : // calculateL0UncompensatedScore calculates a float score representing the
1089 : // relative priority of compacting L0. Level L0 is special in that files within
1090 : // L0 may overlap one another, so a different set of heuristics that take into
1091 : // account read amplification apply.
1092 : func calculateL0UncompensatedScore(
1093 : vers *version, opts *Options, inProgressCompactions []compactionInfo,
1094 1 : ) float64 {
1095 1 : // Use the sublevel count to calculate the score. The base vs intra-L0
1096 1 : // compaction determination happens in pickAuto, not here.
1097 1 : score := float64(2*vers.L0Sublevels.MaxDepthAfterOngoingCompactions()) /
1098 1 : float64(opts.L0CompactionThreshold)
1099 1 :
1100 1 : // Also calculate a score based on the file count but use it only if it
1101 1 : // produces a higher score than the sublevel-based one. This heuristic is
1102 1 : // designed to accommodate cases where L0 is accumulating non-overlapping
1103 1 : // files in L0. Letting too many non-overlapping files accumulate in few
1104 1 : // sublevels is undesirable, because:
1105 1 : // 1) we can produce a massive backlog to compact once files do overlap.
1106 1 : // 2) constructing L0 sublevels has a runtime that grows superlinearly with
1107 1 : // the number of files in L0 and must be done while holding D.mu.
1108 1 : noncompactingFiles := vers.Levels[0].Len()
1109 1 : for _, c := range inProgressCompactions {
1110 1 : for _, cl := range c.inputs {
1111 1 : if cl.level == 0 {
1112 1 : noncompactingFiles -= cl.files.Len()
1113 1 : }
1114 : }
1115 : }
1116 1 : fileScore := float64(noncompactingFiles) / float64(opts.L0CompactionFileThreshold)
1117 1 : if score < fileScore {
1118 1 : score = fileScore
1119 1 : }
1120 1 : return score
1121 : }
1122 :
1123 : // pickCompactionSeedFile picks a file from `level` in the `vers` to build a
1124 : // compaction around. Currently, this function implements a heuristic similar to
1125 : // RocksDB's kMinOverlappingRatio, seeking to minimize write amplification. This
1126 : // function is linear with respect to the number of files in `level` and
1127 : // `outputLevel`.
1128 : func pickCompactionSeedFile(
1129 : vers *version, opts *Options, level, outputLevel int, earliestSnapshotSeqNum uint64,
1130 1 : ) (manifest.LevelFile, bool) {
1131 1 : // Select the file within the level to compact. We want to minimize write
1132 1 : // amplification, but also ensure that deletes are propagated to the
1133 1 : // bottom level in a timely fashion so as to reclaim disk space. A table's
1134 1 : // smallest sequence number provides a measure of its age. The ratio of
1135 1 : // overlapping-bytes / table-size gives an indication of write
1136 1 : // amplification (a smaller ratio is preferrable).
1137 1 : //
1138 1 : // The current heuristic is based off the the RocksDB kMinOverlappingRatio
1139 1 : // heuristic. It chooses the file with the minimum overlapping ratio with
1140 1 : // the target level, which minimizes write amplification.
1141 1 : //
1142 1 : // It uses a "compensated size" for the denominator, which is the file
1143 1 : // size but artificially inflated by an estimate of the space that may be
1144 1 : // reclaimed through compaction. Currently, we only compensate for range
1145 1 : // deletions and only with a rough estimate of the reclaimable bytes. This
1146 1 : // differs from RocksDB which only compensates for point tombstones and
1147 1 : // only if they exceed the number of non-deletion entries in table.
1148 1 : //
1149 1 : // TODO(peter): For concurrent compactions, we may want to try harder to
1150 1 : // pick a seed file whose resulting compaction bounds do not overlap with
1151 1 : // an in-progress compaction.
1152 1 :
1153 1 : cmp := opts.Comparer.Compare
1154 1 : startIter := vers.Levels[level].Iter()
1155 1 : outputIter := vers.Levels[outputLevel].Iter()
1156 1 :
1157 1 : var file manifest.LevelFile
1158 1 : smallestRatio := uint64(math.MaxUint64)
1159 1 :
1160 1 : outputFile := outputIter.First()
1161 1 :
1162 1 : for f := startIter.First(); f != nil; f = startIter.Next() {
1163 1 : var overlappingBytes uint64
1164 1 : compacting := f.IsCompacting()
1165 1 : if compacting {
1166 1 : // Move on if this file is already being compacted. We'll likely
1167 1 : // still need to move past the overlapping output files regardless,
1168 1 : // but in cases where all start-level files are compacting we won't.
1169 1 : continue
1170 : }
1171 :
1172 : // Trim any output-level files smaller than f.
1173 1 : for outputFile != nil && sstableKeyCompare(cmp, outputFile.Largest, f.Smallest) < 0 {
1174 1 : outputFile = outputIter.Next()
1175 1 : }
1176 :
1177 1 : for outputFile != nil && sstableKeyCompare(cmp, outputFile.Smallest, f.Largest) <= 0 && !compacting {
1178 1 : overlappingBytes += outputFile.Size
1179 1 : compacting = compacting || outputFile.IsCompacting()
1180 1 :
1181 1 : // For files in the bottommost level of the LSM, the
1182 1 : // Stats.RangeDeletionsBytesEstimate field is set to the estimate
1183 1 : // of bytes /within/ the file itself that may be dropped by
1184 1 : // recompacting the file. These bytes from obsolete keys would not
1185 1 : // need to be rewritten if we compacted `f` into `outputFile`, so
1186 1 : // they don't contribute to write amplification. Subtracting them
1187 1 : // out of the overlapping bytes helps prioritize these compactions
1188 1 : // that are cheaper than their file sizes suggest.
1189 1 : if outputLevel == numLevels-1 && outputFile.LargestSeqNum < earliestSnapshotSeqNum {
1190 1 : overlappingBytes -= outputFile.Stats.RangeDeletionsBytesEstimate
1191 1 : }
1192 :
1193 : // If the file in the next level extends beyond f's largest key,
1194 : // break out and don't advance outputIter because f's successor
1195 : // might also overlap.
1196 : //
1197 : // Note, we stop as soon as we encounter an output-level file with a
1198 : // largest key beyond the input-level file's largest bound. We
1199 : // perform a simple user key comparison here using sstableKeyCompare
1200 : // which handles the potential for exclusive largest key bounds.
1201 : // There's some subtlety when the bounds are equal (eg, equal and
1202 : // inclusive, or equal and exclusive). Current Pebble doesn't split
1203 : // user keys across sstables within a level (and in format versions
1204 : // FormatSplitUserKeysMarkedCompacted and later we guarantee no
1205 : // split user keys exist within the entire LSM). In that case, we're
1206 : // assured that neither the input level nor the output level's next
1207 : // file shares the same user key, so compaction expansion will not
1208 : // include them in any compaction compacting `f`.
1209 : //
1210 : // NB: If we /did/ allow split user keys, or we're running on an
1211 : // old database with an earlier format major version where there are
1212 : // existing split user keys, this logic would be incorrect. Consider
1213 : // L1: [a#120,a#100] [a#80,a#60]
1214 : // L2: [a#55,a#45] [a#35,a#25] [a#15,a#5]
1215 : // While considering the first file in L1, [a#120,a#100], we'd skip
1216 : // past all of the files in L2. When considering the second file in
1217 : // L1, we'd improperly conclude that the second file overlaps
1218 : // nothing in the second level and is cheap to compact, when in
1219 : // reality we'd need to expand the compaction to include all 5
1220 : // files.
1221 1 : if sstableKeyCompare(cmp, outputFile.Largest, f.Largest) > 0 {
1222 1 : break
1223 : }
1224 1 : outputFile = outputIter.Next()
1225 : }
1226 :
1227 : // If the input level file or one of the overlapping files is
1228 : // compacting, we're not going to be able to compact this file
1229 : // anyways, so skip it.
1230 1 : if compacting {
1231 1 : continue
1232 : }
1233 :
1234 1 : compSz := compensatedSize(f)
1235 1 : scaledRatio := overlappingBytes * 1024 / compSz
1236 1 : if scaledRatio < smallestRatio {
1237 1 : smallestRatio = scaledRatio
1238 1 : file = startIter.Take()
1239 1 : }
1240 : }
1241 1 : return file, file.FileMetadata != nil
1242 : }
1243 :
1244 : // pickAuto picks the best compaction, if any.
1245 : //
1246 : // On each call, pickAuto computes per-level size adjustments based on
1247 : // in-progress compactions, and computes a per-level score. The levels are
1248 : // iterated over in decreasing score order trying to find a valid compaction
1249 : // anchored at that level.
1250 : //
1251 : // If a score-based compaction cannot be found, pickAuto falls back to looking
1252 : // for an elision-only compaction to remove obsolete keys.
1253 1 : func (p *compactionPickerByScore) pickAuto(env compactionEnv) (pc *pickedCompaction) {
1254 1 : // Compaction concurrency is controlled by L0 read-amp. We allow one
1255 1 : // additional compaction per L0CompactionConcurrency sublevels, as well as
1256 1 : // one additional compaction per CompactionDebtConcurrency bytes of
1257 1 : // compaction debt. Compaction concurrency is tied to L0 sublevels as that
1258 1 : // signal is independent of the database size. We tack on the compaction
1259 1 : // debt as a second signal to prevent compaction concurrency from dropping
1260 1 : // significantly right after a base compaction finishes, and before those
1261 1 : // bytes have been compacted further down the LSM.
1262 1 : if n := len(env.inProgressCompactions); n > 0 {
1263 1 : l0ReadAmp := p.vers.L0Sublevels.MaxDepthAfterOngoingCompactions()
1264 1 : compactionDebt := p.estimatedCompactionDebt(0)
1265 1 : ccSignal1 := n * p.opts.Experimental.L0CompactionConcurrency
1266 1 : ccSignal2 := uint64(n) * p.opts.Experimental.CompactionDebtConcurrency
1267 1 : if l0ReadAmp < ccSignal1 && compactionDebt < ccSignal2 {
1268 1 : return nil
1269 1 : }
1270 : }
1271 :
1272 1 : scores := p.calculateLevelScores(env.inProgressCompactions)
1273 1 :
1274 1 : // TODO(bananabrick): Either remove, or change this into an event sent to the
1275 1 : // EventListener.
1276 1 : logCompaction := func(pc *pickedCompaction) {
1277 0 : var buf bytes.Buffer
1278 0 : for i := 0; i < numLevels; i++ {
1279 0 : if i != 0 && i < p.baseLevel {
1280 0 : continue
1281 : }
1282 :
1283 0 : var info *candidateLevelInfo
1284 0 : for j := range scores {
1285 0 : if scores[j].level == i {
1286 0 : info = &scores[j]
1287 0 : break
1288 : }
1289 : }
1290 :
1291 0 : marker := " "
1292 0 : if pc.startLevel.level == info.level {
1293 0 : marker = "*"
1294 0 : }
1295 0 : fmt.Fprintf(&buf, " %sL%d: %5.1f %5.1f %5.1f %5.1f %8s %8s",
1296 0 : marker, info.level, info.compensatedScoreRatio, info.compensatedScore,
1297 0 : info.uncompensatedScoreRatio, info.uncompensatedScore,
1298 0 : humanize.Bytes.Int64(int64(totalCompensatedSize(
1299 0 : p.vers.Levels[info.level].Iter(),
1300 0 : ))),
1301 0 : humanize.Bytes.Int64(p.levelMaxBytes[info.level]),
1302 0 : )
1303 0 :
1304 0 : count := 0
1305 0 : for i := range env.inProgressCompactions {
1306 0 : c := &env.inProgressCompactions[i]
1307 0 : if c.inputs[0].level != info.level {
1308 0 : continue
1309 : }
1310 0 : count++
1311 0 : if count == 1 {
1312 0 : fmt.Fprintf(&buf, " [")
1313 0 : } else {
1314 0 : fmt.Fprintf(&buf, " ")
1315 0 : }
1316 0 : fmt.Fprintf(&buf, "L%d->L%d", c.inputs[0].level, c.outputLevel)
1317 : }
1318 0 : if count > 0 {
1319 0 : fmt.Fprintf(&buf, "]")
1320 0 : }
1321 0 : fmt.Fprintf(&buf, "\n")
1322 : }
1323 0 : p.opts.Logger.Infof("pickAuto: L%d->L%d\n%s",
1324 0 : pc.startLevel.level, pc.outputLevel.level, buf.String())
1325 : }
1326 :
1327 : // Check for a score-based compaction. candidateLevelInfos are first sorted
1328 : // by whether they should be compacted, so if we find a level which shouldn't
1329 : // be compacted, we can break early.
1330 1 : for i := range scores {
1331 1 : info := &scores[i]
1332 1 : if !info.shouldCompact() {
1333 1 : break
1334 : }
1335 1 : if info.level == numLevels-1 {
1336 1 : continue
1337 : }
1338 :
1339 1 : if info.level == 0 {
1340 1 : pc = pickL0(env, p.opts, p.vers, p.baseLevel)
1341 1 : // Fail-safe to protect against compacting the same sstable
1342 1 : // concurrently.
1343 1 : if pc != nil && !inputRangeAlreadyCompacting(env, pc) {
1344 1 : p.addScoresToPickedCompactionMetrics(pc, scores)
1345 1 : pc.score = info.compensatedScoreRatio
1346 1 : // TODO(bananabrick): Create an EventListener for logCompaction.
1347 1 : if false {
1348 0 : logCompaction(pc)
1349 0 : }
1350 1 : return pc
1351 : }
1352 1 : continue
1353 : }
1354 :
1355 : // info.level > 0
1356 1 : var ok bool
1357 1 : info.file, ok = pickCompactionSeedFile(p.vers, p.opts, info.level, info.outputLevel, env.earliestSnapshotSeqNum)
1358 1 : if !ok {
1359 1 : continue
1360 : }
1361 :
1362 1 : pc := pickAutoLPositive(env, p.opts, p.vers, *info, p.baseLevel, p.levelMaxBytes)
1363 1 : // Fail-safe to protect against compacting the same sstable concurrently.
1364 1 : if pc != nil && !inputRangeAlreadyCompacting(env, pc) {
1365 1 : p.addScoresToPickedCompactionMetrics(pc, scores)
1366 1 : pc.score = info.compensatedScoreRatio
1367 1 : // TODO(bananabrick): Create an EventListener for logCompaction.
1368 1 : if false {
1369 0 : logCompaction(pc)
1370 0 : }
1371 1 : return pc
1372 : }
1373 : }
1374 :
1375 : // Check for L6 files with tombstones that may be elided. These files may
1376 : // exist if a snapshot prevented the elision of a tombstone or because of
1377 : // a move compaction. These are low-priority compactions because they
1378 : // don't help us keep up with writes, just reclaim disk space.
1379 1 : if pc := p.pickElisionOnlyCompaction(env); pc != nil {
1380 1 : return pc
1381 1 : }
1382 :
1383 1 : if pc := p.pickReadTriggeredCompaction(env); pc != nil {
1384 1 : return pc
1385 1 : }
1386 :
1387 : // NB: This should only be run if a read compaction wasn't
1388 : // scheduled.
1389 : //
1390 : // We won't be scheduling a read compaction right now, and in
1391 : // read heavy workloads, compactions won't be scheduled frequently
1392 : // because flushes aren't frequent. So we need to signal to the
1393 : // iterator to schedule a compaction when it adds compactions to
1394 : // the read compaction queue.
1395 : //
1396 : // We need the nil check here because without it, we have some
1397 : // tests which don't set that variable fail. Since there's a
1398 : // chance that one of those tests wouldn't want extra compactions
1399 : // to be scheduled, I added this check here, instead of
1400 : // setting rescheduleReadCompaction in those tests.
1401 1 : if env.readCompactionEnv.rescheduleReadCompaction != nil {
1402 1 : *env.readCompactionEnv.rescheduleReadCompaction = true
1403 1 : }
1404 :
1405 : // At the lowest possible compaction-picking priority, look for files marked
1406 : // for compaction. Pebble will mark files for compaction if they have atomic
1407 : // compaction units that span multiple files. While current Pebble code does
1408 : // not construct such sstables, RocksDB and earlier versions of Pebble may
1409 : // have created them. These split user keys form sets of files that must be
1410 : // compacted together for correctness (referred to as "atomic compaction
1411 : // units" within the code). Rewrite them in-place.
1412 : //
1413 : // It's also possible that a file may have been marked for compaction by
1414 : // even earlier versions of Pebble code, since FileMetadata's
1415 : // MarkedForCompaction field is persisted in the manifest. That's okay. We
1416 : // previously would've ignored the designation, whereas now we'll re-compact
1417 : // the file in place.
1418 1 : if p.vers.Stats.MarkedForCompaction > 0 {
1419 1 : if pc := p.pickRewriteCompaction(env); pc != nil {
1420 1 : return pc
1421 1 : }
1422 : }
1423 :
1424 1 : return nil
1425 : }
1426 :
1427 : func (p *compactionPickerByScore) addScoresToPickedCompactionMetrics(
1428 : pc *pickedCompaction, candInfo [numLevels]candidateLevelInfo,
1429 1 : ) {
1430 1 :
1431 1 : // candInfo is sorted by score, not by compaction level.
1432 1 : infoByLevel := [numLevels]candidateLevelInfo{}
1433 1 : for i := range candInfo {
1434 1 : level := candInfo[i].level
1435 1 : infoByLevel[level] = candInfo[i]
1436 1 : }
1437 : // Gather the compaction scores for the levels participating in the compaction.
1438 1 : pc.pickerMetrics.scores = make([]float64, len(pc.inputs))
1439 1 : inputIdx := 0
1440 1 : for i := range infoByLevel {
1441 1 : if pc.inputs[inputIdx].level == infoByLevel[i].level {
1442 1 : pc.pickerMetrics.scores[inputIdx] = infoByLevel[i].compensatedScoreRatio
1443 1 : inputIdx++
1444 1 : }
1445 1 : if inputIdx == len(pc.inputs) {
1446 1 : break
1447 : }
1448 : }
1449 : }
1450 :
1451 : // elisionOnlyAnnotator implements the manifest.Annotator interface,
1452 : // annotating B-Tree nodes with the *fileMetadata of a file meeting the
1453 : // obsolete keys criteria for an elision-only compaction within the subtree.
1454 : // If multiple files meet the criteria, it chooses whichever file has the
1455 : // lowest LargestSeqNum. The lowest LargestSeqNum file will be the first
1456 : // eligible for an elision-only compaction once snapshots less than or equal
1457 : // to its LargestSeqNum are closed.
1458 : type elisionOnlyAnnotator struct{}
1459 :
1460 : var _ manifest.Annotator = elisionOnlyAnnotator{}
1461 :
1462 1 : func (a elisionOnlyAnnotator) Zero(interface{}) interface{} {
1463 1 : return nil
1464 1 : }
1465 :
1466 1 : func (a elisionOnlyAnnotator) Accumulate(f *fileMetadata, dst interface{}) (interface{}, bool) {
1467 1 : if f.IsCompacting() {
1468 1 : return dst, true
1469 1 : }
1470 1 : if !f.StatsValid() {
1471 1 : return dst, false
1472 1 : }
1473 : // Bottommost files are large and not worthwhile to compact just
1474 : // to remove a few tombstones. Consider a file ineligible if its
1475 : // own range deletions delete less than 10% of its data and its
1476 : // deletion tombstones make up less than 10% of its entries.
1477 : //
1478 : // TODO(jackson): This does not account for duplicate user keys
1479 : // which may be collapsed. Ideally, we would have 'obsolete keys'
1480 : // statistics that would include tombstones, the keys that are
1481 : // dropped by tombstones and duplicated user keys. See #847.
1482 : //
1483 : // Note that tables that contain exclusively range keys (i.e. no point keys,
1484 : // `NumEntries` and `RangeDeletionsBytesEstimate` are both zero) are excluded
1485 : // from elision-only compactions.
1486 : // TODO(travers): Consider an alternative heuristic for elision of range-keys.
1487 1 : if f.Stats.RangeDeletionsBytesEstimate*10 < f.Size &&
1488 1 : f.Stats.NumDeletions*10 <= f.Stats.NumEntries {
1489 1 : return dst, true
1490 1 : }
1491 1 : if dst == nil {
1492 1 : return f, true
1493 1 : } else if dstV := dst.(*fileMetadata); dstV.LargestSeqNum > f.LargestSeqNum {
1494 0 : return f, true
1495 0 : }
1496 0 : return dst, true
1497 : }
1498 :
1499 1 : func (a elisionOnlyAnnotator) Merge(v interface{}, accum interface{}) interface{} {
1500 1 : if v == nil {
1501 1 : return accum
1502 1 : }
1503 : // If we haven't accumulated an eligible file yet, or f's LargestSeqNum is
1504 : // less than the accumulated file's, use f.
1505 0 : if accum == nil {
1506 0 : return v
1507 0 : }
1508 0 : f := v.(*fileMetadata)
1509 0 : accumV := accum.(*fileMetadata)
1510 0 : if accumV == nil || accumV.LargestSeqNum > f.LargestSeqNum {
1511 0 : return f
1512 0 : }
1513 0 : return accumV
1514 : }
1515 :
1516 : // markedForCompactionAnnotator implements the manifest.Annotator interface,
1517 : // annotating B-Tree nodes with the *fileMetadata of a file that is marked for
1518 : // compaction within the subtree. If multiple files meet the criteria, it
1519 : // chooses whichever file has the lowest LargestSeqNum.
1520 : type markedForCompactionAnnotator struct{}
1521 :
1522 : var _ manifest.Annotator = markedForCompactionAnnotator{}
1523 :
1524 1 : func (a markedForCompactionAnnotator) Zero(interface{}) interface{} {
1525 1 : return nil
1526 1 : }
1527 :
1528 : func (a markedForCompactionAnnotator) Accumulate(
1529 : f *fileMetadata, dst interface{},
1530 1 : ) (interface{}, bool) {
1531 1 : if !f.MarkedForCompaction {
1532 1 : // Not marked for compaction; return dst.
1533 1 : return dst, true
1534 1 : }
1535 1 : return markedMergeHelper(f, dst)
1536 : }
1537 :
1538 0 : func (a markedForCompactionAnnotator) Merge(v interface{}, accum interface{}) interface{} {
1539 0 : if v == nil {
1540 0 : return accum
1541 0 : }
1542 0 : accum, _ = markedMergeHelper(v.(*fileMetadata), accum)
1543 0 : return accum
1544 : }
1545 :
1546 : // REQUIRES: f is non-nil, and f.MarkedForCompaction=true.
1547 1 : func markedMergeHelper(f *fileMetadata, dst interface{}) (interface{}, bool) {
1548 1 : if dst == nil {
1549 1 : return f, true
1550 1 : } else if dstV := dst.(*fileMetadata); dstV.LargestSeqNum > f.LargestSeqNum {
1551 0 : return f, true
1552 0 : }
1553 0 : return dst, true
1554 : }
1555 :
1556 : // pickElisionOnlyCompaction looks for compactions of sstables in the
1557 : // bottommost level containing obsolete records that may now be dropped.
1558 : func (p *compactionPickerByScore) pickElisionOnlyCompaction(
1559 : env compactionEnv,
1560 1 : ) (pc *pickedCompaction) {
1561 1 : if p.opts.private.disableElisionOnlyCompactions {
1562 1 : return nil
1563 1 : }
1564 1 : v := p.vers.Levels[numLevels-1].Annotation(elisionOnlyAnnotator{})
1565 1 : if v == nil {
1566 1 : return nil
1567 1 : }
1568 1 : candidate := v.(*fileMetadata)
1569 1 : if candidate.IsCompacting() || candidate.LargestSeqNum >= env.earliestSnapshotSeqNum {
1570 1 : return nil
1571 1 : }
1572 1 : lf := p.vers.Levels[numLevels-1].Find(p.opts.Comparer.Compare, candidate)
1573 1 : if lf == nil {
1574 0 : panic(fmt.Sprintf("file %s not found in level %d as expected", candidate.FileNum, numLevels-1))
1575 : }
1576 :
1577 : // Construct a picked compaction of the elision candidate's atomic
1578 : // compaction unit.
1579 1 : pc = newPickedCompaction(p.opts, p.vers, numLevels-1, numLevels-1, p.baseLevel)
1580 1 : pc.kind = compactionKindElisionOnly
1581 1 : var isCompacting bool
1582 1 : pc.startLevel.files, isCompacting = expandToAtomicUnit(p.opts.Comparer.Compare, lf.Slice(), false /* disableIsCompacting */)
1583 1 : if isCompacting {
1584 0 : return nil
1585 0 : }
1586 1 : pc.smallest, pc.largest = manifest.KeyRange(pc.cmp, pc.startLevel.files.Iter())
1587 1 : // Fail-safe to protect against compacting the same sstable concurrently.
1588 1 : if !inputRangeAlreadyCompacting(env, pc) {
1589 1 : return pc
1590 1 : }
1591 0 : return nil
1592 : }
1593 :
1594 : // pickRewriteCompaction attempts to construct a compaction that
1595 : // rewrites a file marked for compaction. pickRewriteCompaction will
1596 : // pull in adjacent files in the file's atomic compaction unit if
1597 : // necessary. A rewrite compaction outputs files to the same level as
1598 : // the input level.
1599 1 : func (p *compactionPickerByScore) pickRewriteCompaction(env compactionEnv) (pc *pickedCompaction) {
1600 1 : for l := numLevels - 1; l >= 0; l-- {
1601 1 : v := p.vers.Levels[l].Annotation(markedForCompactionAnnotator{})
1602 1 : if v == nil {
1603 1 : // Try the next level.
1604 1 : continue
1605 : }
1606 1 : candidate := v.(*fileMetadata)
1607 1 : if candidate.IsCompacting() {
1608 0 : // Try the next level.
1609 0 : continue
1610 : }
1611 1 : lf := p.vers.Levels[l].Find(p.opts.Comparer.Compare, candidate)
1612 1 : if lf == nil {
1613 0 : panic(fmt.Sprintf("file %s not found in level %d as expected", candidate.FileNum, numLevels-1))
1614 : }
1615 :
1616 1 : inputs := lf.Slice()
1617 1 : // L0 files generated by a flush have never been split such that
1618 1 : // adjacent files can contain the same user key. So we do not need to
1619 1 : // rewrite an atomic compaction unit for L0. Note that there is nothing
1620 1 : // preventing two different flushes from producing files that are
1621 1 : // non-overlapping from an InternalKey perspective, but span the same
1622 1 : // user key. However, such files cannot be in the same L0 sublevel,
1623 1 : // since each sublevel requires non-overlapping user keys (unlike other
1624 1 : // levels).
1625 1 : if l > 0 {
1626 1 : // Find this file's atomic compaction unit. This is only relevant
1627 1 : // for levels L1+.
1628 1 : var isCompacting bool
1629 1 : inputs, isCompacting = expandToAtomicUnit(
1630 1 : p.opts.Comparer.Compare,
1631 1 : inputs,
1632 1 : false, /* disableIsCompacting */
1633 1 : )
1634 1 : if isCompacting {
1635 0 : // Try the next level.
1636 0 : continue
1637 : }
1638 : }
1639 :
1640 1 : pc = newPickedCompaction(p.opts, p.vers, l, l, p.baseLevel)
1641 1 : pc.outputLevel.level = l
1642 1 : pc.kind = compactionKindRewrite
1643 1 : pc.startLevel.files = inputs
1644 1 : pc.smallest, pc.largest = manifest.KeyRange(pc.cmp, pc.startLevel.files.Iter())
1645 1 :
1646 1 : // Fail-safe to protect against compacting the same sstable concurrently.
1647 1 : if !inputRangeAlreadyCompacting(env, pc) {
1648 1 : if pc.startLevel.level == 0 {
1649 1 : pc.startLevel.l0SublevelInfo = generateSublevelInfo(pc.cmp, pc.startLevel.files)
1650 1 : }
1651 1 : return pc
1652 : }
1653 : }
1654 0 : return nil
1655 : }
1656 :
1657 : // pickAutoLPositive picks an automatic compaction for the candidate
1658 : // file in a positive-numbered level. This function must not be used for
1659 : // L0.
1660 : func pickAutoLPositive(
1661 : env compactionEnv,
1662 : opts *Options,
1663 : vers *version,
1664 : cInfo candidateLevelInfo,
1665 : baseLevel int,
1666 : levelMaxBytes [numLevels]int64,
1667 1 : ) (pc *pickedCompaction) {
1668 1 : if cInfo.level == 0 {
1669 0 : panic("pebble: pickAutoLPositive called for L0")
1670 : }
1671 :
1672 1 : pc = newPickedCompaction(opts, vers, cInfo.level, defaultOutputLevel(cInfo.level, baseLevel), baseLevel)
1673 1 : if pc.outputLevel.level != cInfo.outputLevel {
1674 0 : panic("pebble: compaction picked unexpected output level")
1675 : }
1676 1 : pc.startLevel.files = cInfo.file.Slice()
1677 1 : // Files in level 0 may overlap each other, so pick up all overlapping ones.
1678 1 : if pc.startLevel.level == 0 {
1679 0 : cmp := opts.Comparer.Compare
1680 0 : smallest, largest := manifest.KeyRange(cmp, pc.startLevel.files.Iter())
1681 0 : pc.startLevel.files = vers.Overlaps(0, cmp, smallest.UserKey,
1682 0 : largest.UserKey, largest.IsExclusiveSentinel())
1683 0 : if pc.startLevel.files.Empty() {
1684 0 : panic("pebble: empty compaction")
1685 : }
1686 : }
1687 :
1688 1 : if !pc.setupInputs(opts, env.diskAvailBytes, pc.startLevel) {
1689 0 : return nil
1690 0 : }
1691 1 : return pc.maybeAddLevel(opts, env.diskAvailBytes)
1692 : }
1693 :
1694 : // maybeAddLevel maybe adds a level to the picked compaction.
1695 1 : func (pc *pickedCompaction) maybeAddLevel(opts *Options, diskAvailBytes uint64) *pickedCompaction {
1696 1 : pc.pickerMetrics.singleLevelOverlappingRatio = pc.overlappingRatio()
1697 1 : if pc.outputLevel.level == numLevels-1 {
1698 1 : // Don't add a level if the current output level is in L6
1699 1 : return pc
1700 1 : }
1701 1 : if !opts.Experimental.MultiLevelCompactionHeuristic.allowL0() && pc.startLevel.level == 0 {
1702 1 : return pc
1703 1 : }
1704 1 : if pc.compactionSize() > expandedCompactionByteSizeLimit(
1705 1 : opts, adjustedOutputLevel(pc.outputLevel.level, pc.baseLevel), diskAvailBytes) {
1706 1 : // Don't add a level if the current compaction exceeds the compaction size limit
1707 1 : return pc
1708 1 : }
1709 1 : return opts.Experimental.MultiLevelCompactionHeuristic.pick(pc, opts, diskAvailBytes)
1710 : }
1711 :
1712 : // MultiLevelHeuristic evaluates whether to add files from the next level into the compaction.
1713 : type MultiLevelHeuristic interface {
1714 : // Evaluate returns the preferred compaction.
1715 : pick(pc *pickedCompaction, opts *Options, diskAvailBytes uint64) *pickedCompaction
1716 :
1717 : // Returns if the heuristic allows L0 to be involved in ML compaction
1718 : allowL0() bool
1719 :
1720 : // String implements fmt.Stringer.
1721 : String() string
1722 : }
1723 :
1724 : // NoMultiLevel will never add an additional level to the compaction.
1725 : type NoMultiLevel struct{}
1726 :
1727 : var _ MultiLevelHeuristic = (*NoMultiLevel)(nil)
1728 :
1729 : func (nml NoMultiLevel) pick(
1730 : pc *pickedCompaction, opts *Options, diskAvailBytes uint64,
1731 1 : ) *pickedCompaction {
1732 1 : return pc
1733 1 : }
1734 :
1735 1 : func (nml NoMultiLevel) allowL0() bool { return false }
1736 1 : func (nml NoMultiLevel) String() string { return "none" }
1737 :
1738 1 : func (pc *pickedCompaction) predictedWriteAmp() float64 {
1739 1 : var bytesToCompact uint64
1740 1 : var higherLevelBytes uint64
1741 1 : for i := range pc.inputs {
1742 1 : levelSize := pc.inputs[i].files.SizeSum()
1743 1 : bytesToCompact += levelSize
1744 1 : if i != len(pc.inputs)-1 {
1745 1 : higherLevelBytes += levelSize
1746 1 : }
1747 : }
1748 1 : return float64(bytesToCompact) / float64(higherLevelBytes)
1749 : }
1750 :
1751 1 : func (pc *pickedCompaction) overlappingRatio() float64 {
1752 1 : var higherLevelBytes uint64
1753 1 : var lowestLevelBytes uint64
1754 1 : for i := range pc.inputs {
1755 1 : levelSize := pc.inputs[i].files.SizeSum()
1756 1 : if i == len(pc.inputs)-1 {
1757 1 : lowestLevelBytes += levelSize
1758 1 : continue
1759 : }
1760 1 : higherLevelBytes += levelSize
1761 : }
1762 1 : return float64(lowestLevelBytes) / float64(higherLevelBytes)
1763 : }
1764 :
1765 : // WriteAmpHeuristic defines a multi level compaction heuristic which will add
1766 : // an additional level to the picked compaction if it reduces predicted write
1767 : // amp of the compaction + the addPropensity constant.
1768 : type WriteAmpHeuristic struct {
1769 : // addPropensity is a constant that affects the propensity to conduct multilevel
1770 : // compactions. If positive, a multilevel compaction may get picked even if
1771 : // the single level compaction has lower write amp, and vice versa.
1772 : AddPropensity float64
1773 :
1774 : // AllowL0 if true, allow l0 to be involved in a ML compaction.
1775 : AllowL0 bool
1776 : }
1777 :
1778 : var _ MultiLevelHeuristic = (*WriteAmpHeuristic)(nil)
1779 :
1780 : // TODO(msbutler): microbenchmark the extent to which multilevel compaction
1781 : // picking slows down the compaction picking process. This should be as fast as
1782 : // possible since Compaction-picking holds d.mu, which prevents WAL rotations,
1783 : // in-progress flushes and compactions from completing, etc. Consider ways to
1784 : // deduplicate work, given that setupInputs has already been called.
1785 : func (wa WriteAmpHeuristic) pick(
1786 : pcOrig *pickedCompaction, opts *Options, diskAvailBytes uint64,
1787 1 : ) *pickedCompaction {
1788 1 : pcMulti := pcOrig.clone()
1789 1 : if !pcMulti.setupMultiLevelCandidate(opts, diskAvailBytes) {
1790 1 : return pcOrig
1791 1 : }
1792 1 : picked := pcOrig
1793 1 : if pcMulti.predictedWriteAmp() <= pcOrig.predictedWriteAmp()+wa.AddPropensity {
1794 1 : picked = pcMulti
1795 1 : }
1796 : // Regardless of what compaction was picked, log the multilevelOverlapping ratio.
1797 1 : picked.pickerMetrics.multiLevelOverlappingRatio = pcMulti.overlappingRatio()
1798 1 : return picked
1799 : }
1800 :
1801 1 : func (wa WriteAmpHeuristic) allowL0() bool {
1802 1 : return wa.AllowL0
1803 1 : }
1804 :
1805 : // String implements fmt.Stringer.
1806 1 : func (wa WriteAmpHeuristic) String() string {
1807 1 : return fmt.Sprintf("wamp(%.2f, %t)", wa.AddPropensity, wa.AllowL0)
1808 1 : }
1809 :
1810 : // Helper method to pick compactions originating from L0. Uses information about
1811 : // sublevels to generate a compaction.
1812 1 : func pickL0(env compactionEnv, opts *Options, vers *version, baseLevel int) (pc *pickedCompaction) {
1813 1 : // It is important to pass information about Lbase files to L0Sublevels
1814 1 : // so it can pick a compaction that does not conflict with an Lbase => Lbase+1
1815 1 : // compaction. Without this, we observed reduced concurrency of L0=>Lbase
1816 1 : // compactions, and increasing read amplification in L0.
1817 1 : //
1818 1 : // TODO(bilal) Remove the minCompactionDepth parameter once fixing it at 1
1819 1 : // has been shown to not cause a performance regression.
1820 1 : lcf, err := vers.L0Sublevels.PickBaseCompaction(1, vers.Levels[baseLevel].Slice())
1821 1 : if err != nil {
1822 1 : opts.Logger.Errorf("error when picking base compaction: %s", err)
1823 1 : return
1824 1 : }
1825 1 : if lcf != nil {
1826 1 : pc = newPickedCompactionFromL0(lcf, opts, vers, baseLevel, true)
1827 1 : pc.setupInputs(opts, env.diskAvailBytes, pc.startLevel)
1828 1 : if pc.startLevel.files.Empty() {
1829 0 : opts.Logger.Fatalf("empty compaction chosen")
1830 0 : }
1831 1 : return pc.maybeAddLevel(opts, env.diskAvailBytes)
1832 : }
1833 :
1834 : // Couldn't choose a base compaction. Try choosing an intra-L0
1835 : // compaction. Note that we pass in L0CompactionThreshold here as opposed to
1836 : // 1, since choosing a single sublevel intra-L0 compaction is
1837 : // counterproductive.
1838 1 : lcf, err = vers.L0Sublevels.PickIntraL0Compaction(env.earliestUnflushedSeqNum, minIntraL0Count)
1839 1 : if err != nil {
1840 0 : opts.Logger.Errorf("error when picking intra-L0 compaction: %s", err)
1841 0 : return
1842 0 : }
1843 1 : if lcf != nil {
1844 1 : pc = newPickedCompactionFromL0(lcf, opts, vers, 0, false)
1845 1 : if !pc.setupInputs(opts, env.diskAvailBytes, pc.startLevel) {
1846 0 : return nil
1847 0 : }
1848 1 : if pc.startLevel.files.Empty() {
1849 0 : opts.Logger.Fatalf("empty compaction chosen")
1850 0 : }
1851 1 : {
1852 1 : iter := pc.startLevel.files.Iter()
1853 1 : if iter.First() == nil || iter.Next() == nil {
1854 0 : // A single-file intra-L0 compaction is unproductive.
1855 0 : return nil
1856 0 : }
1857 : }
1858 :
1859 1 : pc.smallest, pc.largest = manifest.KeyRange(pc.cmp, pc.startLevel.files.Iter())
1860 : }
1861 1 : return pc
1862 : }
1863 :
1864 : func pickManualCompaction(
1865 : vers *version, opts *Options, env compactionEnv, baseLevel int, manual *manualCompaction,
1866 1 : ) (pc *pickedCompaction, retryLater bool) {
1867 1 : outputLevel := manual.level + 1
1868 1 : if manual.level == 0 {
1869 1 : outputLevel = baseLevel
1870 1 : } else if manual.level < baseLevel {
1871 0 : // The start level for a compaction must be >= Lbase. A manual
1872 0 : // compaction could have been created adhering to that condition, and
1873 0 : // then an automatic compaction came in and compacted all of the
1874 0 : // sstables in Lbase to Lbase+1 which caused Lbase to change. Simply
1875 0 : // ignore this manual compaction as there is nothing to do (manual.level
1876 0 : // points to an empty level).
1877 0 : return nil, false
1878 0 : }
1879 : // This conflictsWithInProgress call is necessary for the manual compaction to
1880 : // be retried when it conflicts with an ongoing automatic compaction. Without
1881 : // it, the compaction is dropped due to pc.setupInputs returning false since
1882 : // the input/output range is already being compacted, and the manual
1883 : // compaction ends with a non-compacted LSM.
1884 1 : if conflictsWithInProgress(manual, outputLevel, env.inProgressCompactions, opts.Comparer.Compare) {
1885 1 : return nil, true
1886 1 : }
1887 1 : pc = newPickedCompaction(opts, vers, manual.level, defaultOutputLevel(manual.level, baseLevel), baseLevel)
1888 1 : manual.outputLevel = pc.outputLevel.level
1889 1 : pc.startLevel.files = vers.Overlaps(manual.level, opts.Comparer.Compare, manual.start, manual.end, false)
1890 1 : if pc.startLevel.files.Empty() {
1891 1 : // Nothing to do
1892 1 : return nil, false
1893 1 : }
1894 1 : if !pc.setupInputs(opts, env.diskAvailBytes, pc.startLevel) {
1895 0 : // setupInputs returned false indicating there's a conflicting
1896 0 : // concurrent compaction.
1897 0 : return nil, true
1898 0 : }
1899 1 : if pc = pc.maybeAddLevel(opts, env.diskAvailBytes); pc == nil {
1900 0 : return nil, false
1901 0 : }
1902 1 : if pc.outputLevel.level != outputLevel {
1903 1 : if len(pc.extraLevels) > 0 {
1904 1 : // multilevel compactions relax this invariant
1905 1 : } else {
1906 0 : panic("pebble: compaction picked unexpected output level")
1907 : }
1908 : }
1909 : // Fail-safe to protect against compacting the same sstable concurrently.
1910 1 : if inputRangeAlreadyCompacting(env, pc) {
1911 0 : return nil, true
1912 0 : }
1913 1 : return pc, false
1914 : }
1915 :
1916 : func pickDownloadCompaction(
1917 : vers *version,
1918 : opts *Options,
1919 : env compactionEnv,
1920 : baseLevel int,
1921 : download *downloadSpan,
1922 : level int,
1923 : file *fileMetadata,
1924 1 : ) (pc *pickedCompaction) {
1925 1 : // Check if the file is compacting already. In that case we don't need to do
1926 1 : // anything as it'll be downloaded in the process.
1927 1 : if file.CompactionState == manifest.CompactionStateCompacting {
1928 0 : return nil
1929 0 : }
1930 1 : pc = newPickedCompaction(opts, vers, level, level, baseLevel)
1931 1 : pc.kind = compactionKindRewrite
1932 1 : pc.startLevel.files = manifest.NewLevelSliceKeySorted(opts.Comparer.Compare, []*fileMetadata{file})
1933 1 : if !pc.setupInputs(opts, env.diskAvailBytes, pc.startLevel) {
1934 0 : // setupInputs returned false indicating there's a conflicting
1935 0 : // concurrent compaction.
1936 0 : return nil
1937 0 : }
1938 1 : if pc.outputLevel.level != level {
1939 0 : panic("pebble: download compaction picked unexpected output level")
1940 : }
1941 : // Fail-safe to protect against compacting the same sstable concurrently.
1942 1 : if inputRangeAlreadyCompacting(env, pc) {
1943 0 : return nil
1944 0 : }
1945 1 : return pc
1946 : }
1947 :
1948 : func (p *compactionPickerByScore) pickReadTriggeredCompaction(
1949 : env compactionEnv,
1950 1 : ) (pc *pickedCompaction) {
1951 1 : // If a flush is in-progress or expected to happen soon, it means more writes are taking place. We would
1952 1 : // soon be scheduling more write focussed compactions. In this case, skip read compactions as they are
1953 1 : // lower priority.
1954 1 : if env.readCompactionEnv.flushing || env.readCompactionEnv.readCompactions == nil {
1955 1 : return nil
1956 1 : }
1957 1 : for env.readCompactionEnv.readCompactions.size > 0 {
1958 1 : rc := env.readCompactionEnv.readCompactions.remove()
1959 1 : if pc = pickReadTriggeredCompactionHelper(p, rc, env); pc != nil {
1960 1 : break
1961 : }
1962 : }
1963 1 : return pc
1964 : }
1965 :
1966 : func pickReadTriggeredCompactionHelper(
1967 : p *compactionPickerByScore, rc *readCompaction, env compactionEnv,
1968 1 : ) (pc *pickedCompaction) {
1969 1 : cmp := p.opts.Comparer.Compare
1970 1 : overlapSlice := p.vers.Overlaps(rc.level, cmp, rc.start, rc.end, false /* exclusiveEnd */)
1971 1 : if overlapSlice.Empty() {
1972 1 : // If there is no overlap, then the file with the key range
1973 1 : // must have been compacted away. So, we don't proceed to
1974 1 : // compact the same key range again.
1975 1 : return nil
1976 1 : }
1977 :
1978 1 : iter := overlapSlice.Iter()
1979 1 : var fileMatches bool
1980 1 : for f := iter.First(); f != nil; f = iter.Next() {
1981 1 : if f.FileNum == rc.fileNum {
1982 1 : fileMatches = true
1983 1 : break
1984 : }
1985 : }
1986 1 : if !fileMatches {
1987 1 : return nil
1988 1 : }
1989 :
1990 1 : pc = newPickedCompaction(p.opts, p.vers, rc.level, defaultOutputLevel(rc.level, p.baseLevel), p.baseLevel)
1991 1 :
1992 1 : pc.startLevel.files = overlapSlice
1993 1 : if !pc.setupInputs(p.opts, env.diskAvailBytes, pc.startLevel) {
1994 0 : return nil
1995 0 : }
1996 1 : if inputRangeAlreadyCompacting(env, pc) {
1997 0 : return nil
1998 0 : }
1999 1 : pc.kind = compactionKindRead
2000 1 :
2001 1 : // Prevent read compactions which are too wide.
2002 1 : outputOverlaps := pc.version.Overlaps(
2003 1 : pc.outputLevel.level, pc.cmp, pc.smallest.UserKey,
2004 1 : pc.largest.UserKey, pc.largest.IsExclusiveSentinel())
2005 1 : if outputOverlaps.SizeSum() > pc.maxReadCompactionBytes {
2006 1 : return nil
2007 1 : }
2008 :
2009 : // Prevent compactions which start with a small seed file X, but overlap
2010 : // with over allowedCompactionWidth * X file sizes in the output layer.
2011 1 : const allowedCompactionWidth = 35
2012 1 : if outputOverlaps.SizeSum() > overlapSlice.SizeSum()*allowedCompactionWidth {
2013 0 : return nil
2014 0 : }
2015 :
2016 1 : return pc
2017 : }
2018 :
2019 1 : func (p *compactionPickerByScore) forceBaseLevel1() {
2020 1 : p.baseLevel = 1
2021 1 : }
2022 :
2023 1 : func inputRangeAlreadyCompacting(env compactionEnv, pc *pickedCompaction) bool {
2024 1 : for _, cl := range pc.inputs {
2025 1 : iter := cl.files.Iter()
2026 1 : for f := iter.First(); f != nil; f = iter.Next() {
2027 1 : if f.IsCompacting() {
2028 0 : return true
2029 0 : }
2030 : }
2031 : }
2032 :
2033 : // Look for active compactions outputting to the same region of the key
2034 : // space in the same output level. Two potential compactions may conflict
2035 : // without sharing input files if there are no files in the output level
2036 : // that overlap with the intersection of the compactions' key spaces.
2037 : //
2038 : // Consider an active L0->Lbase compaction compacting two L0 files one
2039 : // [a-f] and the other [t-z] into Lbase.
2040 : //
2041 : // L0
2042 : // ↦ 000100 ↤ ↦ 000101 ↤
2043 : // L1
2044 : // ↦ 000004 ↤
2045 : // a b c d e f g h i j k l m n o p q r s t u v w x y z
2046 : //
2047 : // If a new file 000102 [j-p] is flushed while the existing compaction is
2048 : // still ongoing, new file would not be in any compacting sublevel
2049 : // intervals and would not overlap with any Lbase files that are also
2050 : // compacting. However, this compaction cannot be picked because the
2051 : // compaction's output key space [j-p] would overlap the existing
2052 : // compaction's output key space [a-z].
2053 : //
2054 : // L0
2055 : // ↦ 000100* ↤ ↦ 000102 ↤ ↦ 000101* ↤
2056 : // L1
2057 : // ↦ 000004* ↤
2058 : // a b c d e f g h i j k l m n o p q r s t u v w x y z
2059 : //
2060 : // * - currently compacting
2061 1 : if pc.outputLevel != nil && pc.outputLevel.level != 0 {
2062 1 : for _, c := range env.inProgressCompactions {
2063 1 : if pc.outputLevel.level != c.outputLevel {
2064 1 : continue
2065 : }
2066 1 : if base.InternalCompare(pc.cmp, c.largest, pc.smallest) < 0 ||
2067 1 : base.InternalCompare(pc.cmp, c.smallest, pc.largest) > 0 {
2068 1 : continue
2069 : }
2070 :
2071 : // The picked compaction and the in-progress compaction c are
2072 : // outputting to the same region of the key space of the same
2073 : // level.
2074 1 : return true
2075 : }
2076 : }
2077 1 : return false
2078 : }
2079 :
2080 : // conflictsWithInProgress checks if there are any in-progress compactions with overlapping keyspace.
2081 : func conflictsWithInProgress(
2082 : manual *manualCompaction, outputLevel int, inProgressCompactions []compactionInfo, cmp Compare,
2083 1 : ) bool {
2084 1 : for _, c := range inProgressCompactions {
2085 1 : if (c.outputLevel == manual.level || c.outputLevel == outputLevel) &&
2086 1 : isUserKeysOverlapping(manual.start, manual.end, c.smallest.UserKey, c.largest.UserKey, cmp) {
2087 1 : return true
2088 1 : }
2089 1 : for _, in := range c.inputs {
2090 1 : if in.files.Empty() {
2091 1 : continue
2092 : }
2093 1 : iter := in.files.Iter()
2094 1 : smallest := iter.First().Smallest.UserKey
2095 1 : largest := iter.Last().Largest.UserKey
2096 1 : if (in.level == manual.level || in.level == outputLevel) &&
2097 1 : isUserKeysOverlapping(manual.start, manual.end, smallest, largest, cmp) {
2098 0 : return true
2099 0 : }
2100 : }
2101 : }
2102 1 : return false
2103 : }
2104 :
2105 1 : func isUserKeysOverlapping(x1, x2, y1, y2 []byte, cmp Compare) bool {
2106 1 : return cmp(x1, y2) <= 0 && cmp(y1, x2) <= 0
2107 1 : }
|