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