LCOV - code coverage report
Current view: top level - pebble - compaction_picker.go (source / functions) Coverage Total Hit
Test: 2025-07-02 08:19Z a2947b4a - meta test only.lcov Lines: 83.2 % 1212 1008
Test Date: 2025-07-02 08:20:24 Functions: - 0 0

            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            0 : func (info compactionInfo) String() string {
     106            0 :         var buf bytes.Buffer
     107            0 :         var largest int
     108            0 :         for i, in := range info.inputs {
     109            0 :                 if i > 0 {
     110            0 :                         fmt.Fprintf(&buf, " -> ")
     111            0 :                 }
     112            0 :                 fmt.Fprintf(&buf, "L%d", in.level)
     113            0 :                 for f := range in.files.All() {
     114            0 :                         fmt.Fprintf(&buf, " %s", f.TableNum)
     115            0 :                 }
     116            0 :                 if largest < in.level {
     117            0 :                         largest = in.level
     118            0 :                 }
     119              :         }
     120            0 :         if largest != info.outputLevel || len(info.inputs) == 1 {
     121            0 :                 fmt.Fprintf(&buf, " -> L%d", info.outputLevel)
     122            0 :         }
     123            0 :         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            0 : func (cl sublevelInfo) String() string {
     140            0 :         return fmt.Sprintf(`Sublevel %s; Levels %s`, cl.sublevel, cl.LevelSlice)
     141            0 : }
     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            0 :                 panic(fmt.Sprintf("invalid compaction: start level %d should not be empty (base level %d)",
     293            0 :                         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            0 : func adjustedOutputLevel(outputLevel int, baseLevel int) int {
     315            0 :         if outputLevel == 0 {
     316            0 :                 return 0
     317            0 :         }
     318            0 :         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            0 :         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            0 : func (pc *pickedTableCompaction) String() string {
     353            0 :         var builder strings.Builder
     354            0 :         builder.WriteString(fmt.Sprintf(`Score=%f, `, pc.score))
     355            0 :         builder.WriteString(fmt.Sprintf(`Kind=%s, `, pc.kind))
     356            0 :         builder.WriteString(fmt.Sprintf(`AdjustedOutputLevel=%d, `, adjustedOutputLevel(pc.outputLevel.level, pc.baseLevel)))
     357            0 :         builder.WriteString(fmt.Sprintf(`maxOutputFileSize=%d, `, pc.maxOutputFileSize))
     358            0 :         builder.WriteString(fmt.Sprintf(`maxReadCompactionBytes=%d, `, pc.maxReadCompactionBytes))
     359            0 :         builder.WriteString(fmt.Sprintf(`bounds=%s, `, pc.bounds))
     360            0 :         builder.WriteString(fmt.Sprintf(`version=%s, `, pc.version))
     361            0 :         builder.WriteString(fmt.Sprintf(`inputs=%s, `, pc.inputs))
     362            0 :         builder.WriteString(fmt.Sprintf(`startlevel=%s, `, pc.startLevel))
     363            0 :         builder.WriteString(fmt.Sprintf(`outputLevel=%s, `, pc.outputLevel))
     364            0 :         builder.WriteString(fmt.Sprintf(`l0SublevelInfo=%s, `, pc.startLevel.l0SublevelInfo))
     365            0 :         builder.WriteString(fmt.Sprintf(`lcf=%s`, pc.lcf))
     366            0 :         return builder.String()
     367            0 : }
     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            1 :                 return false
     485            1 :         }
     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            1 :                 *pc.lcf = *oldLcf
     568            1 :                 return false
     569            1 :         }
     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            1 : func (pc *pickedTableCompaction) setupMultiLevelCandidate(opts *Options, env compactionEnv) bool {
     591            1 :         pc.inputs = append(pc.inputs, compactionLevel{level: pc.outputLevel.level + 1})
     592            1 : 
     593            1 :         // Recalibrate startLevel and outputLevel:
     594            1 :         //  - startLevel and outputLevel pointers may be obsolete after appending to pc.inputs.
     595            1 :         //  - push outputLevel to extraLevels and move the new level to outputLevel
     596            1 :         pc.startLevel = &pc.inputs[0]
     597            1 :         pc.outputLevel = &pc.inputs[2]
     598            1 :         return pc.setupInputs(opts, env.diskAvailBytes, env.inProgressCompactions, &pc.inputs[1], nil /* TODO(radu) */)
     599            1 : }
     600              : 
     601              : // canCompactTables returns true if the tables in the level slice are not
     602              : // compacting already and don't intersect any problem spans.
     603              : func canCompactTables(
     604              :         inputs manifest.LevelSlice, level int, problemSpans *problemspans.ByLevel,
     605            1 : ) bool {
     606            1 :         for f := range inputs.All() {
     607            1 :                 if f.IsCompacting() {
     608            1 :                         return false
     609            1 :                 }
     610            1 :                 if problemSpans != nil && problemSpans.Overlaps(level, f.UserKeyBounds()) {
     611            0 :                         return false
     612            0 :                 }
     613              :         }
     614            1 :         return true
     615              : }
     616              : 
     617              : // newCompactionPickerByScore creates a compactionPickerByScore associated with
     618              : // the newest version. The picker is used under logLock (until a new version is
     619              : // installed).
     620              : func newCompactionPickerByScore(
     621              :         v *manifest.Version,
     622              :         lvs *latestVersionState,
     623              :         opts *Options,
     624              :         inProgressCompactions []compactionInfo,
     625            1 : ) *compactionPickerByScore {
     626            1 :         p := &compactionPickerByScore{
     627            1 :                 opts:               opts,
     628            1 :                 vers:               v,
     629            1 :                 latestVersionState: lvs,
     630            1 :         }
     631            1 :         p.initLevelMaxBytes(inProgressCompactions)
     632            1 :         return p
     633            1 : }
     634              : 
     635              : // Information about a candidate compaction level that has been identified by
     636              : // the compaction picker.
     637              : type candidateLevelInfo struct {
     638              :         // The fill factor of the level, calculated using uncompensated file sizes and
     639              :         // without any adjustments. A factor > 1 means that the level has more data
     640              :         // than the ideal size for that level.
     641              :         //
     642              :         // For L0, the fill factor is calculated based on the number of sublevels
     643              :         // (see calculateL0FillFactor).
     644              :         //
     645              :         // For L1+, the fill factor is the ratio between the total uncompensated file
     646              :         // size and the ideal size of the level (based on the total size of the DB).
     647              :         fillFactor float64
     648              : 
     649              :         // The score of the level, used to rank levels.
     650              :         //
     651              :         // If the level doesn't require compaction, the score is 0. Otherwise:
     652              :         //  - for L6 the score is equal to the fillFactor;
     653              :         //  - for L0-L5:
     654              :         //    - if the fillFactor is < 1: the score is equal to the fillFactor;
     655              :         //    - if the fillFactor is >= 1: the score is the ratio between the
     656              :         //                                 fillFactor and the next level's fillFactor.
     657              :         score float64
     658              : 
     659              :         // The fill factor of the level after accounting for level size compensation.
     660              :         //
     661              :         // For L0, the compensatedFillFactor is equal to the fillFactor as we don't
     662              :         // account for level size compensation in L0.
     663              :         //
     664              :         // For l1+, the compensatedFillFactor takes into account the estimated
     665              :         // savings in the lower levels because of deletions.
     666              :         //
     667              :         // The compensated fill factor is used to determine if the level should be
     668              :         // compacted (see calculateLevelScores).
     669              :         compensatedFillFactor float64
     670              : 
     671              :         level int
     672              :         // The level to compact to.
     673              :         outputLevel int
     674              :         // The file in level that will be compacted. Additional files may be
     675              :         // picked by the compaction, and a pickedCompaction created for the
     676              :         // compaction.
     677              :         file manifest.LevelFile
     678              : }
     679              : 
     680            1 : func (c *candidateLevelInfo) shouldCompact() bool {
     681            1 :         return c.score > 0
     682            1 : }
     683              : 
     684            1 : func tableTombstoneCompensation(t *manifest.TableMetadata) uint64 {
     685            1 :         return t.Stats.PointDeletionsBytesEstimate + t.Stats.RangeDeletionsBytesEstimate
     686            1 : }
     687              : 
     688              : // tableCompensatedSize returns t's size, including an estimate of the physical
     689              : // size of its external references, and inflated according to compaction
     690              : // priorities.
     691            1 : func tableCompensatedSize(t *manifest.TableMetadata) uint64 {
     692            1 :         // Add in the estimate of disk space that may be reclaimed by compacting the
     693            1 :         // table's tombstones.
     694            1 :         return t.Size + t.EstimatedReferenceSize() + tableTombstoneCompensation(t)
     695            1 : }
     696              : 
     697              : // totalCompensatedSize computes the compensated size over a table metadata
     698              : // iterator. Note that this function is linear in the files available to the
     699              : // iterator. Use the compensatedSizeAnnotator if querying the total
     700              : // compensated size of a level.
     701            1 : func totalCompensatedSize(iter iter.Seq[*manifest.TableMetadata]) uint64 {
     702            1 :         var sz uint64
     703            1 :         for f := range iter {
     704            1 :                 sz += tableCompensatedSize(f)
     705            1 :         }
     706            1 :         return sz
     707              : }
     708              : 
     709              : // compactionPickerByScore holds the state and logic for picking a compaction. A
     710              : // compaction picker is associated with a single version. A new compaction
     711              : // picker is created and initialized every time a new version is installed.
     712              : type compactionPickerByScore struct {
     713              :         opts *Options
     714              :         vers *manifest.Version
     715              :         // Unlike vers, which is immutable and the latest version when this picker
     716              :         // is created, latestVersionState represents the mutable state of the latest
     717              :         // version. This means that at some point in the future a
     718              :         // compactionPickerByScore created in the past will have mutually
     719              :         // inconsistent state in vers and latestVersionState. This is not a problem
     720              :         // since (a) a new picker is created in UpdateVersionLocked when a new
     721              :         // version is installed, and (b) only the latest picker is used for picking
     722              :         // compactions. This is ensured by holding versionSet.logLock for both (a)
     723              :         // and (b).
     724              :         latestVersionState *latestVersionState
     725              :         // The level to target for L0 compactions. Levels L1 to baseLevel must be
     726              :         // empty.
     727              :         baseLevel int
     728              :         // levelMaxBytes holds the dynamically adjusted max bytes setting for each
     729              :         // level.
     730              :         levelMaxBytes [numLevels]int64
     731              :         dbSizeBytes   uint64
     732              : }
     733              : 
     734              : var _ compactionPicker = &compactionPickerByScore{}
     735              : 
     736            1 : func (p *compactionPickerByScore) getMetrics(inProgress []compactionInfo) compactionPickerMetrics {
     737            1 :         var m compactionPickerMetrics
     738            1 :         for _, info := range p.calculateLevelScores(inProgress) {
     739            1 :                 m.levels[info.level].score = info.score
     740            1 :                 m.levels[info.level].fillFactor = info.fillFactor
     741            1 :                 m.levels[info.level].compensatedFillFactor = info.compensatedFillFactor
     742            1 :         }
     743            1 :         return m
     744              : }
     745              : 
     746            1 : func (p *compactionPickerByScore) getBaseLevel() int {
     747            1 :         if p == nil {
     748            0 :                 return 1
     749            0 :         }
     750            1 :         return p.baseLevel
     751              : }
     752              : 
     753              : // estimatedCompactionDebt estimates the number of bytes which need to be
     754              : // compacted before the LSM tree becomes stable.
     755            1 : func (p *compactionPickerByScore) estimatedCompactionDebt() uint64 {
     756            1 :         if p == nil {
     757            0 :                 return 0
     758            0 :         }
     759              : 
     760              :         // We assume that all the bytes in L0 need to be compacted to Lbase. This is
     761              :         // unlike the RocksDB logic that figures out whether L0 needs compaction.
     762            1 :         bytesAddedToNextLevel := p.vers.Levels[0].AggregateSize()
     763            1 :         lbaseSize := p.vers.Levels[p.baseLevel].AggregateSize()
     764            1 : 
     765            1 :         var compactionDebt uint64
     766            1 :         if bytesAddedToNextLevel > 0 && lbaseSize > 0 {
     767            1 :                 // We only incur compaction debt if both L0 and Lbase contain data. If L0
     768            1 :                 // is empty, no compaction is necessary. If Lbase is empty, a move-based
     769            1 :                 // compaction from L0 would occur.
     770            1 :                 compactionDebt += bytesAddedToNextLevel + lbaseSize
     771            1 :         }
     772              : 
     773              :         // loop invariant: At the beginning of the loop, bytesAddedToNextLevel is the
     774              :         // bytes added to `level` in the loop.
     775            1 :         for level := p.baseLevel; level < numLevels-1; level++ {
     776            1 :                 levelSize := p.vers.Levels[level].AggregateSize() + bytesAddedToNextLevel
     777            1 :                 nextLevelSize := p.vers.Levels[level+1].AggregateSize()
     778            1 :                 if levelSize > uint64(p.levelMaxBytes[level]) {
     779            1 :                         bytesAddedToNextLevel = levelSize - uint64(p.levelMaxBytes[level])
     780            1 :                         if nextLevelSize > 0 {
     781            1 :                                 // We only incur compaction debt if the next level contains data. If the
     782            1 :                                 // next level is empty, a move-based compaction would be used.
     783            1 :                                 levelRatio := float64(nextLevelSize) / float64(levelSize)
     784            1 :                                 // The current level contributes bytesAddedToNextLevel to compactions.
     785            1 :                                 // The next level contributes levelRatio * bytesAddedToNextLevel.
     786            1 :                                 compactionDebt += uint64(float64(bytesAddedToNextLevel) * (levelRatio + 1))
     787            1 :                         }
     788            1 :                 } else {
     789            1 :                         // We're not moving any bytes to the next level.
     790            1 :                         bytesAddedToNextLevel = 0
     791            1 :                 }
     792              :         }
     793            1 :         return compactionDebt
     794              : }
     795              : 
     796            1 : func (p *compactionPickerByScore) initLevelMaxBytes(inProgressCompactions []compactionInfo) {
     797            1 :         // The levelMaxBytes calculations here differ from RocksDB in two ways:
     798            1 :         //
     799            1 :         // 1. The use of dbSize vs maxLevelSize. RocksDB uses the size of the maximum
     800            1 :         //    level in L1-L6, rather than determining the size of the bottom level
     801            1 :         //    based on the total amount of data in the dB. The RocksDB calculation is
     802            1 :         //    problematic if L0 contains a significant fraction of data, or if the
     803            1 :         //    level sizes are roughly equal and thus there is a significant fraction
     804            1 :         //    of data outside of the largest level.
     805            1 :         //
     806            1 :         // 2. Not adjusting the size of Lbase based on L0. RocksDB computes
     807            1 :         //    baseBytesMax as the maximum of the configured LBaseMaxBytes and the
     808            1 :         //    size of L0. This is problematic because baseBytesMax is used to compute
     809            1 :         //    the max size of lower levels. A very large baseBytesMax will result in
     810            1 :         //    an overly large value for the size of lower levels which will caused
     811            1 :         //    those levels not to be compacted even when they should be
     812            1 :         //    compacted. This often results in "inverted" LSM shapes where Ln is
     813            1 :         //    larger than Ln+1.
     814            1 : 
     815            1 :         // Determine the first non-empty level and the total DB size.
     816            1 :         firstNonEmptyLevel := -1
     817            1 :         var dbSize uint64
     818            1 :         for level := 1; level < numLevels; level++ {
     819            1 :                 if p.vers.Levels[level].AggregateSize() > 0 {
     820            1 :                         if firstNonEmptyLevel == -1 {
     821            1 :                                 firstNonEmptyLevel = level
     822            1 :                         }
     823            1 :                         dbSize += p.vers.Levels[level].AggregateSize()
     824              :                 }
     825              :         }
     826            1 :         for _, c := range inProgressCompactions {
     827            1 :                 if c.outputLevel == 0 || c.outputLevel == -1 {
     828            1 :                         continue
     829              :                 }
     830            1 :                 if c.inputs[0].level == 0 && (firstNonEmptyLevel == -1 || c.outputLevel < firstNonEmptyLevel) {
     831            1 :                         firstNonEmptyLevel = c.outputLevel
     832            1 :                 }
     833              :         }
     834              : 
     835              :         // Initialize the max-bytes setting for each level to "infinity" which will
     836              :         // disallow compaction for that level. We'll fill in the actual value below
     837              :         // for levels we want to allow compactions from.
     838            1 :         for level := 0; level < numLevels; level++ {
     839            1 :                 p.levelMaxBytes[level] = math.MaxInt64
     840            1 :         }
     841              : 
     842            1 :         dbSizeBelowL0 := dbSize
     843            1 :         dbSize += p.vers.Levels[0].AggregateSize()
     844            1 :         p.dbSizeBytes = dbSize
     845            1 :         if dbSizeBelowL0 == 0 {
     846            1 :                 // No levels for L1 and up contain any data. Target L0 compactions for the
     847            1 :                 // last level or to the level to which there is an ongoing L0 compaction.
     848            1 :                 p.baseLevel = numLevels - 1
     849            1 :                 if firstNonEmptyLevel >= 0 {
     850            1 :                         p.baseLevel = firstNonEmptyLevel
     851            1 :                 }
     852            1 :                 return
     853              :         }
     854              : 
     855            1 :         bottomLevelSize := dbSize - dbSize/uint64(p.opts.Experimental.LevelMultiplier)
     856            1 : 
     857            1 :         curLevelSize := bottomLevelSize
     858            1 :         for level := numLevels - 2; level >= firstNonEmptyLevel; level-- {
     859            1 :                 curLevelSize = uint64(float64(curLevelSize) / float64(p.opts.Experimental.LevelMultiplier))
     860            1 :         }
     861              : 
     862              :         // Compute base level (where L0 data is compacted to).
     863            1 :         baseBytesMax := uint64(p.opts.LBaseMaxBytes)
     864            1 :         p.baseLevel = firstNonEmptyLevel
     865            1 :         for p.baseLevel > 1 && curLevelSize > baseBytesMax {
     866            1 :                 p.baseLevel--
     867            1 :                 curLevelSize = uint64(float64(curLevelSize) / float64(p.opts.Experimental.LevelMultiplier))
     868            1 :         }
     869              : 
     870            1 :         smoothedLevelMultiplier := 1.0
     871            1 :         if p.baseLevel < numLevels-1 {
     872            1 :                 smoothedLevelMultiplier = math.Pow(
     873            1 :                         float64(bottomLevelSize)/float64(baseBytesMax),
     874            1 :                         1.0/float64(numLevels-p.baseLevel-1))
     875            1 :         }
     876              : 
     877            1 :         levelSize := float64(baseBytesMax)
     878            1 :         for level := p.baseLevel; level < numLevels; level++ {
     879            1 :                 if level > p.baseLevel && levelSize > 0 {
     880            1 :                         levelSize *= smoothedLevelMultiplier
     881            1 :                 }
     882              :                 // Round the result since test cases use small target level sizes, which
     883              :                 // can be impacted by floating-point imprecision + integer truncation.
     884            1 :                 roundedLevelSize := math.Round(levelSize)
     885            1 :                 if roundedLevelSize > float64(math.MaxInt64) {
     886            0 :                         p.levelMaxBytes[level] = math.MaxInt64
     887            1 :                 } else {
     888            1 :                         p.levelMaxBytes[level] = int64(roundedLevelSize)
     889            1 :                 }
     890              :         }
     891              : }
     892              : 
     893              : type levelSizeAdjust struct {
     894              :         incomingActualBytes      uint64
     895              :         outgoingActualBytes      uint64
     896              :         outgoingCompensatedBytes uint64
     897              : }
     898              : 
     899            1 : func (a levelSizeAdjust) compensated() uint64 {
     900            1 :         return a.incomingActualBytes - a.outgoingCompensatedBytes
     901            1 : }
     902              : 
     903            1 : func (a levelSizeAdjust) actual() uint64 {
     904            1 :         return a.incomingActualBytes - a.outgoingActualBytes
     905            1 : }
     906              : 
     907            1 : func calculateSizeAdjust(inProgressCompactions []compactionInfo) [numLevels]levelSizeAdjust {
     908            1 :         // Compute size adjustments for each level based on the in-progress
     909            1 :         // compactions. We sum the file sizes of all files leaving and entering each
     910            1 :         // level in in-progress compactions. For outgoing files, we also sum a
     911            1 :         // separate sum of 'compensated file sizes', which are inflated according
     912            1 :         // to deletion estimates.
     913            1 :         //
     914            1 :         // When we adjust a level's size according to these values during score
     915            1 :         // calculation, we subtract the compensated size of start level inputs to
     916            1 :         // account for the fact that score calculation uses compensated sizes.
     917            1 :         //
     918            1 :         // Since compensated file sizes may be compensated because they reclaim
     919            1 :         // space from the output level's files, we only add the real file size to
     920            1 :         // the output level.
     921            1 :         //
     922            1 :         // This is slightly different from RocksDB's behavior, which simply elides
     923            1 :         // compacting files from the level size calculation.
     924            1 :         var sizeAdjust [numLevels]levelSizeAdjust
     925            1 :         for i := range inProgressCompactions {
     926            1 :                 c := &inProgressCompactions[i]
     927            1 :                 // If this compaction's version edit has already been applied, there's
     928            1 :                 // no need to adjust: The LSM we'll examine will already reflect the
     929            1 :                 // new LSM state.
     930            1 :                 if c.versionEditApplied {
     931            1 :                         continue
     932              :                 }
     933              : 
     934            1 :                 for _, input := range c.inputs {
     935            1 :                         actualSize := input.files.AggregateSizeSum()
     936            1 :                         compensatedSize := totalCompensatedSize(input.files.All())
     937            1 : 
     938            1 :                         if input.level != c.outputLevel {
     939            1 :                                 sizeAdjust[input.level].outgoingCompensatedBytes += compensatedSize
     940            1 :                                 sizeAdjust[input.level].outgoingActualBytes += actualSize
     941            1 :                                 if c.outputLevel != -1 {
     942            1 :                                         sizeAdjust[c.outputLevel].incomingActualBytes += actualSize
     943            1 :                                 }
     944              :                         }
     945              :                 }
     946              :         }
     947            1 :         return sizeAdjust
     948              : }
     949              : 
     950              : // calculateLevelScores calculates the candidateLevelInfo for all levels and
     951              : // returns them in decreasing score order.
     952              : func (p *compactionPickerByScore) calculateLevelScores(
     953              :         inProgressCompactions []compactionInfo,
     954            1 : ) [numLevels]candidateLevelInfo {
     955            1 :         var scores [numLevels]candidateLevelInfo
     956            1 :         for i := range scores {
     957            1 :                 scores[i].level = i
     958            1 :                 scores[i].outputLevel = i + 1
     959            1 :         }
     960            1 :         l0FillFactor := calculateL0FillFactor(p.vers, p.latestVersionState.l0Organizer, p.opts, inProgressCompactions)
     961            1 :         scores[0] = candidateLevelInfo{
     962            1 :                 outputLevel:           p.baseLevel,
     963            1 :                 fillFactor:            l0FillFactor,
     964            1 :                 compensatedFillFactor: l0FillFactor, // No compensation for L0.
     965            1 :         }
     966            1 :         sizeAdjust := calculateSizeAdjust(inProgressCompactions)
     967            1 :         for level := 1; level < numLevels; level++ {
     968            1 :                 compensatedLevelSize :=
     969            1 :                         // Actual file size.
     970            1 :                         p.vers.Levels[level].AggregateSize() +
     971            1 :                                 // Point deletions.
     972            1 :                                 *pointDeletionsBytesEstimateAnnotator.LevelAnnotation(p.vers.Levels[level]) +
     973            1 :                                 // Range deletions.
     974            1 :                                 *rangeDeletionsBytesEstimateAnnotator.LevelAnnotation(p.vers.Levels[level]) +
     975            1 :                                 // Adjustments for in-progress compactions.
     976            1 :                                 sizeAdjust[level].compensated()
     977            1 :                 scores[level].compensatedFillFactor = float64(compensatedLevelSize) / float64(p.levelMaxBytes[level])
     978            1 :                 scores[level].fillFactor = float64(p.vers.Levels[level].AggregateSize()+sizeAdjust[level].actual()) / float64(p.levelMaxBytes[level])
     979            1 :         }
     980              : 
     981              :         // Adjust each level's fill factor by the fill factor of the next level to get
     982              :         // an (uncompensated) score; and each level's compensated fill factor by the
     983              :         // fill factor of the next level to get a compensated score.
     984              :         //
     985              :         // The compensated score is used to determine if the level should be compacted
     986              :         // at all. The (uncompensated) score is used as the value used to rank levels.
     987              :         //
     988              :         // If the next level has a high fill factor, and is thus a priority for
     989              :         // compaction, this reduces the priority for compacting the current level. If
     990              :         // the next level has a low fill factor (i.e. it is below its target size),
     991              :         // this increases the priority for compacting the current level.
     992              :         //
     993              :         // The effect of this adjustment is to help prioritize compactions in lower
     994              :         // levels. The following example shows the scores and the fill factors. In this
     995              :         // scenario, L0 has 68 sublevels. L3 (a.k.a. Lbase) is significantly above its
     996              :         // target size. The original score prioritizes compactions from those two
     997              :         // levels, but doing so ends up causing a future problem: data piles up in the
     998              :         // higher levels, starving L5->L6 compactions, and to a lesser degree starving
     999              :         // L4->L5 compactions.
    1000              :         //
    1001              :         // Note that in the example shown there is no level size compensation so the
    1002              :         // compensatedFillFactor and fillFactor are the same for each level.
    1003              :         //
    1004              :         //        score   fillFactor   compensatedFillFactor   size   max-size
    1005              :         //   L0     3.2         68.0                    68.0  2.2 G          -
    1006              :         //   L3     3.2         21.1                    21.1  1.3 G       64 M
    1007              :         //   L4     3.4          6.7                     6.7  3.1 G      467 M
    1008              :         //   L5     3.4          2.0                     2.0  6.6 G      3.3 G
    1009              :         //   L6       0          0.6                     0.6   14 G       24 G
    1010              :         //
    1011              :         // TODO(radu): the way compensation works needs some rethinking. For example,
    1012              :         // if compacting L5 can free up a lot of space in L6, the score of L5 should
    1013              :         // go *up* with the fill factor of L6, not the other way around.
    1014            1 :         for level := 0; level < numLevels; level++ {
    1015            1 :                 if level > 0 && level < p.baseLevel {
    1016            1 :                         continue
    1017              :                 }
    1018            1 :                 const compensatedFillFactorThreshold = 1.0
    1019            1 :                 if scores[level].compensatedFillFactor < compensatedFillFactorThreshold {
    1020            1 :                         // No need to compact this level; score stays 0.
    1021            1 :                         continue
    1022              :                 }
    1023            1 :                 score := scores[level].fillFactor
    1024            1 :                 compensatedScore := scores[level].compensatedFillFactor
    1025            1 :                 if level < numLevels-1 {
    1026            1 :                         nextLevel := scores[level].outputLevel
    1027            1 :                         // Avoid absurdly large scores by placing a floor on the factor that we'll
    1028            1 :                         // adjust a level by. The value of 0.01 was chosen somewhat arbitrarily.
    1029            1 :                         denominator := max(0.01, scores[nextLevel].fillFactor)
    1030            1 :                         score /= denominator
    1031            1 :                         compensatedScore /= denominator
    1032            1 :                 }
    1033              :                 // The level requires compaction iff both compensatedFillFactor and
    1034              :                 // compensatedScore are >= 1.0.
    1035              :                 //
    1036              :                 // TODO(radu): this seems ad-hoc. In principle, the state of other levels
    1037              :                 // should not come into play when we're determining this level's eligibility
    1038              :                 // for compaction. The score should take care of correctly prioritizing the
    1039              :                 // levels.
    1040            1 :                 const compensatedScoreThreshold = 1.0
    1041            1 :                 if compensatedScore < compensatedScoreThreshold {
    1042            1 :                         // No need to compact this level; score stays 0.
    1043            1 :                         continue
    1044              :                 }
    1045            1 :                 scores[level].score = score
    1046              :         }
    1047              :         // Sort by score (decreasing) and break ties by level (increasing).
    1048            1 :         slices.SortFunc(scores[:], func(a, b candidateLevelInfo) int {
    1049            1 :                 if a.score != b.score {
    1050            1 :                         return cmp.Compare(b.score, a.score)
    1051            1 :                 }
    1052            1 :                 return cmp.Compare(a.level, b.level)
    1053              :         })
    1054            1 :         return scores
    1055              : }
    1056              : 
    1057              : // calculateL0FillFactor calculates a float value representing the relative
    1058              : // priority of compacting L0. A value less than 1 indicates that L0 does not
    1059              : // need any compactions.
    1060              : //
    1061              : // L0 is special in that files within L0 may overlap one another, so a different
    1062              : // set of heuristics that take into account read amplification apply.
    1063              : func calculateL0FillFactor(
    1064              :         vers *manifest.Version,
    1065              :         l0Organizer *manifest.L0Organizer,
    1066              :         opts *Options,
    1067              :         inProgressCompactions []compactionInfo,
    1068            1 : ) float64 {
    1069            1 :         // Use the sublevel count to calculate the score. The base vs intra-L0
    1070            1 :         // compaction determination happens in pickAuto, not here.
    1071            1 :         score := float64(2*l0Organizer.MaxDepthAfterOngoingCompactions()) /
    1072            1 :                 float64(opts.L0CompactionThreshold)
    1073            1 : 
    1074            1 :         // Also calculate a score based on the file count but use it only if it
    1075            1 :         // produces a higher score than the sublevel-based one. This heuristic is
    1076            1 :         // designed to accommodate cases where L0 is accumulating non-overlapping
    1077            1 :         // files in L0. Letting too many non-overlapping files accumulate in few
    1078            1 :         // sublevels is undesirable, because:
    1079            1 :         // 1) we can produce a massive backlog to compact once files do overlap.
    1080            1 :         // 2) constructing L0 sublevels has a runtime that grows superlinearly with
    1081            1 :         //    the number of files in L0 and must be done while holding D.mu.
    1082            1 :         noncompactingFiles := vers.Levels[0].Len()
    1083            1 :         for _, c := range inProgressCompactions {
    1084            1 :                 for _, cl := range c.inputs {
    1085            1 :                         if cl.level == 0 {
    1086            1 :                                 noncompactingFiles -= cl.files.Len()
    1087            1 :                         }
    1088              :                 }
    1089              :         }
    1090            1 :         fileScore := float64(noncompactingFiles) / float64(opts.L0CompactionFileThreshold)
    1091            1 :         if score < fileScore {
    1092            1 :                 score = fileScore
    1093            1 :         }
    1094            1 :         return score
    1095              : }
    1096              : 
    1097              : // pickCompactionSeedFile picks a file from `level` in the `vers` to build a
    1098              : // compaction around. Currently, this function implements a heuristic similar to
    1099              : // RocksDB's kMinOverlappingRatio, seeking to minimize write amplification. This
    1100              : // function is linear with respect to the number of files in `level` and
    1101              : // `outputLevel`.
    1102              : func pickCompactionSeedFile(
    1103              :         vers *manifest.Version,
    1104              :         virtualBackings *manifest.VirtualBackings,
    1105              :         opts *Options,
    1106              :         level, outputLevel int,
    1107              :         earliestSnapshotSeqNum base.SeqNum,
    1108              :         problemSpans *problemspans.ByLevel,
    1109            1 : ) (manifest.LevelFile, bool) {
    1110            1 :         // Select the file within the level to compact. We want to minimize write
    1111            1 :         // amplification, but also ensure that (a) deletes are propagated to the
    1112            1 :         // bottom level in a timely fashion, and (b) virtual sstables that are
    1113            1 :         // pinning backing sstables where most of the data is garbage are compacted
    1114            1 :         // away. Doing (a) and (b) reclaims disk space. A table's smallest sequence
    1115            1 :         // number provides a measure of its age. The ratio of overlapping-bytes /
    1116            1 :         // table-size gives an indication of write amplification (a smaller ratio is
    1117            1 :         // preferrable).
    1118            1 :         //
    1119            1 :         // The current heuristic is based off the RocksDB kMinOverlappingRatio
    1120            1 :         // heuristic. It chooses the file with the minimum overlapping ratio with
    1121            1 :         // the target level, which minimizes write amplification.
    1122            1 :         //
    1123            1 :         // The heuristic uses a "compensated size" for the denominator, which is the
    1124            1 :         // file size inflated by (a) an estimate of the space that may be reclaimed
    1125            1 :         // through compaction, and (b) a fraction of the amount of garbage in the
    1126            1 :         // backing sstable pinned by this (virtual) sstable.
    1127            1 :         //
    1128            1 :         // TODO(peter): For concurrent compactions, we may want to try harder to
    1129            1 :         // pick a seed file whose resulting compaction bounds do not overlap with
    1130            1 :         // an in-progress compaction.
    1131            1 : 
    1132            1 :         cmp := opts.Comparer.Compare
    1133            1 :         startIter := vers.Levels[level].Iter()
    1134            1 :         outputIter := vers.Levels[outputLevel].Iter()
    1135            1 : 
    1136            1 :         var file manifest.LevelFile
    1137            1 :         smallestRatio := uint64(math.MaxUint64)
    1138            1 : 
    1139            1 :         outputFile := outputIter.First()
    1140            1 : 
    1141            1 :         for f := startIter.First(); f != nil; f = startIter.Next() {
    1142            1 :                 var overlappingBytes uint64
    1143            1 :                 if f.IsCompacting() {
    1144            1 :                         // Move on if this file is already being compacted. We'll likely
    1145            1 :                         // still need to move past the overlapping output files regardless,
    1146            1 :                         // but in cases where all start-level files are compacting we won't.
    1147            1 :                         continue
    1148              :                 }
    1149            1 :                 if problemSpans != nil && problemSpans.Overlaps(level, f.UserKeyBounds()) {
    1150            0 :                         // File touches problem span which temporarily disallows auto compactions.
    1151            0 :                         continue
    1152              :                 }
    1153              : 
    1154              :                 // Trim any output-level files smaller than f.
    1155            1 :                 for outputFile != nil && sstableKeyCompare(cmp, outputFile.Largest(), f.Smallest()) < 0 {
    1156            1 :                         outputFile = outputIter.Next()
    1157            1 :                 }
    1158              : 
    1159            1 :                 skip := false
    1160            1 :                 for outputFile != nil && sstableKeyCompare(cmp, outputFile.Smallest(), f.Largest()) <= 0 {
    1161            1 :                         overlappingBytes += outputFile.Size
    1162            1 :                         if outputFile.IsCompacting() {
    1163            1 :                                 // If one of the overlapping files is compacting, we're not going to be
    1164            1 :                                 // able to compact f anyway, so skip it.
    1165            1 :                                 skip = true
    1166            1 :                                 break
    1167              :                         }
    1168            1 :                         if problemSpans != nil && problemSpans.Overlaps(outputLevel, outputFile.UserKeyBounds()) {
    1169            0 :                                 // Overlapping file touches problem span which temporarily disallows auto compactions.
    1170            0 :                                 skip = true
    1171            0 :                                 break
    1172              :                         }
    1173              : 
    1174              :                         // For files in the bottommost level of the LSM, the
    1175              :                         // Stats.RangeDeletionsBytesEstimate field is set to the estimate
    1176              :                         // of bytes /within/ the file itself that may be dropped by
    1177              :                         // recompacting the file. These bytes from obsolete keys would not
    1178              :                         // need to be rewritten if we compacted `f` into `outputFile`, so
    1179              :                         // they don't contribute to write amplification. Subtracting them
    1180              :                         // out of the overlapping bytes helps prioritize these compactions
    1181              :                         // that are cheaper than their file sizes suggest.
    1182            1 :                         if outputLevel == numLevels-1 && outputFile.LargestSeqNum < earliestSnapshotSeqNum {
    1183            1 :                                 overlappingBytes -= outputFile.Stats.RangeDeletionsBytesEstimate
    1184            1 :                         }
    1185              : 
    1186              :                         // If the file in the next level extends beyond f's largest key,
    1187              :                         // break out and don't advance outputIter because f's successor
    1188              :                         // might also overlap.
    1189              :                         //
    1190              :                         // Note, we stop as soon as we encounter an output-level file with a
    1191              :                         // largest key beyond the input-level file's largest bound. We
    1192              :                         // perform a simple user key comparison here using sstableKeyCompare
    1193              :                         // which handles the potential for exclusive largest key bounds.
    1194              :                         // There's some subtlety when the bounds are equal (eg, equal and
    1195              :                         // inclusive, or equal and exclusive). Current Pebble doesn't split
    1196              :                         // user keys across sstables within a level (and in format versions
    1197              :                         // FormatSplitUserKeysMarkedCompacted and later we guarantee no
    1198              :                         // split user keys exist within the entire LSM). In that case, we're
    1199              :                         // assured that neither the input level nor the output level's next
    1200              :                         // file shares the same user key, so compaction expansion will not
    1201              :                         // include them in any compaction compacting `f`.
    1202              :                         //
    1203              :                         // NB: If we /did/ allow split user keys, or we're running on an
    1204              :                         // old database with an earlier format major version where there are
    1205              :                         // existing split user keys, this logic would be incorrect. Consider
    1206              :                         //    L1: [a#120,a#100] [a#80,a#60]
    1207              :                         //    L2: [a#55,a#45] [a#35,a#25] [a#15,a#5]
    1208              :                         // While considering the first file in L1, [a#120,a#100], we'd skip
    1209              :                         // past all of the files in L2. When considering the second file in
    1210              :                         // L1, we'd improperly conclude that the second file overlaps
    1211              :                         // nothing in the second level and is cheap to compact, when in
    1212              :                         // reality we'd need to expand the compaction to include all 5
    1213              :                         // files.
    1214            1 :                         if sstableKeyCompare(cmp, outputFile.Largest(), f.Largest()) > 0 {
    1215            1 :                                 break
    1216              :                         }
    1217            1 :                         outputFile = outputIter.Next()
    1218              :                 }
    1219            1 :                 if skip {
    1220            1 :                         continue
    1221              :                 }
    1222              : 
    1223            1 :                 compSz := tableCompensatedSize(f) + responsibleForGarbageBytes(virtualBackings, f)
    1224            1 :                 scaledRatio := overlappingBytes * 1024 / compSz
    1225            1 :                 if scaledRatio < smallestRatio {
    1226            1 :                         smallestRatio = scaledRatio
    1227            1 :                         file = startIter.Take()
    1228            1 :                 }
    1229              :         }
    1230            1 :         return file, file.TableMetadata != nil
    1231              : }
    1232              : 
    1233              : // responsibleForGarbageBytes returns the amount of garbage in the backing
    1234              : // sstable that we consider the responsibility of this virtual sstable. For
    1235              : // non-virtual sstables, this is of course 0. For virtual sstables, we equally
    1236              : // distribute the responsibility of the garbage across all the virtual
    1237              : // sstables that are referencing the same backing sstable. One could
    1238              : // alternatively distribute this in proportion to the virtual sst sizes, but
    1239              : // it isn't clear that more sophisticated heuristics are worth it, given that
    1240              : // the garbage cannot be reclaimed until all the referencing virtual sstables
    1241              : // are compacted.
    1242              : func responsibleForGarbageBytes(
    1243              :         virtualBackings *manifest.VirtualBackings, m *manifest.TableMetadata,
    1244            1 : ) uint64 {
    1245            1 :         if !m.Virtual {
    1246            1 :                 return 0
    1247            1 :         }
    1248            1 :         useCount, virtualizedSize := virtualBackings.Usage(m.TableBacking.DiskFileNum)
    1249            1 :         // Since virtualizedSize is the sum of the estimated size of all virtual
    1250            1 :         // ssts, we allow for the possibility that virtualizedSize could exceed
    1251            1 :         // m.TableBacking.Size.
    1252            1 :         totalGarbage := int64(m.TableBacking.Size) - int64(virtualizedSize)
    1253            1 :         if totalGarbage <= 0 {
    1254            1 :                 return 0
    1255            1 :         }
    1256            1 :         if useCount == 0 {
    1257            0 :                 // This cannot happen if m exists in the latest version. The call to
    1258            0 :                 // ResponsibleForGarbageBytes during compaction picking ensures that m
    1259            0 :                 // exists in the latest version by holding versionSet.logLock.
    1260            0 :                 panic(errors.AssertionFailedf("%s has zero useCount", m.String()))
    1261              :         }
    1262            1 :         return uint64(totalGarbage) / uint64(useCount)
    1263              : }
    1264              : 
    1265            1 : func (p *compactionPickerByScore) getCompactionConcurrency() int {
    1266            1 :         lower, upper := p.opts.CompactionConcurrencyRange()
    1267            1 :         if lower >= upper {
    1268            1 :                 return upper
    1269            1 :         }
    1270              :         // Compaction concurrency is controlled by L0 read-amp. We allow one
    1271              :         // additional compaction per L0CompactionConcurrency sublevels, as well as
    1272              :         // one additional compaction per CompactionDebtConcurrency bytes of
    1273              :         // compaction debt. Compaction concurrency is tied to L0 sublevels as that
    1274              :         // signal is independent of the database size. We tack on the compaction
    1275              :         // debt as a second signal to prevent compaction concurrency from dropping
    1276              :         // significantly right after a base compaction finishes, and before those
    1277              :         // bytes have been compacted further down the LSM.
    1278              :         //
    1279              :         // Let n be the number of in-progress compactions.
    1280              :         //
    1281              :         // l0ReadAmp >= ccSignal1 then can run another compaction, where
    1282              :         // ccSignal1 = n * p.opts.Experimental.L0CompactionConcurrency
    1283              :         // Rearranging,
    1284              :         // n <= l0ReadAmp / p.opts.Experimental.L0CompactionConcurrency.
    1285              :         // So we can run up to
    1286              :         // l0ReadAmp / p.opts.Experimental.L0CompactionConcurrency extra compactions.
    1287            1 :         l0ReadAmpCompactions := 0
    1288            1 :         if p.opts.Experimental.L0CompactionConcurrency > 0 {
    1289            1 :                 l0ReadAmp := p.latestVersionState.l0Organizer.MaxDepthAfterOngoingCompactions()
    1290            1 :                 l0ReadAmpCompactions = (l0ReadAmp / p.opts.Experimental.L0CompactionConcurrency)
    1291            1 :         }
    1292              :         // compactionDebt >= ccSignal2 then can run another compaction, where
    1293              :         // ccSignal2 = uint64(n) * p.opts.Experimental.CompactionDebtConcurrency
    1294              :         // Rearranging,
    1295              :         // n <= compactionDebt / p.opts.Experimental.CompactionDebtConcurrency
    1296              :         // So we can run up to
    1297              :         // compactionDebt / p.opts.Experimental.CompactionDebtConcurrency extra
    1298              :         // compactions.
    1299            1 :         compactionDebtCompactions := 0
    1300            1 :         if p.opts.Experimental.CompactionDebtConcurrency > 0 {
    1301            1 :                 compactionDebt := p.estimatedCompactionDebt()
    1302            1 :                 compactionDebtCompactions = int(compactionDebt / p.opts.Experimental.CompactionDebtConcurrency)
    1303            1 :         }
    1304              : 
    1305            1 :         compactableGarbageCompactions := 0
    1306            1 :         garbageFractionLimit := p.opts.Experimental.CompactionGarbageFractionForMaxConcurrency()
    1307            1 :         if garbageFractionLimit > 0 && p.dbSizeBytes > 0 {
    1308            1 :                 compactableGarbageBytes :=
    1309            1 :                         *pointDeletionsBytesEstimateAnnotator.MultiLevelAnnotation(p.vers.Levels[:]) +
    1310            1 :                                 *rangeDeletionsBytesEstimateAnnotator.MultiLevelAnnotation(p.vers.Levels[:])
    1311            1 :                 garbageFraction := float64(compactableGarbageBytes) / float64(p.dbSizeBytes)
    1312            1 :                 compactableGarbageCompactions =
    1313            1 :                         int((garbageFraction / garbageFractionLimit) * float64(upper-lower))
    1314            1 :         }
    1315              : 
    1316            1 :         extraCompactions := max(l0ReadAmpCompactions, compactionDebtCompactions, compactableGarbageCompactions, 0)
    1317            1 : 
    1318            1 :         return min(lower+extraCompactions, upper)
    1319              : }
    1320              : 
    1321              : // TODO(sumeer): remove unless someone actually finds this useful.
    1322              : func (p *compactionPickerByScore) logCompactionForTesting(
    1323              :         env compactionEnv, scores [numLevels]candidateLevelInfo, pc *pickedTableCompaction,
    1324            0 : ) {
    1325            0 :         var buf bytes.Buffer
    1326            0 :         for i := 0; i < numLevels; i++ {
    1327            0 :                 if i != 0 && i < p.baseLevel {
    1328            0 :                         continue
    1329              :                 }
    1330              : 
    1331            0 :                 var info *candidateLevelInfo
    1332            0 :                 for j := range scores {
    1333            0 :                         if scores[j].level == i {
    1334            0 :                                 info = &scores[j]
    1335            0 :                                 break
    1336              :                         }
    1337              :                 }
    1338              : 
    1339            0 :                 marker := " "
    1340            0 :                 if pc.startLevel.level == info.level {
    1341            0 :                         marker = "*"
    1342            0 :                 }
    1343            0 :                 fmt.Fprintf(&buf, "  %sL%d: score:%5.1f  fillFactor:%5.1f  compensatedFillFactor:%5.1f %8s  %8s",
    1344            0 :                         marker, info.level, info.score, info.fillFactor, info.compensatedFillFactor,
    1345            0 :                         humanize.Bytes.Int64(int64(totalCompensatedSize(
    1346            0 :                                 p.vers.Levels[info.level].All(),
    1347            0 :                         ))),
    1348            0 :                         humanize.Bytes.Int64(p.levelMaxBytes[info.level]),
    1349            0 :                 )
    1350            0 : 
    1351            0 :                 count := 0
    1352            0 :                 for i := range env.inProgressCompactions {
    1353            0 :                         c := &env.inProgressCompactions[i]
    1354            0 :                         if c.inputs[0].level != info.level {
    1355            0 :                                 continue
    1356              :                         }
    1357            0 :                         count++
    1358            0 :                         if count == 1 {
    1359            0 :                                 fmt.Fprintf(&buf, "  [")
    1360            0 :                         } else {
    1361            0 :                                 fmt.Fprintf(&buf, " ")
    1362            0 :                         }
    1363            0 :                         fmt.Fprintf(&buf, "L%d->L%d", c.inputs[0].level, c.outputLevel)
    1364              :                 }
    1365            0 :                 if count > 0 {
    1366            0 :                         fmt.Fprintf(&buf, "]")
    1367            0 :                 }
    1368            0 :                 fmt.Fprintf(&buf, "\n")
    1369              :         }
    1370            0 :         p.opts.Logger.Infof("pickAuto: L%d->L%d\n%s",
    1371            0 :                 pc.startLevel.level, pc.outputLevel.level, buf.String())
    1372              : }
    1373              : 
    1374              : // pickAutoScore picks the best score-based compaction, if any.
    1375              : //
    1376              : // On each call, pickAutoScore computes per-level size adjustments based on
    1377              : // in-progress compactions, and computes a per-level score. The levels are
    1378              : // iterated over in decreasing score order trying to find a valid compaction
    1379              : // anchored at that level.
    1380              : //
    1381              : // If a score-based compaction cannot be found, pickAuto falls back to looking
    1382              : // for an elision-only compaction to remove obsolete keys.
    1383            1 : func (p *compactionPickerByScore) pickAutoScore(env compactionEnv) pickedCompaction {
    1384            1 :         scores := p.calculateLevelScores(env.inProgressCompactions)
    1385            1 : 
    1386            1 :         // Check for a score-based compaction. candidateLevelInfos are first sorted
    1387            1 :         // by whether they should be compacted, so if we find a level which shouldn't
    1388            1 :         // be compacted, we can break early.
    1389            1 :         for i := range scores {
    1390            1 :                 info := &scores[i]
    1391            1 :                 if !info.shouldCompact() {
    1392            1 :                         break
    1393              :                 }
    1394            1 :                 if info.level == numLevels-1 {
    1395            1 :                         continue
    1396              :                 }
    1397              : 
    1398            1 :                 if info.level == 0 {
    1399            1 :                         ptc := pickL0(env, p.opts, p.vers, p.latestVersionState.l0Organizer, p.baseLevel)
    1400            1 :                         if ptc != nil {
    1401            1 :                                 p.addScoresToPickedCompactionMetrics(ptc, scores)
    1402            1 :                                 ptc.score = info.score
    1403            1 :                                 if false {
    1404            0 :                                         p.logCompactionForTesting(env, scores, ptc)
    1405            0 :                                 }
    1406            1 :                                 return ptc
    1407              :                         }
    1408            1 :                         continue
    1409              :                 }
    1410              : 
    1411              :                 // info.level > 0
    1412            1 :                 var ok bool
    1413            1 :                 info.file, ok = pickCompactionSeedFile(p.vers, &p.latestVersionState.virtualBackings, p.opts, info.level, info.outputLevel, env.earliestSnapshotSeqNum, env.problemSpans)
    1414            1 :                 if !ok {
    1415            1 :                         continue
    1416              :                 }
    1417              : 
    1418            1 :                 pc := pickAutoLPositive(env, p.opts, p.vers, p.latestVersionState.l0Organizer, *info, p.baseLevel)
    1419            1 :                 if pc != nil {
    1420            1 :                         p.addScoresToPickedCompactionMetrics(pc, scores)
    1421            1 :                         pc.score = info.score
    1422            1 :                         if false {
    1423            0 :                                 p.logCompactionForTesting(env, scores, pc)
    1424            0 :                         }
    1425            1 :                         return pc
    1426              :                 }
    1427              :         }
    1428            1 :         return nil
    1429              : }
    1430              : 
    1431              : // pickAutoNonScore picks the best non-score-based compaction, if any.
    1432            1 : func (p *compactionPickerByScore) pickAutoNonScore(env compactionEnv) (pc pickedCompaction) {
    1433            1 :         // Check for files which contain excessive point tombstones that could slow
    1434            1 :         // down reads. Unlike elision-only compactions, these compactions may select
    1435            1 :         // a file at any level rather than only the lowest level.
    1436            1 :         if pc := p.pickTombstoneDensityCompaction(env); pc != nil {
    1437            1 :                 return pc
    1438            1 :         }
    1439              : 
    1440              :         // Check for L6 files with tombstones that may be elided. These files may
    1441              :         // exist if a snapshot prevented the elision of a tombstone or because of
    1442              :         // a move compaction. These are low-priority compactions because they
    1443              :         // don't help us keep up with writes, just reclaim disk space.
    1444            1 :         if pc := p.pickElisionOnlyCompaction(env); pc != nil {
    1445            1 :                 return pc
    1446            1 :         }
    1447              : 
    1448              :         // Check for blob file rewrites. These are low-priority compactions because
    1449              :         // they don't help us keep up with writes, just reclaim disk space.
    1450            1 :         if pc := p.pickBlobFileRewriteCompaction(env); pc != nil {
    1451            1 :                 return pc
    1452            1 :         }
    1453              : 
    1454            1 :         if pc := p.pickReadTriggeredCompaction(env); pc != nil {
    1455            0 :                 return pc
    1456            0 :         }
    1457              : 
    1458              :         // NB: This should only be run if a read compaction wasn't
    1459              :         // scheduled.
    1460              :         //
    1461              :         // We won't be scheduling a read compaction right now, and in
    1462              :         // read heavy workloads, compactions won't be scheduled frequently
    1463              :         // because flushes aren't frequent. So we need to signal to the
    1464              :         // iterator to schedule a compaction when it adds compactions to
    1465              :         // the read compaction queue.
    1466              :         //
    1467              :         // We need the nil check here because without it, we have some
    1468              :         // tests which don't set that variable fail. Since there's a
    1469              :         // chance that one of those tests wouldn't want extra compactions
    1470              :         // to be scheduled, I added this check here, instead of
    1471              :         // setting rescheduleReadCompaction in those tests.
    1472            1 :         if env.readCompactionEnv.rescheduleReadCompaction != nil {
    1473            1 :                 *env.readCompactionEnv.rescheduleReadCompaction = true
    1474            1 :         }
    1475              : 
    1476              :         // At the lowest possible compaction-picking priority, look for files marked
    1477              :         // for compaction. Pebble will mark files for compaction if they have atomic
    1478              :         // compaction units that span multiple files. While current Pebble code does
    1479              :         // not construct such sstables, RocksDB and earlier versions of Pebble may
    1480              :         // have created them. These split user keys form sets of files that must be
    1481              :         // compacted together for correctness (referred to as "atomic compaction
    1482              :         // units" within the code). Rewrite them in-place.
    1483              :         //
    1484              :         // It's also possible that a file may have been marked for compaction by
    1485              :         // even earlier versions of Pebble code, since TableMetadata's
    1486              :         // MarkedForCompaction field is persisted in the manifest. That's okay. We
    1487              :         // previously would've ignored the designation, whereas now we'll re-compact
    1488              :         // the file in place.
    1489            1 :         if p.vers.Stats.MarkedForCompaction > 0 {
    1490            0 :                 if pc := p.pickRewriteCompaction(env); pc != nil {
    1491            0 :                         return pc
    1492            0 :                 }
    1493              :         }
    1494              : 
    1495            1 :         return nil
    1496              : }
    1497              : 
    1498              : func (p *compactionPickerByScore) addScoresToPickedCompactionMetrics(
    1499              :         pc *pickedTableCompaction, candInfo [numLevels]candidateLevelInfo,
    1500            1 : ) {
    1501            1 : 
    1502            1 :         // candInfo is sorted by score, not by compaction level.
    1503            1 :         infoByLevel := [numLevels]candidateLevelInfo{}
    1504            1 :         for i := range candInfo {
    1505            1 :                 level := candInfo[i].level
    1506            1 :                 infoByLevel[level] = candInfo[i]
    1507            1 :         }
    1508              :         // Gather the compaction scores for the levels participating in the compaction.
    1509            1 :         pc.pickerMetrics.scores = make([]float64, len(pc.inputs))
    1510            1 :         inputIdx := 0
    1511            1 :         for i := range infoByLevel {
    1512            1 :                 if pc.inputs[inputIdx].level == infoByLevel[i].level {
    1513            1 :                         pc.pickerMetrics.scores[inputIdx] = infoByLevel[i].score
    1514            1 :                         inputIdx++
    1515            1 :                 }
    1516            1 :                 if inputIdx == len(pc.inputs) {
    1517            1 :                         break
    1518              :                 }
    1519              :         }
    1520              : }
    1521              : 
    1522              : // elisionOnlyAnnotator is a manifest.Annotator that annotates B-Tree
    1523              : // nodes with the *fileMetadata of a file meeting the obsolete keys criteria
    1524              : // for an elision-only compaction within the subtree. If multiple files meet
    1525              : // the criteria, it chooses whichever file has the lowest LargestSeqNum. The
    1526              : // lowest LargestSeqNum file will be the first eligible for an elision-only
    1527              : // compaction once snapshots less than or equal to its LargestSeqNum are closed.
    1528              : var elisionOnlyAnnotator = &manifest.Annotator[manifest.TableMetadata]{
    1529              :         Aggregator: manifest.PickFileAggregator{
    1530            1 :                 Filter: func(f *manifest.TableMetadata) (eligible bool, cacheOK bool) {
    1531            1 :                         if f.IsCompacting() {
    1532            1 :                                 return false, true
    1533            1 :                         }
    1534            1 :                         if !f.StatsValid() {
    1535            1 :                                 return false, false
    1536            1 :                         }
    1537              :                         // Bottommost files are large and not worthwhile to compact just
    1538              :                         // to remove a few tombstones. Consider a file eligible only if
    1539              :                         // either its own range deletions delete at least 10% of its data or
    1540              :                         // its deletion tombstones make at least 10% of its entries.
    1541              :                         //
    1542              :                         // TODO(jackson): This does not account for duplicate user keys
    1543              :                         // which may be collapsed. Ideally, we would have 'obsolete keys'
    1544              :                         // statistics that would include tombstones, the keys that are
    1545              :                         // dropped by tombstones and duplicated user keys. See #847.
    1546              :                         //
    1547              :                         // Note that tables that contain exclusively range keys (i.e. no point keys,
    1548              :                         // `NumEntries` and `RangeDeletionsBytesEstimate` are both zero) are excluded
    1549              :                         // from elision-only compactions.
    1550              :                         // TODO(travers): Consider an alternative heuristic for elision of range-keys.
    1551            1 :                         return f.Stats.RangeDeletionsBytesEstimate*10 >= f.Size || f.Stats.NumDeletions*10 > f.Stats.NumEntries, true
    1552              :                 },
    1553            1 :                 Compare: func(f1 *manifest.TableMetadata, f2 *manifest.TableMetadata) bool {
    1554            1 :                         return f1.LargestSeqNum < f2.LargestSeqNum
    1555            1 :                 },
    1556              :         },
    1557              : }
    1558              : 
    1559              : // markedForCompactionAnnotator is a manifest.Annotator that annotates B-Tree
    1560              : // nodes with the *fileMetadata of a file that is marked for compaction
    1561              : // within the subtree. If multiple files meet the criteria, it chooses
    1562              : // whichever file has the lowest LargestSeqNum.
    1563              : var markedForCompactionAnnotator = &manifest.Annotator[manifest.TableMetadata]{
    1564              :         Aggregator: manifest.PickFileAggregator{
    1565            0 :                 Filter: func(f *manifest.TableMetadata) (eligible bool, cacheOK bool) {
    1566            0 :                         return f.MarkedForCompaction, true
    1567            0 :                 },
    1568            0 :                 Compare: func(f1 *manifest.TableMetadata, f2 *manifest.TableMetadata) bool {
    1569            0 :                         return f1.LargestSeqNum < f2.LargestSeqNum
    1570            0 :                 },
    1571              :         },
    1572              : }
    1573              : 
    1574              : // pickedCompactionFromCandidateFile creates a pickedCompaction from a *fileMetadata
    1575              : // with various checks to ensure that the file still exists in the expected level
    1576              : // and isn't already being compacted.
    1577              : func (p *compactionPickerByScore) pickedCompactionFromCandidateFile(
    1578              :         candidate *manifest.TableMetadata,
    1579              :         env compactionEnv,
    1580              :         startLevel int,
    1581              :         outputLevel int,
    1582              :         kind compactionKind,
    1583            1 : ) *pickedTableCompaction {
    1584            1 :         if candidate == nil || candidate.IsCompacting() {
    1585            1 :                 return nil
    1586            1 :         }
    1587              : 
    1588            1 :         var inputs manifest.LevelSlice
    1589            1 :         if startLevel == 0 {
    1590            1 :                 // Overlapping L0 files must also be compacted alongside the candidate.
    1591            1 :                 inputs = p.vers.Overlaps(0, candidate.UserKeyBounds())
    1592            1 :         } else {
    1593            1 :                 inputs = p.vers.Levels[startLevel].Find(p.opts.Comparer.Compare, candidate)
    1594            1 :         }
    1595            1 :         if invariants.Enabled {
    1596            1 :                 found := false
    1597            1 :                 for f := range inputs.All() {
    1598            1 :                         if f.TableNum == candidate.TableNum {
    1599            1 :                                 found = true
    1600            1 :                         }
    1601              :                 }
    1602            1 :                 if !found {
    1603            0 :                         panic(fmt.Sprintf("file %s not found in level %d as expected", candidate.TableNum, startLevel))
    1604              :                 }
    1605              :         }
    1606              : 
    1607            1 :         pc := newPickedTableCompaction(p.opts, p.vers, p.latestVersionState.l0Organizer,
    1608            1 :                 startLevel, outputLevel, p.baseLevel)
    1609            1 :         pc.kind = kind
    1610            1 :         pc.startLevel.files = inputs
    1611            1 : 
    1612            1 :         if !pc.setupInputs(p.opts, env.diskAvailBytes, env.inProgressCompactions, pc.startLevel, env.problemSpans) {
    1613            1 :                 return nil
    1614            1 :         }
    1615            1 :         return pc
    1616              : }
    1617              : 
    1618              : // pickElisionOnlyCompaction looks for compactions of sstables in the
    1619              : // bottommost level containing obsolete records that may now be dropped.
    1620              : func (p *compactionPickerByScore) pickElisionOnlyCompaction(
    1621              :         env compactionEnv,
    1622            1 : ) (pc *pickedTableCompaction) {
    1623            1 :         if p.opts.private.disableElisionOnlyCompactions {
    1624            1 :                 return nil
    1625            1 :         }
    1626            1 :         candidate := elisionOnlyAnnotator.LevelAnnotation(p.vers.Levels[numLevels-1])
    1627            1 :         if candidate == nil {
    1628            1 :                 return nil
    1629            1 :         }
    1630            1 :         if candidate.LargestSeqNum >= env.earliestSnapshotSeqNum {
    1631            1 :                 return nil
    1632            1 :         }
    1633            1 :         return p.pickedCompactionFromCandidateFile(candidate, env, numLevels-1, numLevels-1, compactionKindElisionOnly)
    1634              : }
    1635              : 
    1636              : // pickRewriteCompaction attempts to construct a compaction that
    1637              : // rewrites a file marked for compaction. pickRewriteCompaction will
    1638              : // pull in adjacent files in the file's atomic compaction unit if
    1639              : // necessary. A rewrite compaction outputs files to the same level as
    1640              : // the input level.
    1641              : func (p *compactionPickerByScore) pickRewriteCompaction(
    1642              :         env compactionEnv,
    1643            0 : ) (pc *pickedTableCompaction) {
    1644            0 :         if p.vers.Stats.MarkedForCompaction == 0 {
    1645            0 :                 return nil
    1646            0 :         }
    1647            0 :         for l := numLevels - 1; l >= 0; l-- {
    1648            0 :                 candidate := markedForCompactionAnnotator.LevelAnnotation(p.vers.Levels[l])
    1649            0 :                 if candidate == nil {
    1650            0 :                         // Try the next level.
    1651            0 :                         continue
    1652              :                 }
    1653            0 :                 pc := p.pickedCompactionFromCandidateFile(candidate, env, l, l, compactionKindRewrite)
    1654            0 :                 if pc != nil {
    1655            0 :                         return pc
    1656            0 :                 }
    1657              :         }
    1658            0 :         return nil
    1659              : }
    1660              : 
    1661              : // pickBlobFileRewriteCompaction looks for compactions of blob files that
    1662              : // can be rewritten to reclaim disk space.
    1663              : func (p *compactionPickerByScore) pickBlobFileRewriteCompaction(
    1664              :         env compactionEnv,
    1665            1 : ) (pc *pickedBlobFileCompaction) {
    1666            1 :         aggregateStats, heuristicStats := p.latestVersionState.blobFiles.Stats()
    1667            1 :         if heuristicStats.CountFilesEligible == 0 && heuristicStats.CountFilesTooRecent == 0 {
    1668            1 :                 // No blob files with any garbage to rewrite.
    1669            1 :                 return nil
    1670            1 :         }
    1671            1 :         policy := p.opts.Experimental.ValueSeparationPolicy()
    1672            1 :         if policy.TargetGarbageRatio >= 1.0 {
    1673            1 :                 // Blob file rewrite compactions are disabled.
    1674            1 :                 return nil
    1675            1 :         }
    1676            1 :         garbagePct := float64(aggregateStats.ValueSize-aggregateStats.ReferencedValueSize) /
    1677            1 :                 float64(aggregateStats.ValueSize)
    1678            1 :         if garbagePct <= policy.TargetGarbageRatio {
    1679            1 :                 // Not enough garbage to warrant a rewrite compaction.
    1680            1 :                 return nil
    1681            1 :         }
    1682              : 
    1683              :         // Check if there is an ongoing blob file rewrite compaction. If there is,
    1684              :         // don't schedule a new one.
    1685            1 :         for _, c := range env.inProgressCompactions {
    1686            1 :                 if c.kind == compactionKindBlobFileRewrite {
    1687            1 :                         return nil
    1688            1 :                 }
    1689              :         }
    1690              : 
    1691            1 :         candidate, ok := p.latestVersionState.blobFiles.ReplacementCandidate()
    1692            1 :         if !ok {
    1693            1 :                 // None meet the heuristic.
    1694            1 :                 return nil
    1695            1 :         }
    1696            1 :         return &pickedBlobFileCompaction{
    1697            1 :                 vers:              p.vers,
    1698            1 :                 file:              candidate,
    1699            1 :                 referencingTables: p.latestVersionState.blobFiles.ReferencingTables(candidate.FileID),
    1700            1 :         }
    1701              : }
    1702              : 
    1703              : // pickTombstoneDensityCompaction looks for a compaction that eliminates
    1704              : // regions of extremely high point tombstone density. For each level, it picks
    1705              : // a file where the ratio of tombstone-dense blocks is at least
    1706              : // options.Experimental.MinTombstoneDenseRatio, prioritizing compaction of
    1707              : // files with higher ratios of tombstone-dense blocks.
    1708              : func (p *compactionPickerByScore) pickTombstoneDensityCompaction(
    1709              :         env compactionEnv,
    1710            1 : ) (pc *pickedTableCompaction) {
    1711            1 :         if p.opts.Experimental.TombstoneDenseCompactionThreshold <= 0 {
    1712            0 :                 // Tombstone density compactions are disabled.
    1713            0 :                 return nil
    1714            0 :         }
    1715              : 
    1716            1 :         var candidate *manifest.TableMetadata
    1717            1 :         var level int
    1718            1 :         // If a candidate file has a very high overlapping ratio, point tombstones
    1719            1 :         // in it are likely sparse in keyspace even if the sstable itself is tombstone
    1720            1 :         // dense. These tombstones likely wouldn't be slow to iterate over, so we exclude
    1721            1 :         // these files from tombstone density compactions. The threshold of 40.0 is
    1722            1 :         // chosen somewhat arbitrarily, after some observations around excessively large
    1723            1 :         // tombstone density compactions.
    1724            1 :         const maxOverlappingRatio = 40.0
    1725            1 :         // NB: we don't consider the lowest level because elision-only compactions
    1726            1 :         // handle that case.
    1727            1 :         lastNonEmptyLevel := numLevels - 1
    1728            1 :         for l := numLevels - 2; l >= 0; l-- {
    1729            1 :                 iter := p.vers.Levels[l].Iter()
    1730            1 :                 for f := iter.First(); f != nil; f = iter.Next() {
    1731            1 :                         if f.IsCompacting() || !f.StatsValid() || f.Size == 0 {
    1732            1 :                                 continue
    1733              :                         }
    1734            1 :                         if f.Stats.TombstoneDenseBlocksRatio < p.opts.Experimental.TombstoneDenseCompactionThreshold {
    1735            1 :                                 continue
    1736              :                         }
    1737            1 :                         overlaps := p.vers.Overlaps(lastNonEmptyLevel, f.UserKeyBounds())
    1738            1 :                         if float64(overlaps.AggregateSizeSum())/float64(f.Size) > maxOverlappingRatio {
    1739            0 :                                 continue
    1740              :                         }
    1741            1 :                         if candidate == nil || candidate.Stats.TombstoneDenseBlocksRatio < f.Stats.TombstoneDenseBlocksRatio {
    1742            1 :                                 candidate = f
    1743            1 :                                 level = l
    1744            1 :                         }
    1745              :                 }
    1746              :                 // We prefer lower level (ie. L5) candidates over higher level (ie. L4) ones.
    1747            1 :                 if candidate != nil {
    1748            1 :                         break
    1749              :                 }
    1750            1 :                 if !p.vers.Levels[l].Empty() {
    1751            1 :                         lastNonEmptyLevel = l
    1752            1 :                 }
    1753              :         }
    1754              : 
    1755            1 :         return p.pickedCompactionFromCandidateFile(candidate, env, level, defaultOutputLevel(level, p.baseLevel), compactionKindTombstoneDensity)
    1756              : }
    1757              : 
    1758              : // pickAutoLPositive picks an automatic compaction for the candidate
    1759              : // file in a positive-numbered level. This function must not be used for
    1760              : // L0.
    1761              : func pickAutoLPositive(
    1762              :         env compactionEnv,
    1763              :         opts *Options,
    1764              :         vers *manifest.Version,
    1765              :         l0Organizer *manifest.L0Organizer,
    1766              :         cInfo candidateLevelInfo,
    1767              :         baseLevel int,
    1768            1 : ) (pc *pickedTableCompaction) {
    1769            1 :         if cInfo.level == 0 {
    1770            0 :                 panic("pebble: pickAutoLPositive called for L0")
    1771              :         }
    1772              : 
    1773            1 :         pc = newPickedTableCompaction(opts, vers, l0Organizer, cInfo.level, defaultOutputLevel(cInfo.level, baseLevel), baseLevel)
    1774            1 :         if pc.outputLevel.level != cInfo.outputLevel {
    1775            0 :                 panic("pebble: compaction picked unexpected output level")
    1776              :         }
    1777            1 :         pc.startLevel.files = cInfo.file.Slice()
    1778            1 : 
    1779            1 :         if !pc.setupInputs(opts, env.diskAvailBytes, env.inProgressCompactions, pc.startLevel, env.problemSpans) {
    1780            1 :                 return nil
    1781            1 :         }
    1782            1 :         return pc.maybeAddLevel(opts, env)
    1783              : }
    1784              : 
    1785              : // maybeAddLevel maybe adds a level to the picked compaction.
    1786              : func (pc *pickedTableCompaction) maybeAddLevel(
    1787              :         opts *Options, env compactionEnv,
    1788            1 : ) *pickedTableCompaction {
    1789            1 :         pc.pickerMetrics.singleLevelOverlappingRatio = pc.overlappingRatio()
    1790            1 :         if pc.outputLevel.level == numLevels-1 {
    1791            1 :                 // Don't add a level if the current output level is in L6.
    1792            1 :                 return pc
    1793            1 :         }
    1794            1 :         if !opts.Experimental.MultiLevelCompactionHeuristic.allowL0() && pc.startLevel.level == 0 {
    1795            1 :                 return pc
    1796            1 :         }
    1797            1 :         targetFileSize := opts.TargetFileSize(pc.outputLevel.level, pc.baseLevel)
    1798            1 :         if pc.estimatedInputSize() > expandedCompactionByteSizeLimit(opts, targetFileSize, env.diskAvailBytes) {
    1799            0 :                 // Don't add a level if the current compaction exceeds the compaction size limit
    1800            0 :                 return pc
    1801            0 :         }
    1802            1 :         return opts.Experimental.MultiLevelCompactionHeuristic.pick(pc, opts, env)
    1803              : }
    1804              : 
    1805              : // MultiLevelHeuristic evaluates whether to add files from the next level into the compaction.
    1806              : type MultiLevelHeuristic interface {
    1807              :         // Evaluate returns the preferred compaction.
    1808              :         pick(pc *pickedTableCompaction, opts *Options, env compactionEnv) *pickedTableCompaction
    1809              : 
    1810              :         // Returns if the heuristic allows L0 to be involved in ML compaction
    1811              :         allowL0() bool
    1812              : 
    1813              :         // String implements fmt.Stringer.
    1814              :         String() string
    1815              : }
    1816              : 
    1817              : // NoMultiLevel will never add an additional level to the compaction.
    1818              : type NoMultiLevel struct{}
    1819              : 
    1820              : var _ MultiLevelHeuristic = (*NoMultiLevel)(nil)
    1821              : 
    1822              : func (nml NoMultiLevel) pick(
    1823              :         pc *pickedTableCompaction, opts *Options, env compactionEnv,
    1824            1 : ) *pickedTableCompaction {
    1825            1 :         return pc
    1826            1 : }
    1827              : 
    1828            1 : func (nml NoMultiLevel) allowL0() bool  { return false }
    1829            1 : func (nml NoMultiLevel) String() string { return "none" }
    1830              : 
    1831            1 : func (pc *pickedTableCompaction) predictedWriteAmp() float64 {
    1832            1 :         var bytesToCompact uint64
    1833            1 :         var higherLevelBytes uint64
    1834            1 :         for i := range pc.inputs {
    1835            1 :                 levelSize := pc.inputs[i].files.AggregateSizeSum()
    1836            1 :                 bytesToCompact += levelSize
    1837            1 :                 if i != len(pc.inputs)-1 {
    1838            1 :                         higherLevelBytes += levelSize
    1839            1 :                 }
    1840              :         }
    1841            1 :         return float64(bytesToCompact) / float64(higherLevelBytes)
    1842              : }
    1843              : 
    1844            1 : func (pc *pickedTableCompaction) overlappingRatio() float64 {
    1845            1 :         var higherLevelBytes uint64
    1846            1 :         var lowestLevelBytes uint64
    1847            1 :         for i := range pc.inputs {
    1848            1 :                 levelSize := pc.inputs[i].files.AggregateSizeSum()
    1849            1 :                 if i == len(pc.inputs)-1 {
    1850            1 :                         lowestLevelBytes += levelSize
    1851            1 :                         continue
    1852              :                 }
    1853            1 :                 higherLevelBytes += levelSize
    1854              :         }
    1855            1 :         return float64(lowestLevelBytes) / float64(higherLevelBytes)
    1856              : }
    1857              : 
    1858              : // WriteAmpHeuristic defines a multi level compaction heuristic which will add
    1859              : // an additional level to the picked compaction if it reduces predicted write
    1860              : // amp of the compaction + the addPropensity constant.
    1861              : type WriteAmpHeuristic struct {
    1862              :         // addPropensity is a constant that affects the propensity to conduct multilevel
    1863              :         // compactions. If positive, a multilevel compaction may get picked even if
    1864              :         // the single level compaction has lower write amp, and vice versa.
    1865              :         AddPropensity float64
    1866              : 
    1867              :         // AllowL0 if true, allow l0 to be involved in a ML compaction.
    1868              :         AllowL0 bool
    1869              : }
    1870              : 
    1871              : var _ MultiLevelHeuristic = (*WriteAmpHeuristic)(nil)
    1872              : 
    1873              : // TODO(msbutler): microbenchmark the extent to which multilevel compaction
    1874              : // picking slows down the compaction picking process.  This should be as fast as
    1875              : // possible since Compaction-picking holds d.mu, which prevents WAL rotations,
    1876              : // in-progress flushes and compactions from completing, etc. Consider ways to
    1877              : // deduplicate work, given that setupInputs has already been called.
    1878              : func (wa WriteAmpHeuristic) pick(
    1879              :         pcOrig *pickedTableCompaction, opts *Options, env compactionEnv,
    1880            1 : ) *pickedTableCompaction {
    1881            1 :         pcMulti := pcOrig.clone()
    1882            1 :         if !pcMulti.setupMultiLevelCandidate(opts, env) {
    1883            1 :                 return pcOrig
    1884            1 :         }
    1885              :         // We consider the addition of a level as an "expansion" of the compaction.
    1886              :         // If pcMulti is past the expanded compaction byte size limit already,
    1887              :         // we don't consider it.
    1888            1 :         targetFileSize := opts.TargetFileSize(pcMulti.outputLevel.level, pcMulti.baseLevel)
    1889            1 :         if pcMulti.estimatedInputSize() >= expandedCompactionByteSizeLimit(opts, targetFileSize, env.diskAvailBytes) {
    1890            0 :                 return pcOrig
    1891            0 :         }
    1892            1 :         picked := pcOrig
    1893            1 :         if pcMulti.predictedWriteAmp() <= pcOrig.predictedWriteAmp()+wa.AddPropensity {
    1894            1 :                 picked = pcMulti
    1895            1 :         }
    1896              :         // Regardless of what compaction was picked, log the multilevelOverlapping ratio.
    1897            1 :         picked.pickerMetrics.multiLevelOverlappingRatio = pcMulti.overlappingRatio()
    1898            1 :         return picked
    1899              : }
    1900              : 
    1901            1 : func (wa WriteAmpHeuristic) allowL0() bool {
    1902            1 :         return wa.AllowL0
    1903            1 : }
    1904              : 
    1905              : // String implements fmt.Stringer.
    1906            1 : func (wa WriteAmpHeuristic) String() string {
    1907            1 :         return fmt.Sprintf("wamp(%.2f, %t)", wa.AddPropensity, wa.AllowL0)
    1908            1 : }
    1909              : 
    1910              : // Helper method to pick compactions originating from L0. Uses information about
    1911              : // sublevels to generate a compaction.
    1912              : func pickL0(
    1913              :         env compactionEnv,
    1914              :         opts *Options,
    1915              :         vers *manifest.Version,
    1916              :         l0Organizer *manifest.L0Organizer,
    1917              :         baseLevel int,
    1918            1 : ) *pickedTableCompaction {
    1919            1 :         // It is important to pass information about Lbase files to L0Sublevels
    1920            1 :         // so it can pick a compaction that does not conflict with an Lbase => Lbase+1
    1921            1 :         // compaction. Without this, we observed reduced concurrency of L0=>Lbase
    1922            1 :         // compactions, and increasing read amplification in L0.
    1923            1 :         //
    1924            1 :         // TODO(bilal) Remove the minCompactionDepth parameter once fixing it at 1
    1925            1 :         // has been shown to not cause a performance regression.
    1926            1 :         lcf := l0Organizer.PickBaseCompaction(opts.Logger, 1, vers.Levels[baseLevel].Slice(), baseLevel, env.problemSpans)
    1927            1 :         if lcf != nil {
    1928            1 :                 pc := newPickedCompactionFromL0(lcf, opts, vers, l0Organizer, baseLevel, true)
    1929            1 :                 if pc.setupInputs(opts, env.diskAvailBytes, env.inProgressCompactions, pc.startLevel, env.problemSpans) {
    1930            1 :                         if pc.startLevel.files.Empty() {
    1931            0 :                                 opts.Logger.Errorf("%v", base.AssertionFailedf("empty compaction chosen"))
    1932            0 :                         }
    1933            1 :                         return pc.maybeAddLevel(opts, env)
    1934              :                 }
    1935              :                 // TODO(radu): investigate why this happens.
    1936              :                 // opts.Logger.Errorf("%v", base.AssertionFailedf("setupInputs failed"))
    1937              :         }
    1938              : 
    1939              :         // Couldn't choose a base compaction. Try choosing an intra-L0
    1940              :         // compaction. Note that we pass in L0CompactionThreshold here as opposed to
    1941              :         // 1, since choosing a single sublevel intra-L0 compaction is
    1942              :         // counterproductive.
    1943            1 :         lcf = l0Organizer.PickIntraL0Compaction(env.earliestUnflushedSeqNum, minIntraL0Count, env.problemSpans)
    1944            1 :         if lcf != nil {
    1945            1 :                 pc := newPickedCompactionFromL0(lcf, opts, vers, l0Organizer, baseLevel, false)
    1946            1 :                 if pc.setupInputs(opts, env.diskAvailBytes, env.inProgressCompactions, pc.startLevel, env.problemSpans) {
    1947            1 :                         if pc.startLevel.files.Empty() {
    1948            0 :                                 opts.Logger.Fatalf("empty compaction chosen")
    1949            0 :                         }
    1950              :                         // A single-file intra-L0 compaction is unproductive.
    1951            1 :                         if iter := pc.startLevel.files.Iter(); iter.First() != nil && iter.Next() != nil {
    1952            1 :                                 pc.bounds = manifest.KeyRange(opts.Comparer.Compare, pc.startLevel.files.All())
    1953            1 :                                 return pc
    1954            1 :                         }
    1955            0 :                 } else {
    1956            0 :                         // TODO(radu): investigate why this happens.
    1957            0 :                         // opts.Logger.Errorf("%v", base.AssertionFailedf("setupInputs failed"))
    1958            0 :                 }
    1959              :         }
    1960            1 :         return nil
    1961              : }
    1962              : 
    1963              : func newPickedManualCompaction(
    1964              :         vers *manifest.Version,
    1965              :         l0Organizer *manifest.L0Organizer,
    1966              :         opts *Options,
    1967              :         env compactionEnv,
    1968              :         baseLevel int,
    1969              :         manual *manualCompaction,
    1970            1 : ) (pc *pickedTableCompaction, retryLater bool) {
    1971            1 :         outputLevel := manual.level + 1
    1972            1 :         if manual.level == 0 {
    1973            1 :                 outputLevel = baseLevel
    1974            1 :         } else if manual.level < baseLevel {
    1975            1 :                 // The start level for a compaction must be >= Lbase. A manual
    1976            1 :                 // compaction could have been created adhering to that condition, and
    1977            1 :                 // then an automatic compaction came in and compacted all of the
    1978            1 :                 // sstables in Lbase to Lbase+1 which caused Lbase to change. Simply
    1979            1 :                 // ignore this manual compaction as there is nothing to do (manual.level
    1980            1 :                 // points to an empty level).
    1981            1 :                 return nil, false
    1982            1 :         }
    1983              :         // This conflictsWithInProgress call is necessary for the manual compaction to
    1984              :         // be retried when it conflicts with an ongoing automatic compaction. Without
    1985              :         // it, the compaction is dropped due to pc.setupInputs returning false since
    1986              :         // the input/output range is already being compacted, and the manual
    1987              :         // compaction ends with a non-compacted LSM.
    1988            1 :         if conflictsWithInProgress(manual, outputLevel, env.inProgressCompactions, opts.Comparer.Compare) {
    1989            1 :                 return nil, true
    1990            1 :         }
    1991            1 :         pc = newPickedTableCompaction(opts, vers, l0Organizer, manual.level, defaultOutputLevel(manual.level, baseLevel), baseLevel)
    1992            1 :         pc.manualID = manual.id
    1993            1 :         manual.outputLevel = pc.outputLevel.level
    1994            1 :         pc.startLevel.files = vers.Overlaps(manual.level, base.UserKeyBoundsInclusive(manual.start, manual.end))
    1995            1 :         if pc.startLevel.files.Empty() {
    1996            1 :                 // Nothing to do
    1997            1 :                 return nil, false
    1998            1 :         }
    1999              :         // We use nil problemSpans because we don't want problem spans to prevent
    2000              :         // manual compactions.
    2001            1 :         if !pc.setupInputs(opts, env.diskAvailBytes, env.inProgressCompactions, pc.startLevel, nil /* problemSpans */) {
    2002            1 :                 // setupInputs returned false indicating there's a conflicting
    2003            1 :                 // concurrent compaction.
    2004            1 :                 return nil, true
    2005            1 :         }
    2006            1 :         if pc = pc.maybeAddLevel(opts, env); pc == nil {
    2007            0 :                 return nil, false
    2008            0 :         }
    2009            1 :         if pc.outputLevel.level != outputLevel {
    2010            1 :                 if len(pc.inputs) > 2 {
    2011            1 :                         // Multilevel compactions relax this invariant.
    2012            1 :                 } else {
    2013            0 :                         panic("pebble: compaction picked unexpected output level")
    2014              :                 }
    2015              :         }
    2016            1 :         return pc, false
    2017              : }
    2018              : 
    2019              : // pickDownloadCompaction picks a download compaction for the downloadSpan,
    2020              : // which could be specified as being performed either by a copy compaction of
    2021              : // the backing file or a rewrite compaction.
    2022              : func pickDownloadCompaction(
    2023              :         vers *manifest.Version,
    2024              :         l0Organizer *manifest.L0Organizer,
    2025              :         opts *Options,
    2026              :         env compactionEnv,
    2027              :         baseLevel int,
    2028              :         kind compactionKind,
    2029              :         level int,
    2030              :         file *manifest.TableMetadata,
    2031            1 : ) (pc *pickedTableCompaction) {
    2032            1 :         // Check if the file is compacting already.
    2033            1 :         if file.CompactionState == manifest.CompactionStateCompacting {
    2034            0 :                 return nil
    2035            0 :         }
    2036            1 :         if kind != compactionKindCopy && kind != compactionKindRewrite {
    2037            0 :                 panic("invalid download/rewrite compaction kind")
    2038              :         }
    2039            1 :         pc = newPickedTableCompaction(opts, vers, l0Organizer, level, level, baseLevel)
    2040            1 :         pc.kind = kind
    2041            1 :         pc.startLevel.files = manifest.NewLevelSliceKeySorted(opts.Comparer.Compare, []*manifest.TableMetadata{file})
    2042            1 :         if !pc.setupInputs(opts, env.diskAvailBytes, env.inProgressCompactions, pc.startLevel, nil /* problemSpans */) {
    2043            0 :                 // setupInputs returned false indicating there's a conflicting
    2044            0 :                 // concurrent compaction.
    2045            0 :                 return nil
    2046            0 :         }
    2047            1 :         if pc.outputLevel.level != level {
    2048            0 :                 panic("pebble: download compaction picked unexpected output level")
    2049              :         }
    2050            1 :         return pc
    2051              : }
    2052              : 
    2053              : func (p *compactionPickerByScore) pickReadTriggeredCompaction(
    2054              :         env compactionEnv,
    2055            1 : ) (pc *pickedTableCompaction) {
    2056            1 :         // If a flush is in-progress or expected to happen soon, it means more writes are taking place. We would
    2057            1 :         // soon be scheduling more write focussed compactions. In this case, skip read compactions as they are
    2058            1 :         // lower priority.
    2059            1 :         if env.readCompactionEnv.flushing || env.readCompactionEnv.readCompactions == nil {
    2060            1 :                 return nil
    2061            1 :         }
    2062            1 :         for env.readCompactionEnv.readCompactions.size > 0 {
    2063            0 :                 rc := env.readCompactionEnv.readCompactions.remove()
    2064            0 :                 if pc = pickReadTriggeredCompactionHelper(p, rc, env); pc != nil {
    2065            0 :                         break
    2066              :                 }
    2067              :         }
    2068            1 :         return pc
    2069              : }
    2070              : 
    2071              : func pickReadTriggeredCompactionHelper(
    2072              :         p *compactionPickerByScore, rc *readCompaction, env compactionEnv,
    2073            0 : ) (pc *pickedTableCompaction) {
    2074            0 :         overlapSlice := p.vers.Overlaps(rc.level, base.UserKeyBoundsInclusive(rc.start, rc.end))
    2075            0 :         var fileMatches bool
    2076            0 :         for f := range overlapSlice.All() {
    2077            0 :                 if f.TableNum == rc.tableNum {
    2078            0 :                         fileMatches = true
    2079            0 :                         break
    2080              :                 }
    2081              :         }
    2082            0 :         if !fileMatches {
    2083            0 :                 return nil
    2084            0 :         }
    2085              : 
    2086            0 :         pc = newPickedTableCompaction(p.opts, p.vers, p.latestVersionState.l0Organizer,
    2087            0 :                 rc.level, defaultOutputLevel(rc.level, p.baseLevel), p.baseLevel)
    2088            0 : 
    2089            0 :         pc.startLevel.files = overlapSlice
    2090            0 :         if !pc.setupInputs(p.opts, env.diskAvailBytes, env.inProgressCompactions, pc.startLevel, env.problemSpans) {
    2091            0 :                 return nil
    2092            0 :         }
    2093            0 :         pc.kind = compactionKindRead
    2094            0 : 
    2095            0 :         // Prevent read compactions which are too wide.
    2096            0 :         outputOverlaps := pc.version.Overlaps(pc.outputLevel.level, pc.bounds)
    2097            0 :         if outputOverlaps.AggregateSizeSum() > pc.maxReadCompactionBytes {
    2098            0 :                 return nil
    2099            0 :         }
    2100              : 
    2101              :         // Prevent compactions which start with a small seed file X, but overlap
    2102              :         // with over allowedCompactionWidth * X file sizes in the output layer.
    2103            0 :         const allowedCompactionWidth = 35
    2104            0 :         if outputOverlaps.AggregateSizeSum() > overlapSlice.AggregateSizeSum()*allowedCompactionWidth {
    2105            0 :                 return nil
    2106            0 :         }
    2107              : 
    2108            0 :         return pc
    2109              : }
    2110              : 
    2111            0 : func (p *compactionPickerByScore) forceBaseLevel1() {
    2112            0 :         p.baseLevel = 1
    2113            0 : }
    2114              : 
    2115              : // outputKeyRangeAlreadyCompacting checks if the input range of the picked
    2116              : // compaction is already being written to by an in-progress compaction.
    2117              : func outputKeyRangeAlreadyCompacting(
    2118              :         cmp base.Compare, inProgressCompactions []compactionInfo, pc *pickedTableCompaction,
    2119            1 : ) bool {
    2120            1 :         // Look for active compactions outputting to the same region of the key
    2121            1 :         // space in the same output level. Two potential compactions may conflict
    2122            1 :         // without sharing input files if there are no files in the output level
    2123            1 :         // that overlap with the intersection of the compactions' key spaces.
    2124            1 :         //
    2125            1 :         // Consider an active L0->Lbase compaction compacting two L0 files one
    2126            1 :         // [a-f] and the other [t-z] into Lbase.
    2127            1 :         //
    2128            1 :         // L0
    2129            1 :         //     ↦ 000100  ↤                           ↦  000101   ↤
    2130            1 :         // L1
    2131            1 :         //     ↦ 000004  ↤
    2132            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
    2133            1 :         //
    2134            1 :         // If a new file 000102 [j-p] is flushed while the existing compaction is
    2135            1 :         // still ongoing, new file would not be in any compacting sublevel
    2136            1 :         // intervals and would not overlap with any Lbase files that are also
    2137            1 :         // compacting. However, this compaction cannot be picked because the
    2138            1 :         // compaction's output key space [j-p] would overlap the existing
    2139            1 :         // compaction's output key space [a-z].
    2140            1 :         //
    2141            1 :         // L0
    2142            1 :         //     ↦ 000100* ↤       ↦   000102  ↤       ↦  000101*  ↤
    2143            1 :         // L1
    2144            1 :         //     ↦ 000004* ↤
    2145            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
    2146            1 :         //
    2147            1 :         // * - currently compacting
    2148            1 :         if pc.outputLevel != nil && pc.outputLevel.level != 0 {
    2149            1 :                 for _, c := range inProgressCompactions {
    2150            1 :                         if pc.outputLevel.level != c.outputLevel {
    2151            1 :                                 continue
    2152              :                         }
    2153            1 :                         if !c.bounds.Overlaps(cmp, &pc.bounds) {
    2154            1 :                                 continue
    2155              :                         }
    2156              :                         // The picked compaction and the in-progress compaction c are
    2157              :                         // outputting to the same region of the key space of the same
    2158              :                         // level.
    2159            1 :                         return true
    2160              :                 }
    2161              :         }
    2162            1 :         return false
    2163              : }
    2164              : 
    2165              : // conflictsWithInProgress checks if there are any in-progress compactions with overlapping keyspace.
    2166              : func conflictsWithInProgress(
    2167              :         manual *manualCompaction, outputLevel int, inProgressCompactions []compactionInfo, cmp Compare,
    2168            1 : ) bool {
    2169            1 :         for _, c := range inProgressCompactions {
    2170            1 :                 if (c.outputLevel == manual.level || c.outputLevel == outputLevel) &&
    2171            1 :                         areUserKeysOverlapping(manual.start, manual.end, c.bounds.Start, c.bounds.End.Key, cmp) {
    2172            1 :                         return true
    2173            1 :                 }
    2174            1 :                 for _, in := range c.inputs {
    2175            1 :                         if in.files.Empty() {
    2176            1 :                                 continue
    2177              :                         }
    2178            1 :                         iter := in.files.Iter()
    2179            1 :                         smallest := iter.First().Smallest().UserKey
    2180            1 :                         largest := iter.Last().Largest().UserKey
    2181            1 :                         if (in.level == manual.level || in.level == outputLevel) &&
    2182            1 :                                 areUserKeysOverlapping(manual.start, manual.end, smallest, largest, cmp) {
    2183            1 :                                 return true
    2184            1 :                         }
    2185              :                 }
    2186              :         }
    2187            1 :         return false
    2188              : }
    2189              : 
    2190            1 : func areUserKeysOverlapping(x1, x2, y1, y2 []byte, cmp Compare) bool {
    2191            1 :         return cmp(x1, y2) <= 0 && cmp(y1, x2) <= 0
    2192            1 : }
        

Generated by: LCOV version 2.0-1