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

Generated by: LCOV version 2.0-1