LCOV - code coverage report
Current view: top level - pebble - compaction.go (source / functions) Coverage Total Hit
Test: 2025-06-19 08:18Z 54bb06f3 - meta test only.lcov Lines: 88.9 % 2458 2184
Test Date: 2025-06-19 08:19:49 Functions: - 0 0

            Line data    Source code
       1              : // Copyright 2013 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              :         "context"
      10              :         "fmt"
      11              :         "iter"
      12              :         "math"
      13              :         "runtime/pprof"
      14              :         "slices"
      15              :         "sort"
      16              :         "sync/atomic"
      17              :         "time"
      18              :         "unsafe"
      19              : 
      20              :         "github.com/cockroachdb/crlib/crtime"
      21              :         "github.com/cockroachdb/errors"
      22              :         "github.com/cockroachdb/pebble/internal/base"
      23              :         "github.com/cockroachdb/pebble/internal/compact"
      24              :         "github.com/cockroachdb/pebble/internal/keyspan"
      25              :         "github.com/cockroachdb/pebble/internal/keyspan/keyspanimpl"
      26              :         "github.com/cockroachdb/pebble/internal/manifest"
      27              :         "github.com/cockroachdb/pebble/internal/sstableinternal"
      28              :         "github.com/cockroachdb/pebble/objstorage"
      29              :         "github.com/cockroachdb/pebble/objstorage/objstorageprovider/objiotracing"
      30              :         "github.com/cockroachdb/pebble/objstorage/remote"
      31              :         "github.com/cockroachdb/pebble/sstable"
      32              :         "github.com/cockroachdb/pebble/sstable/blob"
      33              :         "github.com/cockroachdb/pebble/sstable/block"
      34              :         "github.com/cockroachdb/pebble/vfs"
      35              : )
      36              : 
      37              : var errEmptyTable = errors.New("pebble: empty table")
      38              : 
      39              : // ErrCancelledCompaction is returned if a compaction is cancelled by a
      40              : // concurrent excise or ingest-split operation.
      41              : var ErrCancelledCompaction = errors.New("pebble: compaction cancelled by a concurrent operation, will retry compaction")
      42              : 
      43              : var flushLabels = pprof.Labels("pebble", "flush", "output-level", "L0")
      44              : var gcLabels = pprof.Labels("pebble", "gc")
      45              : 
      46              : // expandedCompactionByteSizeLimit is the maximum number of bytes in all
      47              : // compacted files. We avoid expanding the lower level file set of a compaction
      48              : // if it would make the total compaction cover more than this many bytes.
      49            1 : func expandedCompactionByteSizeLimit(opts *Options, level int, availBytes uint64) uint64 {
      50            1 :         v := uint64(25 * opts.Levels[level].TargetFileSize)
      51            1 : 
      52            1 :         // Never expand a compaction beyond half the available capacity, divided
      53            1 :         // by the maximum number of concurrent compactions. Each of the concurrent
      54            1 :         // compactions may expand up to this limit, so this attempts to limit
      55            1 :         // compactions to half of available disk space. Note that this will not
      56            1 :         // prevent compaction picking from pursuing compactions that are larger
      57            1 :         // than this threshold before expansion.
      58            1 :         //
      59            1 :         // NB: this heuristic is an approximation since we may run more compactions
      60            1 :         // than the upper concurrency limit.
      61            1 :         _, maxConcurrency := opts.CompactionConcurrencyRange()
      62            1 :         diskMax := (availBytes / 2) / uint64(maxConcurrency)
      63            1 :         if v > diskMax {
      64            0 :                 v = diskMax
      65            0 :         }
      66            1 :         return v
      67              : }
      68              : 
      69              : // maxGrandparentOverlapBytes is the maximum bytes of overlap with level+1
      70              : // before we stop building a single file in a level-1 to level compaction.
      71            1 : func maxGrandparentOverlapBytes(opts *Options, level int) uint64 {
      72            1 :         return uint64(10 * opts.Levels[level].TargetFileSize)
      73            1 : }
      74              : 
      75              : // maxReadCompactionBytes is used to prevent read compactions which
      76              : // are too wide.
      77            1 : func maxReadCompactionBytes(opts *Options, level int) uint64 {
      78            1 :         return uint64(10 * opts.Levels[level].TargetFileSize)
      79            1 : }
      80              : 
      81              : // noCloseIter wraps around a FragmentIterator, intercepting and eliding
      82              : // calls to Close. It is used during compaction to ensure that rangeDelIters
      83              : // are not closed prematurely.
      84              : type noCloseIter struct {
      85              :         keyspan.FragmentIterator
      86              : }
      87              : 
      88            1 : func (i *noCloseIter) Close() {}
      89              : 
      90              : type compactionLevel struct {
      91              :         level int
      92              :         files manifest.LevelSlice
      93              :         // l0SublevelInfo contains information about L0 sublevels being compacted.
      94              :         // It's only set for the start level of a compaction starting out of L0 and
      95              :         // is nil for all other compactions.
      96              :         l0SublevelInfo []sublevelInfo
      97              : }
      98              : 
      99            1 : func (cl compactionLevel) Clone() compactionLevel {
     100            1 :         newCL := compactionLevel{
     101            1 :                 level: cl.level,
     102            1 :                 files: cl.files,
     103            1 :         }
     104            1 :         return newCL
     105            1 : }
     106            0 : func (cl compactionLevel) String() string {
     107            0 :         return fmt.Sprintf(`Level %d, Files %s`, cl.level, cl.files)
     108            0 : }
     109              : 
     110              : // compactionWritable is a objstorage.Writable wrapper that, on every write,
     111              : // updates a metric in `versions` on bytes written by in-progress compactions so
     112              : // far. It also increments a per-compaction `written` atomic int.
     113              : type compactionWritable struct {
     114              :         objstorage.Writable
     115              : 
     116              :         versions *versionSet
     117              :         written  *atomic.Int64
     118              : }
     119              : 
     120              : // Write is part of the objstorage.Writable interface.
     121            1 : func (c *compactionWritable) Write(p []byte) error {
     122            1 :         if err := c.Writable.Write(p); err != nil {
     123            0 :                 return err
     124            0 :         }
     125              : 
     126            1 :         c.written.Add(int64(len(p)))
     127            1 :         c.versions.incrementCompactionBytes(int64(len(p)))
     128            1 :         return nil
     129              : }
     130              : 
     131              : type compactionKind int
     132              : 
     133              : const (
     134              :         compactionKindDefault compactionKind = iota
     135              :         compactionKindFlush
     136              :         // compactionKindMove denotes a move compaction where the input file is
     137              :         // retained and linked in a new level without being obsoleted.
     138              :         compactionKindMove
     139              :         // compactionKindCopy denotes a copy compaction where the input file is
     140              :         // copied byte-by-byte into a new file with a new TableNum in the output level.
     141              :         compactionKindCopy
     142              :         // compactionKindDeleteOnly denotes a compaction that only deletes input
     143              :         // files. It can occur when wide range tombstones completely contain sstables.
     144              :         compactionKindDeleteOnly
     145              :         compactionKindElisionOnly
     146              :         compactionKindRead
     147              :         compactionKindTombstoneDensity
     148              :         compactionKindRewrite
     149              :         compactionKindIngestedFlushable
     150              : )
     151              : 
     152            1 : func (k compactionKind) String() string {
     153            1 :         switch k {
     154            1 :         case compactionKindDefault:
     155            1 :                 return "default"
     156            0 :         case compactionKindFlush:
     157            0 :                 return "flush"
     158            1 :         case compactionKindMove:
     159            1 :                 return "move"
     160            1 :         case compactionKindDeleteOnly:
     161            1 :                 return "delete-only"
     162            1 :         case compactionKindElisionOnly:
     163            1 :                 return "elision-only"
     164            0 :         case compactionKindRead:
     165            0 :                 return "read"
     166            1 :         case compactionKindTombstoneDensity:
     167            1 :                 return "tombstone-density"
     168            1 :         case compactionKindRewrite:
     169            1 :                 return "rewrite"
     170            0 :         case compactionKindIngestedFlushable:
     171            0 :                 return "ingested-flushable"
     172            1 :         case compactionKindCopy:
     173            1 :                 return "copy"
     174              :         }
     175            0 :         return "?"
     176              : }
     177              : 
     178              : // compactingOrFlushing returns "flushing" if the compaction kind is a flush,
     179              : // otherwise it returns "compacting".
     180            1 : func (k compactionKind) compactingOrFlushing() string {
     181            1 :         if k == compactionKindFlush {
     182            1 :                 return "flushing"
     183            1 :         }
     184            1 :         return "compacting"
     185              : }
     186              : 
     187              : // compaction is a table compaction from one level to the next, starting from a
     188              : // given version.
     189              : type compaction struct {
     190              :         // cancel is a bool that can be used by other goroutines to signal a compaction
     191              :         // to cancel, such as if a conflicting excise operation raced it to manifest
     192              :         // application. Only holders of the manifest lock will write to this atomic.
     193              :         cancel atomic.Bool
     194              : 
     195              :         kind compactionKind
     196              :         // isDownload is true if this compaction was started as part of a Download
     197              :         // operation. In this case kind is compactionKindCopy or
     198              :         // compactionKindRewrite.
     199              :         isDownload bool
     200              : 
     201              :         cmp       Compare
     202              :         equal     Equal
     203              :         comparer  *base.Comparer
     204              :         formatKey base.FormatKey
     205              :         logger    Logger
     206              :         version   *manifest.Version
     207              :         stats     base.InternalIteratorStats
     208              :         beganAt   time.Time
     209              :         // versionEditApplied is set to true when a compaction has completed and the
     210              :         // resulting version has been installed (if successful), but the compaction
     211              :         // goroutine is still cleaning up (eg, deleting obsolete files).
     212              :         versionEditApplied bool
     213              :         bufferPool         sstable.BufferPool
     214              :         // getValueSeparation constructs a compact.ValueSeparation for use in a
     215              :         // compaction. It implements heuristics around choosing whether a compaction
     216              :         // should:
     217              :         //
     218              :         // a) preserve existing blob references: The compaction does not write any
     219              :         // new blob files, but propagates existing references to blob files.This
     220              :         // conserves write bandwidth by avoiding rewriting the referenced values. It
     221              :         // also reduces the locality of the referenced values which can reduce scan
     222              :         // performance because a scan must load values from more unique blob files.
     223              :         // It can also delay reclamation of disk space if some of the references to
     224              :         // blob values are elided by the compaction, increasing space amplification.
     225              :         //
     226              :         // b) rewrite blob files: The compaction will write eligible values to new
     227              :         // blob files. This consumes more write bandwidth because all values are
     228              :         // rewritten. However it restores locality.
     229              :         getValueSeparation func(JobID, *compaction, sstable.TableFormat) compact.ValueSeparation
     230              :         // valueFetcher is used to fetch values from blob files. It's propagated
     231              :         // down the iterator tree through the internal iterator options.
     232              :         valueFetcher blob.ValueFetcher
     233              : 
     234              :         // startLevel is the level that is being compacted. Inputs from startLevel
     235              :         // and outputLevel will be merged to produce a set of outputLevel files.
     236              :         startLevel *compactionLevel
     237              : 
     238              :         // outputLevel is the level that files are being produced in. outputLevel is
     239              :         // equal to startLevel+1 except when:
     240              :         //    - if startLevel is 0, the output level equals compactionPicker.baseLevel().
     241              :         //    - in multilevel compaction, the output level is the lowest level involved in
     242              :         //      the compaction
     243              :         // A compaction's outputLevel is nil for delete-only compactions.
     244              :         outputLevel *compactionLevel
     245              : 
     246              :         // extraLevels point to additional levels in between the input and output
     247              :         // levels that get compacted in multilevel compactions
     248              :         extraLevels []*compactionLevel
     249              : 
     250              :         inputs []compactionLevel
     251              : 
     252              :         // maxOutputFileSize is the maximum size of an individual table created
     253              :         // during compaction.
     254              :         maxOutputFileSize uint64
     255              :         // maxOverlapBytes is the maximum number of bytes of overlap allowed for a
     256              :         // single output table with the tables in the grandparent level.
     257              :         maxOverlapBytes uint64
     258              : 
     259              :         // flushing contains the flushables (aka memtables) that are being flushed.
     260              :         flushing flushableList
     261              :         // bytesWritten contains the number of bytes that have been written to outputs.
     262              :         bytesWritten atomic.Int64
     263              : 
     264              :         // The boundaries of the input data.
     265              :         smallest InternalKey
     266              :         largest  InternalKey
     267              : 
     268              :         // A list of fragment iterators to close when the compaction finishes. Used by
     269              :         // input iteration to keep rangeDelIters open for the lifetime of the
     270              :         // compaction, and only close them when the compaction finishes.
     271              :         closers []*noCloseIter
     272              : 
     273              :         // grandparents are the tables in level+2 that overlap with the files being
     274              :         // compacted. Used to determine output table boundaries. Do not assume that the actual files
     275              :         // in the grandparent when this compaction finishes will be the same.
     276              :         grandparents manifest.LevelSlice
     277              : 
     278              :         // Boundaries at which flushes to L0 should be split. Determined by
     279              :         // L0Sublevels. If nil, flushes aren't split.
     280              :         l0Limits [][]byte
     281              : 
     282              :         delElision      compact.TombstoneElision
     283              :         rangeKeyElision compact.TombstoneElision
     284              : 
     285              :         // allowedZeroSeqNum is true if seqnums can be zeroed if there are no
     286              :         // snapshots requiring them to be kept. This determination is made by
     287              :         // looking for an sstable which overlaps the bounds of the compaction at a
     288              :         // lower level in the LSM during runCompaction.
     289              :         allowedZeroSeqNum bool
     290              : 
     291              :         // deletionHints are set if this is a compactionKindDeleteOnly. Used to figure
     292              :         // out whether an input must be deleted in its entirety, or excised into
     293              :         // virtual sstables.
     294              :         deletionHints []deleteCompactionHint
     295              : 
     296              :         // exciseEnabled is set to true if this is a compactionKindDeleteOnly and
     297              :         // this compaction is allowed to excise files.
     298              :         exciseEnabled bool
     299              : 
     300              :         metrics levelMetricsDelta
     301              : 
     302              :         pickerMetrics pickedCompactionMetrics
     303              : 
     304              :         grantHandle CompactionGrantHandle
     305              : 
     306              :         tableFormat   sstable.TableFormat
     307              :         objCreateOpts objstorage.CreateOptions
     308              : }
     309              : 
     310              : // inputLargestSeqNumAbsolute returns the maximum LargestSeqNumAbsolute of any
     311              : // input sstables.
     312            1 : func (c *compaction) inputLargestSeqNumAbsolute() base.SeqNum {
     313            1 :         var seqNum base.SeqNum
     314            1 :         for _, cl := range c.inputs {
     315            1 :                 for m := range cl.files.All() {
     316            1 :                         seqNum = max(seqNum, m.LargestSeqNumAbsolute)
     317            1 :                 }
     318              :         }
     319            1 :         return seqNum
     320              : }
     321              : 
     322            1 : func (c *compaction) makeInfo(jobID JobID) CompactionInfo {
     323            1 :         info := CompactionInfo{
     324            1 :                 JobID:       int(jobID),
     325            1 :                 Reason:      c.kind.String(),
     326            1 :                 Input:       make([]LevelInfo, 0, len(c.inputs)),
     327            1 :                 Annotations: []string{},
     328            1 :         }
     329            1 :         if c.isDownload {
     330            1 :                 info.Reason = "download," + info.Reason
     331            1 :         }
     332            1 :         for _, cl := range c.inputs {
     333            1 :                 inputInfo := LevelInfo{Level: cl.level, Tables: nil}
     334            1 :                 for m := range cl.files.All() {
     335            1 :                         inputInfo.Tables = append(inputInfo.Tables, m.TableInfo())
     336            1 :                 }
     337            1 :                 info.Input = append(info.Input, inputInfo)
     338              :         }
     339            1 :         if c.outputLevel != nil {
     340            1 :                 info.Output.Level = c.outputLevel.level
     341            1 : 
     342            1 :                 // If there are no inputs from the output level (eg, a move
     343            1 :                 // compaction), add an empty LevelInfo to info.Input.
     344            1 :                 if len(c.inputs) > 0 && c.inputs[len(c.inputs)-1].level != c.outputLevel.level {
     345            0 :                         info.Input = append(info.Input, LevelInfo{Level: c.outputLevel.level})
     346            0 :                 }
     347            1 :         } else {
     348            1 :                 // For a delete-only compaction, set the output level to L6. The
     349            1 :                 // output level is not meaningful here, but complicating the
     350            1 :                 // info.Output interface with a pointer doesn't seem worth the
     351            1 :                 // semantic distinction.
     352            1 :                 info.Output.Level = numLevels - 1
     353            1 :         }
     354              : 
     355            1 :         for i, score := range c.pickerMetrics.scores {
     356            1 :                 info.Input[i].Score = score
     357            1 :         }
     358            1 :         info.SingleLevelOverlappingRatio = c.pickerMetrics.singleLevelOverlappingRatio
     359            1 :         info.MultiLevelOverlappingRatio = c.pickerMetrics.multiLevelOverlappingRatio
     360            1 :         if len(info.Input) > 2 {
     361            1 :                 info.Annotations = append(info.Annotations, "multilevel")
     362            1 :         }
     363            1 :         return info
     364              : }
     365              : 
     366            1 : func (c *compaction) userKeyBounds() base.UserKeyBounds {
     367            1 :         return base.UserKeyBoundsFromInternal(c.smallest, c.largest)
     368            1 : }
     369              : 
     370              : type getValueSeparation func(JobID, *compaction, sstable.TableFormat) compact.ValueSeparation
     371              : 
     372              : // newCompaction constructs a compaction from the provided picked compaction.
     373              : //
     374              : // The compaction is created with a reference to its version that must be
     375              : // released when the compaction is complete.
     376              : func newCompaction(
     377              :         pc *pickedCompaction,
     378              :         opts *Options,
     379              :         beganAt time.Time,
     380              :         provider objstorage.Provider,
     381              :         grantHandle CompactionGrantHandle,
     382              :         tableFormat sstable.TableFormat,
     383              :         getValueSeparation getValueSeparation,
     384            1 : ) *compaction {
     385            1 :         c := &compaction{
     386            1 :                 kind:               compactionKindDefault,
     387            1 :                 cmp:                pc.cmp,
     388            1 :                 equal:              opts.Comparer.Equal,
     389            1 :                 comparer:           opts.Comparer,
     390            1 :                 formatKey:          opts.Comparer.FormatKey,
     391            1 :                 inputs:             pc.inputs,
     392            1 :                 smallest:           pc.smallest,
     393            1 :                 largest:            pc.largest,
     394            1 :                 logger:             opts.Logger,
     395            1 :                 version:            pc.version,
     396            1 :                 beganAt:            beganAt,
     397            1 :                 getValueSeparation: getValueSeparation,
     398            1 :                 maxOutputFileSize:  pc.maxOutputFileSize,
     399            1 :                 maxOverlapBytes:    pc.maxOverlapBytes,
     400            1 :                 pickerMetrics:      pc.pickerMetrics,
     401            1 :                 grantHandle:        grantHandle,
     402            1 :                 tableFormat:        tableFormat,
     403            1 :         }
     404            1 :         // Acquire a reference to the version to ensure that files and in-memory
     405            1 :         // version state necessary for reading files remain available. Ignoring
     406            1 :         // excises, this isn't strictly necessary for reading the sstables that are
     407            1 :         // inputs to the compaction because those files are 'marked as compacting'
     408            1 :         // and shouldn't be subject to any competing compactions. However with
     409            1 :         // excises, a concurrent excise may remove a compaction's file from the
     410            1 :         // Version and then cancel the compaction. The file shouldn't be physically
     411            1 :         // removed until the cancelled compaction stops reading it.
     412            1 :         //
     413            1 :         // Additionally, we need any blob files referenced by input sstables to
     414            1 :         // remain available, even if the blob file is rewritten. Maintaining a
     415            1 :         // reference ensures that all these files remain available for the
     416            1 :         // compaction's reads.
     417            1 :         c.version.Ref()
     418            1 : 
     419            1 :         c.startLevel = &c.inputs[0]
     420            1 :         if pc.startLevel.l0SublevelInfo != nil {
     421            1 :                 c.startLevel.l0SublevelInfo = pc.startLevel.l0SublevelInfo
     422            1 :         }
     423            1 :         c.outputLevel = &c.inputs[1]
     424            1 : 
     425            1 :         if len(pc.extraLevels) > 0 {
     426            1 :                 c.extraLevels = pc.extraLevels
     427            1 :                 c.outputLevel = &c.inputs[len(c.inputs)-1]
     428            1 :         }
     429              :         // Compute the set of outputLevel+1 files that overlap this compaction (these
     430              :         // are the grandparent sstables).
     431            1 :         if c.outputLevel.level+1 < numLevels {
     432            1 :                 c.grandparents = c.version.Overlaps(c.outputLevel.level+1, c.userKeyBounds())
     433            1 :         }
     434            1 :         c.delElision, c.rangeKeyElision = compact.SetupTombstoneElision(
     435            1 :                 c.cmp, c.version, pc.l0Organizer, c.outputLevel.level, base.UserKeyBoundsFromInternal(c.smallest, c.largest),
     436            1 :         )
     437            1 :         c.kind = pc.kind
     438            1 : 
     439            1 :         preferSharedStorage := tableFormat >= FormatMinForSharedObjects.MaxTableFormat() &&
     440            1 :                 remote.ShouldCreateShared(opts.Experimental.CreateOnShared, c.outputLevel.level)
     441            1 :         c.maybeSwitchToMoveOrCopy(preferSharedStorage, provider)
     442            1 :         c.objCreateOpts = objstorage.CreateOptions{
     443            1 :                 PreferSharedStorage: preferSharedStorage,
     444            1 :                 WriteCategory:       getDiskWriteCategoryForCompaction(opts, c.kind),
     445            1 :         }
     446            1 :         if preferSharedStorage {
     447            1 :                 c.getValueSeparation = neverSeparateValues
     448            1 :         }
     449              : 
     450            1 :         return c
     451              : }
     452              : 
     453              : // maybeSwitchToMoveOrCopy decides if the compaction can be changed into a move
     454              : // or copy compaction, in which case c.kind is updated.
     455              : func (c *compaction) maybeSwitchToMoveOrCopy(
     456              :         preferSharedStorage bool, provider objstorage.Provider,
     457            1 : ) {
     458            1 :         // Only non-multi-level compactions with a single input file can be
     459            1 :         // considered.
     460            1 :         if c.startLevel.files.Len() != 1 || !c.outputLevel.files.Empty() || c.hasExtraLevelData() {
     461            1 :                 return
     462            1 :         }
     463              : 
     464              :         // In addition to the default compaction, we also check whether a tombstone
     465              :         // density compaction can be optimized into a move compaction. However, we
     466              :         // want to avoid performing a move compaction into the lowest level, since the
     467              :         // goal there is to actually remove the tombstones.
     468              :         //
     469              :         // Tombstone density compaction is meant to address cases where tombstones
     470              :         // don't reclaim much space but are still expensive to scan over. We can only
     471              :         // remove the tombstones once there's nothing at all underneath them.
     472            1 :         switch c.kind {
     473            1 :         case compactionKindDefault:
     474              :                 // Proceed.
     475            1 :         case compactionKindTombstoneDensity:
     476            1 :                 // Tombstone density compaction can be optimized into a move compaction.
     477            1 :                 // However, we want to avoid performing a move compaction into the lowest
     478            1 :                 // level, since the goal there is to actually remove the tombstones; even if
     479            1 :                 // they don't prevent a lot of space from being reclaimed, tombstones can
     480            1 :                 // still be expensive to scan over.
     481            1 :                 if c.outputLevel.level == numLevels-1 {
     482            1 :                         return
     483            1 :                 }
     484            1 :         default:
     485            1 :                 // Other compaction kinds not supported.
     486            1 :                 return
     487              :         }
     488              : 
     489              :         // We avoid a move or copy if there is lots of overlapping grandparent data.
     490              :         // Otherwise, the move could create a parent file that will require a very
     491              :         // expensive merge later on.
     492            1 :         if c.grandparents.AggregateSizeSum() > c.maxOverlapBytes {
     493            0 :                 return
     494            0 :         }
     495              : 
     496            1 :         iter := c.startLevel.files.Iter()
     497            1 :         meta := iter.First()
     498            1 : 
     499            1 :         // We should always be passed a provider, except in some unit tests.
     500            1 :         isRemote := provider != nil && !objstorage.IsLocalTable(provider, meta.TableBacking.DiskFileNum)
     501            1 : 
     502            1 :         // Shared and external tables can always be moved. We can also move a local
     503            1 :         // table unless we need the result to be on shared storage.
     504            1 :         if isRemote || !preferSharedStorage {
     505            1 :                 c.kind = compactionKindMove
     506            1 :                 return
     507            1 :         }
     508              : 
     509              :         // We can rewrite the table (regular compaction) or we can use a copy compaction.
     510            1 :         switch {
     511            1 :         case meta.Virtual:
     512              :                 // We want to avoid a copy compaction if the table is virtual, as we may end
     513              :                 // up copying a lot more data than necessary.
     514            1 :         case meta.BlobReferenceDepth != 0:
     515              :                 // We also want to avoid copy compactions for tables with blob references,
     516              :                 // as we currently lack a mechanism to propagate blob references along with
     517              :                 // the sstable.
     518            1 :         default:
     519            1 :                 c.kind = compactionKindCopy
     520              :         }
     521              : }
     522              : 
     523              : // newDeleteOnlyCompaction constructs a delete-only compaction from the provided
     524              : // inputs.
     525              : //
     526              : // The compaction is created with a reference to its version that must be
     527              : // released when the compaction is complete.
     528              : func newDeleteOnlyCompaction(
     529              :         opts *Options,
     530              :         cur *manifest.Version,
     531              :         inputs []compactionLevel,
     532              :         beganAt time.Time,
     533              :         hints []deleteCompactionHint,
     534              :         exciseEnabled bool,
     535            1 : ) *compaction {
     536            1 :         c := &compaction{
     537            1 :                 kind:          compactionKindDeleteOnly,
     538            1 :                 cmp:           opts.Comparer.Compare,
     539            1 :                 equal:         opts.Comparer.Equal,
     540            1 :                 comparer:      opts.Comparer,
     541            1 :                 formatKey:     opts.Comparer.FormatKey,
     542            1 :                 logger:        opts.Logger,
     543            1 :                 version:       cur,
     544            1 :                 beganAt:       beganAt,
     545            1 :                 inputs:        inputs,
     546            1 :                 deletionHints: hints,
     547            1 :                 exciseEnabled: exciseEnabled,
     548            1 :                 grantHandle:   noopGrantHandle{},
     549            1 :         }
     550            1 :         // Acquire a reference to the version to ensure that files and in-memory
     551            1 :         // version state necessary for reading files remain available. Ignoring
     552            1 :         // excises, this isn't strictly necessary for reading the sstables that are
     553            1 :         // inputs to the compaction because those files are 'marked as compacting'
     554            1 :         // and shouldn't be subject to any competing compactions. However with
     555            1 :         // excises, a concurrent excise may remove a compaction's file from the
     556            1 :         // Version and then cancel the compaction. The file shouldn't be physically
     557            1 :         // removed until the cancelled compaction stops reading it.
     558            1 :         //
     559            1 :         // Additionally, we need any blob files referenced by input sstables to
     560            1 :         // remain available, even if the blob file is rewritten. Maintaining a
     561            1 :         // reference ensures that all these files remain available for the
     562            1 :         // compaction's reads.
     563            1 :         c.version.Ref()
     564            1 : 
     565            1 :         // Set c.smallest, c.largest.
     566            1 :         files := make([]iter.Seq[*manifest.TableMetadata], 0, len(inputs))
     567            1 :         for _, in := range inputs {
     568            1 :                 files = append(files, in.files.All())
     569            1 :         }
     570            1 :         c.smallest, c.largest = manifest.KeyRange(opts.Comparer.Compare, files...)
     571            1 :         return c
     572              : }
     573              : 
     574            1 : func adjustGrandparentOverlapBytesForFlush(c *compaction, flushingBytes uint64) {
     575            1 :         // Heuristic to place a lower bound on compaction output file size
     576            1 :         // caused by Lbase. Prior to this heuristic we have observed an L0 in
     577            1 :         // production with 310K files of which 290K files were < 10KB in size.
     578            1 :         // Our hypothesis is that it was caused by L1 having 2600 files and
     579            1 :         // ~10GB, such that each flush got split into many tiny files due to
     580            1 :         // overlapping with most of the files in Lbase.
     581            1 :         //
     582            1 :         // The computation below is general in that it accounts
     583            1 :         // for flushing different volumes of data (e.g. we may be flushing
     584            1 :         // many memtables). For illustration, we consider the typical
     585            1 :         // example of flushing a 64MB memtable. So 12.8MB output,
     586            1 :         // based on the compression guess below. If the compressed bytes
     587            1 :         // guess is an over-estimate we will end up with smaller files,
     588            1 :         // and if an under-estimate we will end up with larger files.
     589            1 :         // With a 2MB target file size, 7 files. We are willing to accept
     590            1 :         // 4x the number of files, if it results in better write amplification
     591            1 :         // when later compacting to Lbase, i.e., ~450KB files (target file
     592            1 :         // size / 4).
     593            1 :         //
     594            1 :         // Note that this is a pessimistic heuristic in that
     595            1 :         // fileCountUpperBoundDueToGrandparents could be far from the actual
     596            1 :         // number of files produced due to the grandparent limits. For
     597            1 :         // example, in the extreme, consider a flush that overlaps with 1000
     598            1 :         // files in Lbase f0...f999, and the initially calculated value of
     599            1 :         // maxOverlapBytes will cause splits at f10, f20,..., f990, which
     600            1 :         // means an upper bound file count of 100 files. Say the input bytes
     601            1 :         // in the flush are such that acceptableFileCount=10. We will fatten
     602            1 :         // up maxOverlapBytes by 10x to ensure that the upper bound file count
     603            1 :         // drops to 10. However, it is possible that in practice, even without
     604            1 :         // this change, we would have produced no more than 10 files, and that
     605            1 :         // this change makes the files unnecessarily wide. Say the input bytes
     606            1 :         // are distributed such that 10% are in f0...f9, 10% in f10...f19, ...
     607            1 :         // 10% in f80...f89 and 10% in f990...f999. The original value of
     608            1 :         // maxOverlapBytes would have actually produced only 10 sstables. But
     609            1 :         // by increasing maxOverlapBytes by 10x, we may produce 1 sstable that
     610            1 :         // spans f0...f89, i.e., a much wider sstable than necessary.
     611            1 :         //
     612            1 :         // We could produce a tighter estimate of
     613            1 :         // fileCountUpperBoundDueToGrandparents if we had knowledge of the key
     614            1 :         // distribution of the flush. The 4x multiplier mentioned earlier is
     615            1 :         // a way to try to compensate for this pessimism.
     616            1 :         //
     617            1 :         // TODO(sumeer): we don't have compression info for the data being
     618            1 :         // flushed, but it is likely that existing files that overlap with
     619            1 :         // this flush in Lbase are representative wrt compression ratio. We
     620            1 :         // could store the uncompressed size in TableMetadata and estimate
     621            1 :         // the compression ratio.
     622            1 :         const approxCompressionRatio = 0.2
     623            1 :         approxOutputBytes := approxCompressionRatio * float64(flushingBytes)
     624            1 :         approxNumFilesBasedOnTargetSize :=
     625            1 :                 int(math.Ceil(approxOutputBytes / float64(c.maxOutputFileSize)))
     626            1 :         acceptableFileCount := float64(4 * approxNumFilesBasedOnTargetSize)
     627            1 :         // The byte calculation is linear in numGrandparentFiles, but we will
     628            1 :         // incur this linear cost in compact.Runner.TableSplitLimit() too, so we are
     629            1 :         // also willing to pay it now. We could approximate this cheaply by using the
     630            1 :         // mean file size of Lbase.
     631            1 :         grandparentFileBytes := c.grandparents.AggregateSizeSum()
     632            1 :         fileCountUpperBoundDueToGrandparents :=
     633            1 :                 float64(grandparentFileBytes) / float64(c.maxOverlapBytes)
     634            1 :         if fileCountUpperBoundDueToGrandparents > acceptableFileCount {
     635            1 :                 c.maxOverlapBytes = uint64(
     636            1 :                         float64(c.maxOverlapBytes) *
     637            1 :                                 (fileCountUpperBoundDueToGrandparents / acceptableFileCount))
     638            1 :         }
     639              : }
     640              : 
     641              : // newFlush creates the state necessary for a flush (modeled with the compaction
     642              : // struct).
     643              : //
     644              : // newFlush takes the current Version in order to populate grandparent flushing
     645              : // limits, but it does not reference the version.
     646              : //
     647              : // TODO(jackson): Consider maintaining a reference to the version anyways since
     648              : // in the future in-memory Version state may only be available while a Version
     649              : // is referenced (eg, if we start recycling B-Tree nodes once they're no longer
     650              : // referenced). There's subtlety around unref'ing the version at the right
     651              : // moment, so we defer it for now.
     652              : func newFlush(
     653              :         opts *Options,
     654              :         cur *manifest.Version,
     655              :         l0Organizer *manifest.L0Organizer,
     656              :         baseLevel int,
     657              :         flushing flushableList,
     658              :         beganAt time.Time,
     659              :         tableFormat sstable.TableFormat,
     660              :         getValueSeparation getValueSeparation,
     661            1 : ) (*compaction, error) {
     662            1 :         c := &compaction{
     663            1 :                 kind:               compactionKindFlush,
     664            1 :                 cmp:                opts.Comparer.Compare,
     665            1 :                 equal:              opts.Comparer.Equal,
     666            1 :                 comparer:           opts.Comparer,
     667            1 :                 formatKey:          opts.Comparer.FormatKey,
     668            1 :                 logger:             opts.Logger,
     669            1 :                 version:            cur,
     670            1 :                 beganAt:            beganAt,
     671            1 :                 inputs:             []compactionLevel{{level: -1}, {level: 0}},
     672            1 :                 getValueSeparation: getValueSeparation,
     673            1 :                 maxOutputFileSize:  math.MaxUint64,
     674            1 :                 maxOverlapBytes:    math.MaxUint64,
     675            1 :                 flushing:           flushing,
     676            1 :                 grantHandle:        noopGrantHandle{},
     677            1 :                 tableFormat:        tableFormat,
     678            1 :         }
     679            1 :         c.startLevel = &c.inputs[0]
     680            1 :         c.outputLevel = &c.inputs[1]
     681            1 :         if len(flushing) > 0 {
     682            1 :                 if _, ok := flushing[0].flushable.(*ingestedFlushable); ok {
     683            1 :                         if len(flushing) != 1 {
     684            0 :                                 panic("pebble: ingestedFlushable must be flushed one at a time.")
     685              :                         }
     686            1 :                         c.kind = compactionKindIngestedFlushable
     687            1 :                         return c, nil
     688              :                 }
     689              :         }
     690              : 
     691            1 :         preferSharedStorage := tableFormat >= FormatMinForSharedObjects.MaxTableFormat() &&
     692            1 :                 remote.ShouldCreateShared(opts.Experimental.CreateOnShared, c.outputLevel.level)
     693            1 :         c.objCreateOpts = objstorage.CreateOptions{
     694            1 :                 PreferSharedStorage: preferSharedStorage,
     695            1 :                 WriteCategory:       getDiskWriteCategoryForCompaction(opts, c.kind),
     696            1 :         }
     697            1 :         if preferSharedStorage {
     698            1 :                 c.getValueSeparation = neverSeparateValues
     699            1 :         }
     700              : 
     701              :         // Make sure there's no ingestedFlushable after the first flushable in the
     702              :         // list.
     703            1 :         for _, f := range flushing {
     704            1 :                 if _, ok := f.flushable.(*ingestedFlushable); ok {
     705            0 :                         panic("pebble: flushing shouldn't contain ingestedFlushable flushable")
     706              :                 }
     707              :         }
     708              : 
     709            1 :         c.l0Limits = l0Organizer.FlushSplitKeys()
     710            1 : 
     711            1 :         smallestSet, largestSet := false, false
     712            1 :         updatePointBounds := func(iter internalIterator) {
     713            1 :                 if kv := iter.First(); kv != nil {
     714            1 :                         if !smallestSet ||
     715            1 :                                 base.InternalCompare(c.cmp, c.smallest, kv.K) > 0 {
     716            1 :                                 smallestSet = true
     717            1 :                                 c.smallest = kv.K.Clone()
     718            1 :                         }
     719              :                 }
     720            1 :                 if kv := iter.Last(); kv != nil {
     721            1 :                         if !largestSet ||
     722            1 :                                 base.InternalCompare(c.cmp, c.largest, kv.K) < 0 {
     723            1 :                                 largestSet = true
     724            1 :                                 c.largest = kv.K.Clone()
     725            1 :                         }
     726              :                 }
     727              :         }
     728              : 
     729            1 :         updateRangeBounds := func(iter keyspan.FragmentIterator) error {
     730            1 :                 // File bounds require s != nil && !s.Empty(). We only need to check for
     731            1 :                 // s != nil here, as the memtable's FragmentIterator would never surface
     732            1 :                 // empty spans.
     733            1 :                 if s, err := iter.First(); err != nil {
     734            0 :                         return err
     735            1 :                 } else if s != nil {
     736            1 :                         if key := s.SmallestKey(); !smallestSet ||
     737            1 :                                 base.InternalCompare(c.cmp, c.smallest, key) > 0 {
     738            1 :                                 smallestSet = true
     739            1 :                                 c.smallest = key.Clone()
     740            1 :                         }
     741              :                 }
     742            1 :                 if s, err := iter.Last(); err != nil {
     743            0 :                         return err
     744            1 :                 } else if s != nil {
     745            1 :                         if key := s.LargestKey(); !largestSet ||
     746            1 :                                 base.InternalCompare(c.cmp, c.largest, key) < 0 {
     747            1 :                                 largestSet = true
     748            1 :                                 c.largest = key.Clone()
     749            1 :                         }
     750              :                 }
     751            1 :                 return nil
     752              :         }
     753              : 
     754            1 :         var flushingBytes uint64
     755            1 :         for i := range flushing {
     756            1 :                 f := flushing[i]
     757            1 :                 updatePointBounds(f.newIter(nil))
     758            1 :                 if rangeDelIter := f.newRangeDelIter(nil); rangeDelIter != nil {
     759            1 :                         if err := updateRangeBounds(rangeDelIter); err != nil {
     760            0 :                                 return nil, err
     761            0 :                         }
     762              :                 }
     763            1 :                 if rangeKeyIter := f.newRangeKeyIter(nil); rangeKeyIter != nil {
     764            1 :                         if err := updateRangeBounds(rangeKeyIter); err != nil {
     765            0 :                                 return nil, err
     766            0 :                         }
     767              :                 }
     768            1 :                 flushingBytes += f.inuseBytes()
     769              :         }
     770              : 
     771            1 :         if opts.FlushSplitBytes > 0 {
     772            1 :                 c.maxOutputFileSize = uint64(opts.Levels[0].TargetFileSize)
     773            1 :                 c.maxOverlapBytes = maxGrandparentOverlapBytes(opts, 0)
     774            1 :                 c.grandparents = c.version.Overlaps(baseLevel, c.userKeyBounds())
     775            1 :                 adjustGrandparentOverlapBytesForFlush(c, flushingBytes)
     776            1 :         }
     777              : 
     778              :         // We don't elide tombstones for flushes.
     779            1 :         c.delElision, c.rangeKeyElision = compact.NoTombstoneElision(), compact.NoTombstoneElision()
     780            1 :         return c, nil
     781              : }
     782              : 
     783            1 : func (c *compaction) hasExtraLevelData() bool {
     784            1 :         if len(c.extraLevels) == 0 {
     785            1 :                 // not a multi level compaction
     786            1 :                 return false
     787            1 :         } else if c.extraLevels[0].files.Empty() {
     788            1 :                 // a multi level compaction without data in the intermediate input level;
     789            1 :                 // e.g. for a multi level compaction with levels 4,5, and 6, this could
     790            1 :                 // occur if there is no files to compact in 5, or in 5 and 6 (i.e. a move).
     791            1 :                 return false
     792            1 :         }
     793            1 :         return true
     794              : }
     795              : 
     796              : // errorOnUserKeyOverlap returns an error if the last two written sstables in
     797              : // this compaction have revisions of the same user key present in both sstables,
     798              : // when it shouldn't (eg. when splitting flushes).
     799            0 : func (c *compaction) errorOnUserKeyOverlap(ve *manifest.VersionEdit) error {
     800            0 :         if n := len(ve.NewTables); n > 1 {
     801            0 :                 meta := ve.NewTables[n-1].Meta
     802            0 :                 prevMeta := ve.NewTables[n-2].Meta
     803            0 :                 if !prevMeta.Largest().IsExclusiveSentinel() &&
     804            0 :                         c.cmp(prevMeta.Largest().UserKey, meta.Smallest().UserKey) >= 0 {
     805            0 :                         return errors.Errorf("pebble: compaction split user key across two sstables: %s in %s and %s",
     806            0 :                                 prevMeta.Largest().Pretty(c.formatKey),
     807            0 :                                 prevMeta.TableNum,
     808            0 :                                 meta.TableNum)
     809            0 :                 }
     810              :         }
     811            0 :         return nil
     812              : }
     813              : 
     814              : // allowZeroSeqNum returns true if seqnum's can be zeroed if there are no
     815              : // snapshots requiring them to be kept. It performs this determination by
     816              : // looking at the TombstoneElision values which are set up based on sstables
     817              : // which overlap the bounds of the compaction at a lower level in the LSM.
     818            1 : func (c *compaction) allowZeroSeqNum() bool {
     819            1 :         // TODO(peter): we disable zeroing of seqnums during flushing to match
     820            1 :         // RocksDB behavior and to avoid generating overlapping sstables during
     821            1 :         // DB.replayWAL. When replaying WAL files at startup, we flush after each
     822            1 :         // WAL is replayed building up a single version edit that is
     823            1 :         // applied. Because we don't apply the version edit after each flush, this
     824            1 :         // code doesn't know that L0 contains files and zeroing of seqnums should
     825            1 :         // be disabled. That is fixable, but it seems safer to just match the
     826            1 :         // RocksDB behavior for now.
     827            1 :         return len(c.flushing) == 0 && c.delElision.ElidesEverything() && c.rangeKeyElision.ElidesEverything()
     828            1 : }
     829              : 
     830              : // newInputIters returns an iterator over all the input tables in a compaction.
     831              : func (c *compaction) newInputIters(
     832              :         newIters tableNewIters, newRangeKeyIter keyspanimpl.TableNewSpanIter, iiopts internalIterOpts,
     833              : ) (
     834              :         pointIter internalIterator,
     835              :         rangeDelIter, rangeKeyIter keyspan.FragmentIterator,
     836              :         retErr error,
     837            1 : ) {
     838            1 :         // Validate the ordering of compaction input files for defense in depth.
     839            1 :         if len(c.flushing) == 0 {
     840            1 :                 if c.startLevel.level >= 0 {
     841            1 :                         err := manifest.CheckOrdering(c.cmp, c.formatKey,
     842            1 :                                 manifest.Level(c.startLevel.level), c.startLevel.files.Iter())
     843            1 :                         if err != nil {
     844            0 :                                 return nil, nil, nil, err
     845            0 :                         }
     846              :                 }
     847            1 :                 err := manifest.CheckOrdering(c.cmp, c.formatKey,
     848            1 :                         manifest.Level(c.outputLevel.level), c.outputLevel.files.Iter())
     849            1 :                 if err != nil {
     850            0 :                         return nil, nil, nil, err
     851            0 :                 }
     852            1 :                 if c.startLevel.level == 0 {
     853            1 :                         if c.startLevel.l0SublevelInfo == nil {
     854            0 :                                 panic("l0SublevelInfo not created for compaction out of L0")
     855              :                         }
     856            1 :                         for _, info := range c.startLevel.l0SublevelInfo {
     857            1 :                                 err := manifest.CheckOrdering(c.cmp, c.formatKey,
     858            1 :                                         info.sublevel, info.Iter())
     859            1 :                                 if err != nil {
     860            0 :                                         return nil, nil, nil, err
     861            0 :                                 }
     862              :                         }
     863              :                 }
     864            1 :                 if len(c.extraLevels) > 0 {
     865            1 :                         if len(c.extraLevels) > 1 {
     866            0 :                                 panic("n>2 multi level compaction not implemented yet")
     867              :                         }
     868            1 :                         interLevel := c.extraLevels[0]
     869            1 :                         err := manifest.CheckOrdering(c.cmp, c.formatKey,
     870            1 :                                 manifest.Level(interLevel.level), interLevel.files.Iter())
     871            1 :                         if err != nil {
     872            0 :                                 return nil, nil, nil, err
     873            0 :                         }
     874              :                 }
     875              :         }
     876              : 
     877              :         // There are three classes of keys that a compaction needs to process: point
     878              :         // keys, range deletion tombstones and range keys. Collect all iterators for
     879              :         // all these classes of keys from all the levels. We'll aggregate them
     880              :         // together farther below.
     881              :         //
     882              :         // numInputLevels is an approximation of the number of iterator levels. Due
     883              :         // to idiosyncrasies in iterator construction, we may (rarely) exceed this
     884              :         // initial capacity.
     885            1 :         numInputLevels := max(len(c.flushing), len(c.inputs))
     886            1 :         iters := make([]internalIterator, 0, numInputLevels)
     887            1 :         rangeDelIters := make([]keyspan.FragmentIterator, 0, numInputLevels)
     888            1 :         rangeKeyIters := make([]keyspan.FragmentIterator, 0, numInputLevels)
     889            1 : 
     890            1 :         // If construction of the iterator inputs fails, ensure that we close all
     891            1 :         // the consitutent iterators.
     892            1 :         defer func() {
     893            1 :                 if retErr != nil {
     894            0 :                         for _, iter := range iters {
     895            0 :                                 if iter != nil {
     896            0 :                                         _ = iter.Close()
     897            0 :                                 }
     898              :                         }
     899            0 :                         for _, rangeDelIter := range rangeDelIters {
     900            0 :                                 rangeDelIter.Close()
     901            0 :                         }
     902              :                 }
     903              :         }()
     904            1 :         iterOpts := IterOptions{
     905            1 :                 Category: categoryCompaction,
     906            1 :                 logger:   c.logger,
     907            1 :         }
     908            1 : 
     909            1 :         // Populate iters, rangeDelIters and rangeKeyIters with the appropriate
     910            1 :         // constituent iterators. This depends on whether this is a flush or a
     911            1 :         // compaction.
     912            1 :         if len(c.flushing) != 0 {
     913            1 :                 // If flushing, we need to build the input iterators over the memtables
     914            1 :                 // stored in c.flushing.
     915            1 :                 for i := range c.flushing {
     916            1 :                         f := c.flushing[i]
     917            1 :                         iters = append(iters, f.newFlushIter(nil))
     918            1 :                         rangeDelIter := f.newRangeDelIter(nil)
     919            1 :                         if rangeDelIter != nil {
     920            1 :                                 rangeDelIters = append(rangeDelIters, rangeDelIter)
     921            1 :                         }
     922            1 :                         if rangeKeyIter := f.newRangeKeyIter(nil); rangeKeyIter != nil {
     923            1 :                                 rangeKeyIters = append(rangeKeyIters, rangeKeyIter)
     924            1 :                         }
     925              :                 }
     926            1 :         } else {
     927            1 :                 addItersForLevel := func(level *compactionLevel, l manifest.Layer) error {
     928            1 :                         // Add a *levelIter for point iterators. Because we don't call
     929            1 :                         // initRangeDel, the levelIter will close and forget the range
     930            1 :                         // deletion iterator when it steps on to a new file. Surfacing range
     931            1 :                         // deletions to compactions are handled below.
     932            1 :                         iters = append(iters, newLevelIter(context.Background(),
     933            1 :                                 iterOpts, c.comparer, newIters, level.files.Iter(), l, iiopts))
     934            1 :                         // TODO(jackson): Use keyspanimpl.LevelIter to avoid loading all the range
     935            1 :                         // deletions into memory upfront. (See #2015, which reverted this.) There
     936            1 :                         // will be no user keys that are split between sstables within a level in
     937            1 :                         // Cockroach 23.1, which unblocks this optimization.
     938            1 : 
     939            1 :                         // Add the range deletion iterator for each file as an independent level
     940            1 :                         // in mergingIter, as opposed to making a levelIter out of those. This
     941            1 :                         // is safer as levelIter expects all keys coming from underlying
     942            1 :                         // iterators to be in order. Due to compaction / tombstone writing
     943            1 :                         // logic in finishOutput(), it is possible for range tombstones to not
     944            1 :                         // be strictly ordered across all files in one level.
     945            1 :                         //
     946            1 :                         // Consider this example from the metamorphic tests (also repeated in
     947            1 :                         // finishOutput()), consisting of three L3 files with their bounds
     948            1 :                         // specified in square brackets next to the file name:
     949            1 :                         //
     950            1 :                         // ./000240.sst   [tmgc#391,MERGE-tmgc#391,MERGE]
     951            1 :                         // tmgc#391,MERGE [786e627a]
     952            1 :                         // tmgc-udkatvs#331,RANGEDEL
     953            1 :                         //
     954            1 :                         // ./000241.sst   [tmgc#384,MERGE-tmgc#384,MERGE]
     955            1 :                         // tmgc#384,MERGE [666c7070]
     956            1 :                         // tmgc-tvsalezade#383,RANGEDEL
     957            1 :                         // tmgc-tvsalezade#331,RANGEDEL
     958            1 :                         //
     959            1 :                         // ./000242.sst   [tmgc#383,RANGEDEL-tvsalezade#72057594037927935,RANGEDEL]
     960            1 :                         // tmgc-tvsalezade#383,RANGEDEL
     961            1 :                         // tmgc#375,SET [72646c78766965616c72776865676e79]
     962            1 :                         // tmgc-tvsalezade#356,RANGEDEL
     963            1 :                         //
     964            1 :                         // Here, the range tombstone in 000240.sst falls "after" one in
     965            1 :                         // 000241.sst, despite 000240.sst being ordered "before" 000241.sst for
     966            1 :                         // levelIter's purposes. While each file is still consistent before its
     967            1 :                         // bounds, it's safer to have all rangedel iterators be visible to
     968            1 :                         // mergingIter.
     969            1 :                         iter := level.files.Iter()
     970            1 :                         for f := iter.First(); f != nil; f = iter.Next() {
     971            1 :                                 rangeDelIter, err := c.newRangeDelIter(newIters, iter.Take(), iterOpts, iiopts, l)
     972            1 :                                 if err != nil {
     973            0 :                                         // The error will already be annotated with the BackingFileNum, so
     974            0 :                                         // we annotate it with the FileNum.
     975            0 :                                         return errors.Wrapf(err, "pebble: could not open table %s", errors.Safe(f.TableNum))
     976            0 :                                 }
     977            1 :                                 if rangeDelIter == nil {
     978            1 :                                         continue
     979              :                                 }
     980            1 :                                 rangeDelIters = append(rangeDelIters, rangeDelIter)
     981            1 :                                 c.closers = append(c.closers, rangeDelIter)
     982              :                         }
     983              : 
     984              :                         // Check if this level has any range keys.
     985            1 :                         hasRangeKeys := false
     986            1 :                         for f := iter.First(); f != nil; f = iter.Next() {
     987            1 :                                 if f.HasRangeKeys {
     988            1 :                                         hasRangeKeys = true
     989            1 :                                         break
     990              :                                 }
     991              :                         }
     992            1 :                         if hasRangeKeys {
     993            1 :                                 newRangeKeyIterWrapper := func(ctx context.Context, file *manifest.TableMetadata, iterOptions keyspan.SpanIterOptions) (keyspan.FragmentIterator, error) {
     994            1 :                                         rangeKeyIter, err := newRangeKeyIter(ctx, file, iterOptions)
     995            1 :                                         if err != nil {
     996            0 :                                                 return nil, err
     997            1 :                                         } else if rangeKeyIter == nil {
     998            0 :                                                 return emptyKeyspanIter, nil
     999            0 :                                         }
    1000              :                                         // Ensure that the range key iter is not closed until the compaction is
    1001              :                                         // finished. This is necessary because range key processing
    1002              :                                         // requires the range keys to be held in memory for up to the
    1003              :                                         // lifetime of the compaction.
    1004            1 :                                         noCloseIter := &noCloseIter{rangeKeyIter}
    1005            1 :                                         c.closers = append(c.closers, noCloseIter)
    1006            1 : 
    1007            1 :                                         // We do not need to truncate range keys to sstable boundaries, or
    1008            1 :                                         // only read within the file's atomic compaction units, unlike with
    1009            1 :                                         // range tombstones. This is because range keys were added after we
    1010            1 :                                         // stopped splitting user keys across sstables, so all the range keys
    1011            1 :                                         // in this sstable must wholly lie within the file's bounds.
    1012            1 :                                         return noCloseIter, err
    1013              :                                 }
    1014            1 :                                 li := keyspanimpl.NewLevelIter(
    1015            1 :                                         context.Background(), keyspan.SpanIterOptions{}, c.cmp,
    1016            1 :                                         newRangeKeyIterWrapper, level.files.Iter(), l, manifest.KeyTypeRange,
    1017            1 :                                 )
    1018            1 :                                 rangeKeyIters = append(rangeKeyIters, li)
    1019              :                         }
    1020            1 :                         return nil
    1021              :                 }
    1022              : 
    1023            1 :                 for i := range c.inputs {
    1024            1 :                         // If the level is annotated with l0SublevelInfo, expand it into one
    1025            1 :                         // level per sublevel.
    1026            1 :                         // TODO(jackson): Perform this expansion even earlier when we pick the
    1027            1 :                         // compaction?
    1028            1 :                         if len(c.inputs[i].l0SublevelInfo) > 0 {
    1029            1 :                                 for _, info := range c.startLevel.l0SublevelInfo {
    1030            1 :                                         sublevelCompactionLevel := &compactionLevel{0, info.LevelSlice, nil}
    1031            1 :                                         if err := addItersForLevel(sublevelCompactionLevel, info.sublevel); err != nil {
    1032            0 :                                                 return nil, nil, nil, err
    1033            0 :                                         }
    1034              :                                 }
    1035            1 :                                 continue
    1036              :                         }
    1037            1 :                         if err := addItersForLevel(&c.inputs[i], manifest.Level(c.inputs[i].level)); err != nil {
    1038            0 :                                 return nil, nil, nil, err
    1039            0 :                         }
    1040              :                 }
    1041              :         }
    1042              : 
    1043              :         // If there's only one constituent point iterator, we can avoid the overhead
    1044              :         // of a *mergingIter. This is possible, for example, when performing a flush
    1045              :         // of a single memtable. Otherwise, combine all the iterators into a merging
    1046              :         // iter.
    1047            1 :         pointIter = iters[0]
    1048            1 :         if len(iters) > 1 {
    1049            1 :                 pointIter = newMergingIter(c.logger, &c.stats, c.cmp, nil, iters...)
    1050            1 :         }
    1051              : 
    1052              :         // In normal operation, levelIter iterates over the point operations in a
    1053              :         // level, and initializes a rangeDelIter pointer for the range deletions in
    1054              :         // each table. During compaction, we want to iterate over the merged view of
    1055              :         // point operations and range deletions. In order to do this we create one
    1056              :         // levelIter per level to iterate over the point operations, and collect up
    1057              :         // all the range deletion files.
    1058              :         //
    1059              :         // The range deletion levels are combined with a keyspanimpl.MergingIter. The
    1060              :         // resulting merged rangedel iterator is then included using an
    1061              :         // InterleavingIter.
    1062              :         // TODO(jackson): Consider using a defragmenting iterator to stitch together
    1063              :         // logical range deletions that were fragmented due to previous file
    1064              :         // boundaries.
    1065            1 :         if len(rangeDelIters) > 0 {
    1066            1 :                 mi := &keyspanimpl.MergingIter{}
    1067            1 :                 mi.Init(c.comparer, keyspan.NoopTransform, new(keyspanimpl.MergingBuffers), rangeDelIters...)
    1068            1 :                 rangeDelIter = mi
    1069            1 :         }
    1070              : 
    1071              :         // If there are range key iterators, we need to combine them using
    1072              :         // keyspanimpl.MergingIter, and then interleave them among the points.
    1073            1 :         if len(rangeKeyIters) > 0 {
    1074            1 :                 mi := &keyspanimpl.MergingIter{}
    1075            1 :                 mi.Init(c.comparer, keyspan.NoopTransform, new(keyspanimpl.MergingBuffers), rangeKeyIters...)
    1076            1 :                 // TODO(radu): why do we have a defragmenter here but not above?
    1077            1 :                 di := &keyspan.DefragmentingIter{}
    1078            1 :                 di.Init(c.comparer, mi, keyspan.DefragmentInternal, keyspan.StaticDefragmentReducer, new(keyspan.DefragmentingBuffers))
    1079            1 :                 rangeKeyIter = di
    1080            1 :         }
    1081            1 :         return pointIter, rangeDelIter, rangeKeyIter, nil
    1082              : }
    1083              : 
    1084              : func (c *compaction) newRangeDelIter(
    1085              :         newIters tableNewIters,
    1086              :         f manifest.LevelFile,
    1087              :         opts IterOptions,
    1088              :         iiopts internalIterOpts,
    1089              :         l manifest.Layer,
    1090            1 : ) (*noCloseIter, error) {
    1091            1 :         opts.layer = l
    1092            1 :         iterSet, err := newIters(context.Background(), f.TableMetadata, &opts,
    1093            1 :                 internalIterOpts{
    1094            1 :                         compaction: true,
    1095            1 :                         readEnv:    sstable.ReadEnv{Block: block.ReadEnv{BufferPool: &c.bufferPool}},
    1096            1 :                 }, iterRangeDeletions)
    1097            1 :         if err != nil {
    1098            0 :                 return nil, err
    1099            1 :         } else if iterSet.rangeDeletion == nil {
    1100            1 :                 // The file doesn't contain any range deletions.
    1101            1 :                 return nil, nil
    1102            1 :         }
    1103              :         // Ensure that rangeDelIter is not closed until the compaction is
    1104              :         // finished. This is necessary because range tombstone processing
    1105              :         // requires the range tombstones to be held in memory for up to the
    1106              :         // lifetime of the compaction.
    1107            1 :         return &noCloseIter{iterSet.rangeDeletion}, nil
    1108              : }
    1109              : 
    1110            0 : func (c *compaction) String() string {
    1111            0 :         if len(c.flushing) != 0 {
    1112            0 :                 return "flush\n"
    1113            0 :         }
    1114              : 
    1115            0 :         var buf bytes.Buffer
    1116            0 :         for level := c.startLevel.level; level <= c.outputLevel.level; level++ {
    1117            0 :                 i := level - c.startLevel.level
    1118            0 :                 fmt.Fprintf(&buf, "%d:", level)
    1119            0 :                 for f := range c.inputs[i].files.All() {
    1120            0 :                         fmt.Fprintf(&buf, " %s:%s-%s", f.TableNum, f.Smallest(), f.Largest())
    1121            0 :                 }
    1122            0 :                 fmt.Fprintf(&buf, "\n")
    1123              :         }
    1124            0 :         return buf.String()
    1125              : }
    1126              : 
    1127              : type manualCompaction struct {
    1128              :         // id is for internal bookkeeping.
    1129              :         id uint64
    1130              :         // Count of the retries due to concurrent compaction to overlapping levels.
    1131              :         retries     int
    1132              :         level       int
    1133              :         outputLevel int
    1134              :         done        chan error
    1135              :         start       []byte
    1136              :         end         []byte
    1137              :         split       bool
    1138              : }
    1139              : 
    1140              : type readCompaction struct {
    1141              :         level int
    1142              :         // [start, end] key ranges are used for de-duping.
    1143              :         start []byte
    1144              :         end   []byte
    1145              : 
    1146              :         // The file associated with the compaction.
    1147              :         // If the file no longer belongs in the same
    1148              :         // level, then we skip the compaction.
    1149              :         tableNum base.TableNum
    1150              : }
    1151              : 
    1152            1 : func (d *DB) addInProgressCompaction(c *compaction) {
    1153            1 :         d.mu.compact.inProgress[c] = struct{}{}
    1154            1 :         var isBase, isIntraL0 bool
    1155            1 :         for _, cl := range c.inputs {
    1156            1 :                 for f := range cl.files.All() {
    1157            1 :                         if f.IsCompacting() {
    1158            0 :                                 d.opts.Logger.Fatalf("L%d->L%d: %s already being compacted", c.startLevel.level, c.outputLevel.level, f.TableNum)
    1159            0 :                         }
    1160            1 :                         f.SetCompactionState(manifest.CompactionStateCompacting)
    1161            1 :                         if c.startLevel != nil && c.outputLevel != nil && c.startLevel.level == 0 {
    1162            1 :                                 if c.outputLevel.level == 0 {
    1163            1 :                                         f.IsIntraL0Compacting = true
    1164            1 :                                         isIntraL0 = true
    1165            1 :                                 } else {
    1166            1 :                                         isBase = true
    1167            1 :                                 }
    1168              :                         }
    1169              :                 }
    1170              :         }
    1171              : 
    1172            1 :         if isIntraL0 || isBase {
    1173            1 :                 l0Inputs := []manifest.LevelSlice{c.startLevel.files}
    1174            1 :                 if isIntraL0 {
    1175            1 :                         l0Inputs = append(l0Inputs, c.outputLevel.files)
    1176            1 :                 }
    1177            1 :                 if err := d.mu.versions.l0Organizer.UpdateStateForStartedCompaction(l0Inputs, isBase); err != nil {
    1178            0 :                         d.opts.Logger.Fatalf("could not update state for compaction: %s", err)
    1179            0 :                 }
    1180              :         }
    1181              : }
    1182              : 
    1183              : // Removes compaction markers from files in a compaction. The rollback parameter
    1184              : // indicates whether the compaction state should be rolled back to its original
    1185              : // state in the case of an unsuccessful compaction.
    1186              : //
    1187              : // DB.mu must be held when calling this method, however this method can drop and
    1188              : // re-acquire that mutex. All writes to the manifest for this compaction should
    1189              : // have completed by this point.
    1190            1 : func (d *DB) clearCompactingState(c *compaction, rollback bool) {
    1191            1 :         c.versionEditApplied = true
    1192            1 :         for _, cl := range c.inputs {
    1193            1 :                 for f := range cl.files.All() {
    1194            1 :                         if !f.IsCompacting() {
    1195            0 :                                 d.opts.Logger.Fatalf("L%d->L%d: %s not being compacted", c.startLevel.level, c.outputLevel.level, f.TableNum)
    1196            0 :                         }
    1197            1 :                         if !rollback {
    1198            1 :                                 // On success all compactions other than move and delete-only compactions
    1199            1 :                                 // transition the file into the Compacted state. Move-compacted files
    1200            1 :                                 // become eligible for compaction again and transition back to NotCompacting.
    1201            1 :                                 // Delete-only compactions could, on rare occasion, leave files untouched
    1202            1 :                                 // (eg. if files have a loose bound), so we revert them all to NotCompacting
    1203            1 :                                 // just in case they need to be compacted again.
    1204            1 :                                 if c.kind != compactionKindMove && c.kind != compactionKindDeleteOnly {
    1205            1 :                                         f.SetCompactionState(manifest.CompactionStateCompacted)
    1206            1 :                                 } else {
    1207            1 :                                         f.SetCompactionState(manifest.CompactionStateNotCompacting)
    1208            1 :                                 }
    1209            1 :                         } else {
    1210            1 :                                 // Else, on rollback, all input files unconditionally transition back to
    1211            1 :                                 // NotCompacting.
    1212            1 :                                 f.SetCompactionState(manifest.CompactionStateNotCompacting)
    1213            1 :                         }
    1214            1 :                         f.IsIntraL0Compacting = false
    1215              :                 }
    1216              :         }
    1217            1 :         l0InProgress := inProgressL0Compactions(d.getInProgressCompactionInfoLocked(c))
    1218            1 :         func() {
    1219            1 :                 // InitCompactingFileInfo requires that no other manifest writes be
    1220            1 :                 // happening in parallel with it, i.e. we're not in the midst of installing
    1221            1 :                 // another version. Otherwise, it's possible that we've created another
    1222            1 :                 // L0Sublevels instance, but not added it to the versions list, causing
    1223            1 :                 // all the indices in TableMetadata to be inaccurate. To ensure this,
    1224            1 :                 // grab the manifest lock.
    1225            1 :                 d.mu.versions.logLock()
    1226            1 :                 // It is a bit peculiar that we are fiddling with th current version state
    1227            1 :                 // in a separate critical section from when this version was installed.
    1228            1 :                 // But this fiddling is necessary if the compaction failed. When the
    1229            1 :                 // compaction succeeded, we've already done this in UpdateVersionLocked, so
    1230            1 :                 // this seems redundant. Anyway, we clear the pickedCompactionCache since we
    1231            1 :                 // may be able to pick a better compaction (though when this compaction
    1232            1 :                 // succeeded we've also cleared the cache in UpdateVersionLocked).
    1233            1 :                 defer d.mu.versions.logUnlockAndInvalidatePickedCompactionCache()
    1234            1 :                 d.mu.versions.l0Organizer.InitCompactingFileInfo(l0InProgress)
    1235            1 :         }()
    1236              : }
    1237              : 
    1238            1 : func (d *DB) calculateDiskAvailableBytes() uint64 {
    1239            1 :         space, err := d.opts.FS.GetDiskUsage(d.dirname)
    1240            1 :         if err != nil {
    1241            1 :                 if !errors.Is(err, vfs.ErrUnsupported) {
    1242            0 :                         d.opts.EventListener.BackgroundError(err)
    1243            0 :                 }
    1244              :                 // Return the last value we managed to obtain.
    1245            1 :                 return d.diskAvailBytes.Load()
    1246              :         }
    1247              : 
    1248            1 :         d.lowDiskSpaceReporter.Report(space.AvailBytes, space.TotalBytes, d.opts.EventListener)
    1249            1 :         d.diskAvailBytes.Store(space.AvailBytes)
    1250            1 :         return space.AvailBytes
    1251              : }
    1252              : 
    1253              : // maybeScheduleFlush schedules a flush if necessary.
    1254              : //
    1255              : // d.mu must be held when calling this.
    1256            1 : func (d *DB) maybeScheduleFlush() {
    1257            1 :         if d.mu.compact.flushing || d.closed.Load() != nil || d.opts.ReadOnly {
    1258            1 :                 return
    1259            1 :         }
    1260            1 :         if len(d.mu.mem.queue) <= 1 {
    1261            1 :                 return
    1262            1 :         }
    1263              : 
    1264            1 :         if !d.passedFlushThreshold() {
    1265            1 :                 return
    1266            1 :         }
    1267              : 
    1268            1 :         d.mu.compact.flushing = true
    1269            1 :         go d.flush()
    1270              : }
    1271              : 
    1272            1 : func (d *DB) passedFlushThreshold() bool {
    1273            1 :         var n int
    1274            1 :         var size uint64
    1275            1 :         for ; n < len(d.mu.mem.queue)-1; n++ {
    1276            1 :                 if !d.mu.mem.queue[n].readyForFlush() {
    1277            1 :                         break
    1278              :                 }
    1279            1 :                 if d.mu.mem.queue[n].flushForced {
    1280            1 :                         // A flush was forced. Pretend the memtable size is the configured
    1281            1 :                         // size. See minFlushSize below.
    1282            1 :                         size += d.opts.MemTableSize
    1283            1 :                 } else {
    1284            1 :                         size += d.mu.mem.queue[n].totalBytes()
    1285            1 :                 }
    1286              :         }
    1287            1 :         if n == 0 {
    1288            1 :                 // None of the immutable memtables are ready for flushing.
    1289            1 :                 return false
    1290            1 :         }
    1291              : 
    1292              :         // Only flush once the sum of the queued memtable sizes exceeds half the
    1293              :         // configured memtable size. This prevents flushing of memtables at startup
    1294              :         // while we're undergoing the ramp period on the memtable size. See
    1295              :         // DB.newMemTable().
    1296            1 :         minFlushSize := d.opts.MemTableSize / 2
    1297            1 :         return size >= minFlushSize
    1298              : }
    1299              : 
    1300            1 : func (d *DB) maybeScheduleDelayedFlush(tbl *memTable, dur time.Duration) {
    1301            1 :         var mem *flushableEntry
    1302            1 :         for _, m := range d.mu.mem.queue {
    1303            1 :                 if m.flushable == tbl {
    1304            1 :                         mem = m
    1305            1 :                         break
    1306              :                 }
    1307              :         }
    1308            1 :         if mem == nil || mem.flushForced {
    1309            1 :                 return
    1310            1 :         }
    1311            1 :         deadline := d.timeNow().Add(dur)
    1312            1 :         if !mem.delayedFlushForcedAt.IsZero() && deadline.After(mem.delayedFlushForcedAt) {
    1313            1 :                 // Already scheduled to flush sooner than within `dur`.
    1314            1 :                 return
    1315            1 :         }
    1316            1 :         mem.delayedFlushForcedAt = deadline
    1317            1 :         go func() {
    1318            1 :                 timer := time.NewTimer(dur)
    1319            1 :                 defer timer.Stop()
    1320            1 : 
    1321            1 :                 select {
    1322            1 :                 case <-d.closedCh:
    1323            1 :                         return
    1324            1 :                 case <-mem.flushed:
    1325            1 :                         return
    1326            1 :                 case <-timer.C:
    1327            1 :                         d.commit.mu.Lock()
    1328            1 :                         defer d.commit.mu.Unlock()
    1329            1 :                         d.mu.Lock()
    1330            1 :                         defer d.mu.Unlock()
    1331            1 : 
    1332            1 :                         // NB: The timer may fire concurrently with a call to Close.  If a
    1333            1 :                         // Close call beat us to acquiring d.mu, d.closed holds ErrClosed,
    1334            1 :                         // and it's too late to flush anything. Otherwise, the Close call
    1335            1 :                         // will block on locking d.mu until we've finished scheduling the
    1336            1 :                         // flush and set `d.mu.compact.flushing` to true. Close will wait
    1337            1 :                         // for the current flush to complete.
    1338            1 :                         if d.closed.Load() != nil {
    1339            1 :                                 return
    1340            1 :                         }
    1341              : 
    1342            1 :                         if d.mu.mem.mutable == tbl {
    1343            1 :                                 _ = d.makeRoomForWrite(nil)
    1344            1 :                         } else {
    1345            1 :                                 mem.flushForced = true
    1346            1 :                         }
    1347            1 :                         d.maybeScheduleFlush()
    1348              :                 }
    1349              :         }()
    1350              : }
    1351              : 
    1352            1 : func (d *DB) flush() {
    1353            1 :         pprof.Do(context.Background(), flushLabels, func(context.Context) {
    1354            1 :                 flushingWorkStart := crtime.NowMono()
    1355            1 :                 d.mu.Lock()
    1356            1 :                 defer d.mu.Unlock()
    1357            1 :                 idleDuration := flushingWorkStart.Sub(d.mu.compact.noOngoingFlushStartTime)
    1358            1 :                 var bytesFlushed uint64
    1359            1 :                 var err error
    1360            1 :                 if bytesFlushed, err = d.flush1(); err != nil {
    1361            1 :                         // TODO(peter): count consecutive flush errors and backoff.
    1362            1 :                         d.opts.EventListener.BackgroundError(err)
    1363            1 :                 }
    1364            1 :                 d.mu.compact.flushing = false
    1365            1 :                 d.mu.compact.noOngoingFlushStartTime = crtime.NowMono()
    1366            1 :                 workDuration := d.mu.compact.noOngoingFlushStartTime.Sub(flushingWorkStart)
    1367            1 :                 d.mu.compact.flushWriteThroughput.Bytes += int64(bytesFlushed)
    1368            1 :                 d.mu.compact.flushWriteThroughput.WorkDuration += workDuration
    1369            1 :                 d.mu.compact.flushWriteThroughput.IdleDuration += idleDuration
    1370            1 :                 // More flush work may have arrived while we were flushing, so schedule
    1371            1 :                 // another flush if needed.
    1372            1 :                 d.maybeScheduleFlush()
    1373            1 :                 // Let the CompactionScheduler know, so that it can react immediately to
    1374            1 :                 // an increase in DB.GetAllowedWithoutPermission.
    1375            1 :                 d.opts.Experimental.CompactionScheduler.UpdateGetAllowedWithoutPermission()
    1376            1 :                 // The flush may have produced too many files in a level, so schedule a
    1377            1 :                 // compaction if needed.
    1378            1 :                 d.maybeScheduleCompaction()
    1379            1 :                 d.mu.compact.cond.Broadcast()
    1380              :         })
    1381              : }
    1382              : 
    1383              : // runIngestFlush is used to generate a flush version edit for sstables which
    1384              : // were ingested as flushables. Both DB.mu and the manifest lock must be held
    1385              : // while runIngestFlush is called.
    1386            1 : func (d *DB) runIngestFlush(c *compaction) (*manifest.VersionEdit, error) {
    1387            1 :         if len(c.flushing) != 1 {
    1388            0 :                 panic("pebble: ingestedFlushable must be flushed one at a time.")
    1389              :         }
    1390              : 
    1391              :         // Finding the target level for ingestion must use the latest version
    1392              :         // after the logLock has been acquired.
    1393            1 :         version := d.mu.versions.currentVersion()
    1394            1 : 
    1395            1 :         baseLevel := d.mu.versions.picker.getBaseLevel()
    1396            1 :         ve := &manifest.VersionEdit{}
    1397            1 :         var ingestSplitFiles []ingestSplitFile
    1398            1 :         ingestFlushable := c.flushing[0].flushable.(*ingestedFlushable)
    1399            1 : 
    1400            1 :         updateLevelMetricsOnExcise := func(m *manifest.TableMetadata, level int, added []manifest.NewTableEntry) {
    1401            1 :                 levelMetrics := c.metrics[level]
    1402            1 :                 if levelMetrics == nil {
    1403            1 :                         levelMetrics = &LevelMetrics{}
    1404            1 :                         c.metrics[level] = levelMetrics
    1405            1 :                 }
    1406            1 :                 levelMetrics.TablesCount--
    1407            1 :                 levelMetrics.TablesSize -= int64(m.Size)
    1408            1 :                 levelMetrics.EstimatedReferencesSize -= m.EstimatedReferenceSize()
    1409            1 :                 for i := range added {
    1410            1 :                         levelMetrics.TablesCount++
    1411            1 :                         levelMetrics.TablesSize += int64(added[i].Meta.Size)
    1412            1 :                         levelMetrics.EstimatedReferencesSize += added[i].Meta.EstimatedReferenceSize()
    1413            1 :                 }
    1414              :         }
    1415              : 
    1416            1 :         suggestSplit := d.opts.Experimental.IngestSplit != nil && d.opts.Experimental.IngestSplit() &&
    1417            1 :                 d.FormatMajorVersion() >= FormatVirtualSSTables
    1418            1 : 
    1419            1 :         if suggestSplit || ingestFlushable.exciseSpan.Valid() {
    1420            1 :                 // We could add deleted files to ve.
    1421            1 :                 ve.DeletedTables = make(map[manifest.DeletedTableEntry]*manifest.TableMetadata)
    1422            1 :         }
    1423              : 
    1424            1 :         ctx := context.Background()
    1425            1 :         overlapChecker := &overlapChecker{
    1426            1 :                 comparer: d.opts.Comparer,
    1427            1 :                 newIters: d.newIters,
    1428            1 :                 opts: IterOptions{
    1429            1 :                         logger:   d.opts.Logger,
    1430            1 :                         Category: categoryIngest,
    1431            1 :                 },
    1432            1 :                 v: version,
    1433            1 :         }
    1434            1 :         replacedTables := make(map[base.TableNum][]manifest.NewTableEntry)
    1435            1 :         for _, file := range ingestFlushable.files {
    1436            1 :                 var fileToSplit *manifest.TableMetadata
    1437            1 :                 var level int
    1438            1 : 
    1439            1 :                 // This file fits perfectly within the excise span, so we can slot it at L6.
    1440            1 :                 if ingestFlushable.exciseSpan.Valid() &&
    1441            1 :                         ingestFlushable.exciseSpan.Contains(d.cmp, file.Smallest()) &&
    1442            1 :                         ingestFlushable.exciseSpan.Contains(d.cmp, file.Largest()) {
    1443            1 :                         level = 6
    1444            1 :                 } else {
    1445            1 :                         // TODO(radu): this can perform I/O; we should not do this while holding DB.mu.
    1446            1 :                         lsmOverlap, err := overlapChecker.DetermineLSMOverlap(ctx, file.UserKeyBounds())
    1447            1 :                         if err != nil {
    1448            0 :                                 return nil, err
    1449            0 :                         }
    1450            1 :                         level, fileToSplit, err = ingestTargetLevel(
    1451            1 :                                 ctx, d.cmp, lsmOverlap, baseLevel, d.mu.compact.inProgress, file, suggestSplit,
    1452            1 :                         )
    1453            1 :                         if err != nil {
    1454            0 :                                 return nil, err
    1455            0 :                         }
    1456              :                 }
    1457              : 
    1458              :                 // Add the current flushableIngest file to the version.
    1459            1 :                 ve.NewTables = append(ve.NewTables, manifest.NewTableEntry{Level: level, Meta: file})
    1460            1 :                 if fileToSplit != nil {
    1461            1 :                         ingestSplitFiles = append(ingestSplitFiles, ingestSplitFile{
    1462            1 :                                 ingestFile: file,
    1463            1 :                                 splitFile:  fileToSplit,
    1464            1 :                                 level:      level,
    1465            1 :                         })
    1466            1 :                 }
    1467            1 :                 levelMetrics := c.metrics[level]
    1468            1 :                 if levelMetrics == nil {
    1469            1 :                         levelMetrics = &LevelMetrics{}
    1470            1 :                         c.metrics[level] = levelMetrics
    1471            1 :                 }
    1472            1 :                 levelMetrics.TableBytesIngested += file.Size
    1473            1 :                 levelMetrics.TablesIngested++
    1474              :         }
    1475            1 :         if ingestFlushable.exciseSpan.Valid() {
    1476            1 :                 exciseBounds := ingestFlushable.exciseSpan.UserKeyBounds()
    1477            1 :                 // Iterate through all levels and find files that intersect with exciseSpan.
    1478            1 :                 for layer, ls := range version.AllLevelsAndSublevels() {
    1479            1 :                         for m := range ls.Overlaps(d.cmp, ingestFlushable.exciseSpan.UserKeyBounds()).All() {
    1480            1 :                                 leftTable, rightTable, err := d.exciseTable(context.TODO(), exciseBounds, m, layer.Level(), tightExciseBounds)
    1481            1 :                                 if err != nil {
    1482            0 :                                         return nil, err
    1483            0 :                                 }
    1484            1 :                                 newFiles := applyExciseToVersionEdit(ve, m, leftTable, rightTable, layer.Level())
    1485            1 :                                 replacedTables[m.TableNum] = newFiles
    1486            1 :                                 updateLevelMetricsOnExcise(m, layer.Level(), newFiles)
    1487              :                         }
    1488              :                 }
    1489              :         }
    1490              : 
    1491            1 :         if len(ingestSplitFiles) > 0 {
    1492            1 :                 if err := d.ingestSplit(context.TODO(), ve, updateLevelMetricsOnExcise, ingestSplitFiles, replacedTables); err != nil {
    1493            0 :                         return nil, err
    1494            0 :                 }
    1495              :         }
    1496              : 
    1497            1 :         return ve, nil
    1498              : }
    1499              : 
    1500              : // flush runs a compaction that copies the immutable memtables from memory to
    1501              : // disk.
    1502              : //
    1503              : // d.mu must be held when calling this, but the mutex may be dropped and
    1504              : // re-acquired during the course of this method.
    1505            1 : func (d *DB) flush1() (bytesFlushed uint64, err error) {
    1506            1 :         // NB: The flushable queue can contain flushables of type ingestedFlushable.
    1507            1 :         // The sstables in ingestedFlushable.files must be placed into the appropriate
    1508            1 :         // level in the lsm. Let's say the flushable queue contains a prefix of
    1509            1 :         // regular immutable memtables, then an ingestedFlushable, and then the
    1510            1 :         // mutable memtable. When the flush of the ingestedFlushable is performed,
    1511            1 :         // it needs an updated view of the lsm. That is, the prefix of immutable
    1512            1 :         // memtables must have already been flushed. Similarly, if there are two
    1513            1 :         // contiguous ingestedFlushables in the queue, then the first flushable must
    1514            1 :         // be flushed, so that the second flushable can see an updated view of the
    1515            1 :         // lsm.
    1516            1 :         //
    1517            1 :         // Given the above, we restrict flushes to either some prefix of regular
    1518            1 :         // memtables, or a single flushable of type ingestedFlushable. The DB.flush
    1519            1 :         // function will call DB.maybeScheduleFlush again, so a new flush to finish
    1520            1 :         // the remaining flush work should be scheduled right away.
    1521            1 :         //
    1522            1 :         // NB: Large batches placed in the flushable queue share the WAL with the
    1523            1 :         // previous memtable in the queue. We must ensure the property that both the
    1524            1 :         // large batch and the memtable with which it shares a WAL are flushed
    1525            1 :         // together. The property ensures that the minimum unflushed log number
    1526            1 :         // isn't incremented incorrectly. Since a flushableBatch.readyToFlush always
    1527            1 :         // returns true, and since the large batch will always be placed right after
    1528            1 :         // the memtable with which it shares a WAL, the property is naturally
    1529            1 :         // ensured. The large batch will always be placed after the memtable with
    1530            1 :         // which it shares a WAL because we ensure it in DB.commitWrite by holding
    1531            1 :         // the commitPipeline.mu and then holding DB.mu. As an extra defensive
    1532            1 :         // measure, if we try to flush the memtable without also flushing the
    1533            1 :         // flushable batch in the same flush, since the memtable and flushableBatch
    1534            1 :         // have the same logNum, the logNum invariant check below will trigger.
    1535            1 :         var n, inputs int
    1536            1 :         var inputBytes uint64
    1537            1 :         var ingest bool
    1538            1 :         for ; n < len(d.mu.mem.queue)-1; n++ {
    1539            1 :                 if f, ok := d.mu.mem.queue[n].flushable.(*ingestedFlushable); ok {
    1540            1 :                         if n == 0 {
    1541            1 :                                 // The first flushable is of type ingestedFlushable. Since these
    1542            1 :                                 // must be flushed individually, we perform a flush for just
    1543            1 :                                 // this.
    1544            1 :                                 if !f.readyForFlush() {
    1545            0 :                                         // This check is almost unnecessary, but we guard against it
    1546            0 :                                         // just in case this invariant changes in the future.
    1547            0 :                                         panic("pebble: ingestedFlushable should always be ready to flush.")
    1548              :                                 }
    1549              :                                 // By setting n = 1, we ensure that the first flushable(n == 0)
    1550              :                                 // is scheduled for a flush. The number of tables added is equal to the
    1551              :                                 // number of files in the ingest operation.
    1552            1 :                                 n = 1
    1553            1 :                                 inputs = len(f.files)
    1554            1 :                                 ingest = true
    1555            1 :                                 break
    1556            1 :                         } else {
    1557            1 :                                 // There was some prefix of flushables which weren't of type
    1558            1 :                                 // ingestedFlushable. So, perform a flush for those.
    1559            1 :                                 break
    1560              :                         }
    1561              :                 }
    1562            1 :                 if !d.mu.mem.queue[n].readyForFlush() {
    1563            0 :                         break
    1564              :                 }
    1565            1 :                 inputBytes += d.mu.mem.queue[n].inuseBytes()
    1566              :         }
    1567            1 :         if n == 0 {
    1568            0 :                 // None of the immutable memtables are ready for flushing.
    1569            0 :                 return 0, nil
    1570            0 :         }
    1571            1 :         if !ingest {
    1572            1 :                 // Flushes of memtables add the prefix of n memtables from the flushable
    1573            1 :                 // queue.
    1574            1 :                 inputs = n
    1575            1 :         }
    1576              : 
    1577              :         // Require that every memtable being flushed has a log number less than the
    1578              :         // new minimum unflushed log number.
    1579            1 :         minUnflushedLogNum := d.mu.mem.queue[n].logNum
    1580            1 :         if !d.opts.DisableWAL {
    1581            1 :                 for i := 0; i < n; i++ {
    1582            1 :                         if logNum := d.mu.mem.queue[i].logNum; logNum >= minUnflushedLogNum {
    1583            0 :                                 panic(errors.AssertionFailedf("logNum invariant violated: flushing %d items; %d:type=%T,logNum=%d; %d:type=%T,logNum=%d",
    1584            0 :                                         n,
    1585            0 :                                         i, d.mu.mem.queue[i].flushable, logNum,
    1586            0 :                                         n, d.mu.mem.queue[n].flushable, minUnflushedLogNum))
    1587              :                         }
    1588              :                 }
    1589              :         }
    1590              : 
    1591            1 :         c, err := newFlush(d.opts, d.mu.versions.currentVersion(), d.mu.versions.l0Organizer,
    1592            1 :                 d.mu.versions.picker.getBaseLevel(), d.mu.mem.queue[:n], d.timeNow(), d.TableFormat(), d.determineCompactionValueSeparation)
    1593            1 :         if err != nil {
    1594            0 :                 return 0, err
    1595            0 :         }
    1596            1 :         d.addInProgressCompaction(c)
    1597            1 : 
    1598            1 :         jobID := d.newJobIDLocked()
    1599            1 :         info := FlushInfo{
    1600            1 :                 JobID:      int(jobID),
    1601            1 :                 Input:      inputs,
    1602            1 :                 InputBytes: inputBytes,
    1603            1 :                 Ingest:     ingest,
    1604            1 :         }
    1605            1 :         d.opts.EventListener.FlushBegin(info)
    1606            1 : 
    1607            1 :         startTime := d.timeNow()
    1608            1 : 
    1609            1 :         var ve *manifest.VersionEdit
    1610            1 :         var stats compact.Stats
    1611            1 :         // To determine the target level of the files in the ingestedFlushable, we
    1612            1 :         // need to acquire the logLock, and not release it for that duration. Since
    1613            1 :         // UpdateVersionLocked acquires it anyway, we create the VersionEdit for
    1614            1 :         // ingestedFlushable outside runCompaction. For all other flush cases, we
    1615            1 :         // construct the VersionEdit inside runCompaction.
    1616            1 :         var compactionErr error
    1617            1 :         if c.kind != compactionKindIngestedFlushable {
    1618            1 :                 ve, stats, compactionErr = d.runCompaction(jobID, c)
    1619            1 :         }
    1620              : 
    1621            1 :         err = d.mu.versions.UpdateVersionLocked(func() (versionUpdate, error) {
    1622            1 :                 err := compactionErr
    1623            1 :                 if c.kind == compactionKindIngestedFlushable {
    1624            1 :                         ve, err = d.runIngestFlush(c)
    1625            1 :                 }
    1626            1 :                 info.Duration = d.timeNow().Sub(startTime)
    1627            1 :                 if err != nil {
    1628            1 :                         return versionUpdate{}, err
    1629            1 :                 }
    1630              : 
    1631            1 :                 validateVersionEdit(ve, d.opts.Comparer.ValidateKey, d.opts.Comparer.FormatKey, d.opts.Logger)
    1632            1 :                 for i := range ve.NewTables {
    1633            1 :                         e := &ve.NewTables[i]
    1634            1 :                         info.Output = append(info.Output, e.Meta.TableInfo())
    1635            1 :                         // Ingested tables are not necessarily flushed to L0. Record the level of
    1636            1 :                         // each ingested file explicitly.
    1637            1 :                         if ingest {
    1638            1 :                                 info.IngestLevels = append(info.IngestLevels, e.Level)
    1639            1 :                         }
    1640              :                 }
    1641              : 
    1642              :                 // The flush succeeded or it produced an empty sstable. In either case we
    1643              :                 // want to bump the minimum unflushed log number to the log number of the
    1644              :                 // oldest unflushed memtable.
    1645            1 :                 ve.MinUnflushedLogNum = minUnflushedLogNum
    1646            1 :                 if c.kind != compactionKindIngestedFlushable {
    1647            1 :                         l0Metrics := c.metrics[0]
    1648            1 :                         if d.opts.DisableWAL {
    1649            1 :                                 // If the WAL is disabled, every flushable has a zero [logSize],
    1650            1 :                                 // resulting in zero bytes in. Instead, use the number of bytes we
    1651            1 :                                 // flushed as the BytesIn. This ensures we get a reasonable w-amp
    1652            1 :                                 // calculation even when the WAL is disabled.
    1653            1 :                                 l0Metrics.TableBytesIn = l0Metrics.TableBytesFlushed + l0Metrics.BlobBytesFlushed
    1654            1 :                         } else {
    1655            1 :                                 for i := 0; i < n; i++ {
    1656            1 :                                         l0Metrics.TableBytesIn += d.mu.mem.queue[i].logSize
    1657            1 :                                 }
    1658              :                         }
    1659            1 :                 } else {
    1660            1 :                         // c.kind == compactionKindIngestedFlushable && we could have deleted files due
    1661            1 :                         // to ingest-time splits or excises.
    1662            1 :                         ingestFlushable := c.flushing[0].flushable.(*ingestedFlushable)
    1663            1 :                         for c2 := range d.mu.compact.inProgress {
    1664            1 :                                 // Check if this compaction overlaps with the excise span. Note that just
    1665            1 :                                 // checking if the inputs individually overlap with the excise span
    1666            1 :                                 // isn't sufficient; for instance, a compaction could have [a,b] and [e,f]
    1667            1 :                                 // as inputs and write it all out as [a,b,e,f] in one sstable. If we're
    1668            1 :                                 // doing a [c,d) excise at the same time as this compaction, we will have
    1669            1 :                                 // to error out the whole compaction as we can't guarantee it hasn't/won't
    1670            1 :                                 // write a file overlapping with the excise span.
    1671            1 :                                 if ingestFlushable.exciseSpan.OverlapsInternalKeyRange(d.cmp, c2.smallest, c2.largest) {
    1672            1 :                                         c2.cancel.Store(true)
    1673            1 :                                 }
    1674              :                         }
    1675              : 
    1676            1 :                         if len(ve.DeletedTables) > 0 {
    1677            1 :                                 // Iterate through all other compactions, and check if their inputs have
    1678            1 :                                 // been replaced due to an ingest-time split or excise. In that case,
    1679            1 :                                 // cancel the compaction.
    1680            1 :                                 for c2 := range d.mu.compact.inProgress {
    1681            1 :                                         for i := range c2.inputs {
    1682            1 :                                                 for f := range c2.inputs[i].files.All() {
    1683            1 :                                                         if _, ok := ve.DeletedTables[manifest.DeletedTableEntry{FileNum: f.TableNum, Level: c2.inputs[i].level}]; ok {
    1684            1 :                                                                 c2.cancel.Store(true)
    1685            1 :                                                                 break
    1686              :                                                         }
    1687              :                                                 }
    1688              :                                         }
    1689              :                                 }
    1690              :                         }
    1691              :                 }
    1692            1 :                 return versionUpdate{
    1693            1 :                         VE:                      ve,
    1694            1 :                         JobID:                   jobID,
    1695            1 :                         Metrics:                 c.metrics,
    1696            1 :                         InProgressCompactionsFn: func() []compactionInfo { return d.getInProgressCompactionInfoLocked(c) },
    1697              :                 }, nil
    1698              :         })
    1699              : 
    1700              :         // If err != nil, then the flush will be retried, and we will recalculate
    1701              :         // these metrics.
    1702            1 :         if err == nil {
    1703            1 :                 d.mu.snapshots.cumulativePinnedCount += stats.CumulativePinnedKeys
    1704            1 :                 d.mu.snapshots.cumulativePinnedSize += stats.CumulativePinnedSize
    1705            1 :                 d.mu.versions.metrics.Keys.MissizedTombstonesCount += stats.CountMissizedDels
    1706            1 :         }
    1707              : 
    1708            1 :         d.clearCompactingState(c, err != nil)
    1709            1 :         delete(d.mu.compact.inProgress, c)
    1710            1 :         d.mu.versions.incrementCompactions(c.kind, c.extraLevels, c.pickerMetrics, c.bytesWritten.Load(), err)
    1711            1 : 
    1712            1 :         var flushed flushableList
    1713            1 :         if err == nil {
    1714            1 :                 flushed = d.mu.mem.queue[:n]
    1715            1 :                 d.mu.mem.queue = d.mu.mem.queue[n:]
    1716            1 :                 d.updateReadStateLocked(d.opts.DebugCheck)
    1717            1 :                 d.updateTableStatsLocked(ve.NewTables)
    1718            1 :                 if ingest {
    1719            1 :                         d.mu.versions.metrics.Flush.AsIngestCount++
    1720            1 :                         for _, l := range c.metrics {
    1721            1 :                                 if l != nil {
    1722            1 :                                         d.mu.versions.metrics.Flush.AsIngestBytes += l.TableBytesIngested
    1723            1 :                                         d.mu.versions.metrics.Flush.AsIngestTableCount += l.TablesIngested
    1724            1 :                                 }
    1725              :                         }
    1726              :                 }
    1727            1 :                 d.maybeTransitionSnapshotsToFileOnlyLocked()
    1728              :         }
    1729              :         // Signal FlushEnd after installing the new readState. This helps for unit
    1730              :         // tests that use the callback to trigger a read using an iterator with
    1731              :         // IterOptions.OnlyReadGuaranteedDurable.
    1732            1 :         info.Err = err
    1733            1 :         if info.Err == nil && len(ve.NewTables) == 0 {
    1734            1 :                 info.Err = errEmptyTable
    1735            1 :         }
    1736            1 :         info.Done = true
    1737            1 :         info.TotalDuration = d.timeNow().Sub(startTime)
    1738            1 :         d.opts.EventListener.FlushEnd(info)
    1739            1 : 
    1740            1 :         // The order of these operations matters here for ease of testing.
    1741            1 :         // Removing the reader reference first allows tests to be guaranteed that
    1742            1 :         // the memtable reservation has been released by the time a synchronous
    1743            1 :         // flush returns. readerUnrefLocked may also produce obsolete files so the
    1744            1 :         // call to deleteObsoleteFiles must happen after it.
    1745            1 :         for i := range flushed {
    1746            1 :                 flushed[i].readerUnrefLocked(true)
    1747            1 :         }
    1748              : 
    1749            1 :         d.deleteObsoleteFiles(jobID)
    1750            1 : 
    1751            1 :         // Mark all the memtables we flushed as flushed.
    1752            1 :         for i := range flushed {
    1753            1 :                 close(flushed[i].flushed)
    1754            1 :         }
    1755              : 
    1756            1 :         return inputBytes, err
    1757              : }
    1758              : 
    1759              : // maybeTransitionSnapshotsToFileOnlyLocked transitions any "eventually
    1760              : // file-only" snapshots to be file-only if all their visible state has been
    1761              : // flushed to sstables.
    1762              : //
    1763              : // REQUIRES: d.mu.
    1764            1 : func (d *DB) maybeTransitionSnapshotsToFileOnlyLocked() {
    1765            1 :         earliestUnflushedSeqNum := d.getEarliestUnflushedSeqNumLocked()
    1766            1 :         currentVersion := d.mu.versions.currentVersion()
    1767            1 :         for s := d.mu.snapshots.root.next; s != &d.mu.snapshots.root; {
    1768            1 :                 if s.efos == nil {
    1769            1 :                         s = s.next
    1770            1 :                         continue
    1771              :                 }
    1772            1 :                 overlapsFlushable := false
    1773            1 :                 if base.Visible(earliestUnflushedSeqNum, s.efos.seqNum, base.SeqNumMax) {
    1774            1 :                         // There are some unflushed keys that are still visible to the EFOS.
    1775            1 :                         // Check if any memtables older than the EFOS contain keys within a
    1776            1 :                         // protected range of the EFOS. If no, we can transition.
    1777            1 :                         protectedRanges := make([]bounded, len(s.efos.protectedRanges))
    1778            1 :                         for i := range s.efos.protectedRanges {
    1779            1 :                                 protectedRanges[i] = s.efos.protectedRanges[i]
    1780            1 :                         }
    1781            1 :                         for i := range d.mu.mem.queue {
    1782            1 :                                 if !base.Visible(d.mu.mem.queue[i].logSeqNum, s.efos.seqNum, base.SeqNumMax) {
    1783            1 :                                         // All keys in this memtable are newer than the EFOS. Skip this
    1784            1 :                                         // memtable.
    1785            1 :                                         continue
    1786              :                                 }
    1787              :                                 // NB: computePossibleOverlaps could have false positives, such as if
    1788              :                                 // the flushable is a flushable ingest and not a memtable. In that
    1789              :                                 // case we don't open the sstables to check; we just pessimistically
    1790              :                                 // assume an overlap.
    1791            1 :                                 d.mu.mem.queue[i].computePossibleOverlaps(func(b bounded) shouldContinue {
    1792            1 :                                         overlapsFlushable = true
    1793            1 :                                         return stopIteration
    1794            1 :                                 }, protectedRanges...)
    1795            1 :                                 if overlapsFlushable {
    1796            1 :                                         break
    1797              :                                 }
    1798              :                         }
    1799              :                 }
    1800            1 :                 if overlapsFlushable {
    1801            1 :                         s = s.next
    1802            1 :                         continue
    1803              :                 }
    1804            1 :                 currentVersion.Ref()
    1805            1 : 
    1806            1 :                 // NB: s.efos.transitionToFileOnlySnapshot could close s, in which
    1807            1 :                 // case s.next would be nil. Save it before calling it.
    1808            1 :                 next := s.next
    1809            1 :                 _ = s.efos.transitionToFileOnlySnapshot(currentVersion)
    1810            1 :                 s = next
    1811              :         }
    1812              : }
    1813              : 
    1814              : // maybeScheduleCompactionAsync should be used when
    1815              : // we want to possibly schedule a compaction, but don't
    1816              : // want to eat the cost of running maybeScheduleCompaction.
    1817              : // This method should be launched in a separate goroutine.
    1818              : // d.mu must not be held when this is called.
    1819            0 : func (d *DB) maybeScheduleCompactionAsync() {
    1820            0 :         defer d.compactionSchedulers.Done()
    1821            0 : 
    1822            0 :         d.mu.Lock()
    1823            0 :         d.maybeScheduleCompaction()
    1824            0 :         d.mu.Unlock()
    1825            0 : }
    1826              : 
    1827              : // maybeScheduleCompaction schedules a compaction if necessary.
    1828              : //
    1829              : // WARNING: maybeScheduleCompaction and Schedule must be the only ways that
    1830              : // any compactions are run. These ensure that the pickedCompactionCache is
    1831              : // used and not stale (by ensuring invalidation is done).
    1832              : //
    1833              : // Even compactions that are not scheduled by the CompactionScheduler must be
    1834              : // run using maybeScheduleCompaction, since starting those compactions needs
    1835              : // to invalidate the pickedCompactionCache.
    1836              : //
    1837              : // Requires d.mu to be held.
    1838            1 : func (d *DB) maybeScheduleCompaction() {
    1839            1 :         d.mu.versions.logLock()
    1840            1 :         defer d.mu.versions.logUnlock()
    1841            1 :         env := d.makeCompactionEnvLocked()
    1842            1 :         if env == nil {
    1843            1 :                 return
    1844            1 :         }
    1845              :         // env.inProgressCompactions will become stale once we pick a compaction, so
    1846              :         // it needs to be kept fresh. Also, the pickedCompaction in the
    1847              :         // pickedCompactionCache is not valid if we pick a compaction before using
    1848              :         // it, since those earlier compactions can mark the same file as compacting.
    1849              : 
    1850              :         // Delete-only compactions are expected to be cheap and reduce future
    1851              :         // compaction work, so schedule them directly instead of using the
    1852              :         // CompactionScheduler.
    1853            1 :         if d.tryScheduleDeleteOnlyCompaction() {
    1854            1 :                 env.inProgressCompactions = d.getInProgressCompactionInfoLocked(nil)
    1855            1 :                 d.mu.versions.pickedCompactionCache.invalidate()
    1856            1 :         }
    1857              :         // Download compactions have their own concurrency and do not currently
    1858              :         // interact with CompactionScheduler.
    1859              :         //
    1860              :         // TODO(sumeer): integrate with CompactionScheduler, since these consume
    1861              :         // disk write bandwidth.
    1862            1 :         if d.tryScheduleDownloadCompactions(*env, d.opts.MaxConcurrentDownloads()) {
    1863            1 :                 env.inProgressCompactions = d.getInProgressCompactionInfoLocked(nil)
    1864            1 :                 d.mu.versions.pickedCompactionCache.invalidate()
    1865            1 :         }
    1866              :         // The remaining compactions are scheduled by the CompactionScheduler.
    1867            1 :         if d.mu.versions.pickedCompactionCache.isWaiting() {
    1868            1 :                 // CompactionScheduler already knows that the DB is waiting to run a
    1869            1 :                 // compaction.
    1870            1 :                 return
    1871            1 :         }
    1872              :         // INVARIANT: !pickedCompactionCache.isWaiting. The following loop will
    1873              :         // either exit after successfully starting all the compactions it can pick,
    1874              :         // or will exit with one pickedCompaction in the cache, and isWaiting=true.
    1875            1 :         for {
    1876            1 :                 // Do not have a pickedCompaction in the cache.
    1877            1 :                 pc := d.pickAnyCompaction(*env)
    1878            1 :                 if pc == nil {
    1879            1 :                         return
    1880            1 :                 }
    1881            1 :                 success, grantHandle := d.opts.Experimental.CompactionScheduler.TrySchedule()
    1882            1 :                 if !success {
    1883            1 :                         // Can't run now, but remember this pickedCompaction in the cache.
    1884            1 :                         d.mu.versions.pickedCompactionCache.add(pc)
    1885            1 :                         return
    1886            1 :                 }
    1887            1 :                 d.runPickedCompaction(pc, grantHandle)
    1888            1 :                 env.inProgressCompactions = d.getInProgressCompactionInfoLocked(nil)
    1889              :         }
    1890              : }
    1891              : 
    1892              : // makeCompactionEnv attempts to create a compactionEnv necessary during
    1893              : // compaction picking. If the DB is closed or marked as read-only,
    1894              : // makeCompactionEnv returns nil to indicate that compactions may not be
    1895              : // performed. Else, a new compactionEnv is constructed using the current DB
    1896              : // state.
    1897              : //
    1898              : // Compaction picking needs a coherent view of a Version. For example, we need
    1899              : // to exclude concurrent ingestions from making a decision on which level to
    1900              : // ingest into that conflicts with our compaction decision.
    1901              : //
    1902              : // A pickedCompaction constructed using a compactionEnv must only be used if
    1903              : // the latest Version has not changed.
    1904              : //
    1905              : // REQUIRES: d.mu and d.mu.versions.logLock are held.
    1906            1 : func (d *DB) makeCompactionEnvLocked() *compactionEnv {
    1907            1 :         if d.closed.Load() != nil || d.opts.ReadOnly {
    1908            1 :                 return nil
    1909            1 :         }
    1910            1 :         env := &compactionEnv{
    1911            1 :                 diskAvailBytes:          d.diskAvailBytes.Load(),
    1912            1 :                 earliestSnapshotSeqNum:  d.mu.snapshots.earliest(),
    1913            1 :                 earliestUnflushedSeqNum: d.getEarliestUnflushedSeqNumLocked(),
    1914            1 :                 inProgressCompactions:   d.getInProgressCompactionInfoLocked(nil),
    1915            1 :                 readCompactionEnv: readCompactionEnv{
    1916            1 :                         readCompactions:          &d.mu.compact.readCompactions,
    1917            1 :                         flushing:                 d.mu.compact.flushing || d.passedFlushThreshold(),
    1918            1 :                         rescheduleReadCompaction: &d.mu.compact.rescheduleReadCompaction,
    1919            1 :                 },
    1920            1 :         }
    1921            1 :         if !d.problemSpans.IsEmpty() {
    1922            0 :                 env.problemSpans = &d.problemSpans
    1923            0 :         }
    1924            1 :         return env
    1925              : }
    1926              : 
    1927              : // pickAnyCompaction tries to pick a manual or automatic compaction.
    1928            1 : func (d *DB) pickAnyCompaction(env compactionEnv) (pc *pickedCompaction) {
    1929            1 :         // Pick a score-based compaction first, since a misshapen LSM is bad.
    1930            1 :         if !d.opts.DisableAutomaticCompactions {
    1931            1 :                 if pc = d.mu.versions.picker.pickAutoScore(env); pc != nil {
    1932            1 :                         return pc
    1933            1 :                 }
    1934              :         }
    1935              :         // Pick a manual compaction, if any.
    1936            1 :         if pc = d.pickManualCompaction(env); pc != nil {
    1937            1 :                 return pc
    1938            1 :         }
    1939            1 :         if !d.opts.DisableAutomaticCompactions {
    1940            1 :                 return d.mu.versions.picker.pickAutoNonScore(env)
    1941            1 :         }
    1942            1 :         return nil
    1943              : }
    1944              : 
    1945              : // runPickedCompaction kicks off the provided pickedCompaction. In case the
    1946              : // pickedCompaction is a manual compaction, the corresponding manualCompaction
    1947              : // is removed from d.mu.compact.manual.
    1948              : //
    1949              : // REQUIRES: d.mu and d.mu.versions.logLock is held.
    1950            1 : func (d *DB) runPickedCompaction(pc *pickedCompaction, grantHandle CompactionGrantHandle) {
    1951            1 :         var doneChannel chan error
    1952            1 :         if pc.manualID > 0 {
    1953            1 :                 for i := range d.mu.compact.manual {
    1954            1 :                         if d.mu.compact.manual[i].id == pc.manualID {
    1955            1 :                                 doneChannel = d.mu.compact.manual[i].done
    1956            1 :                                 d.mu.compact.manual = slices.Delete(d.mu.compact.manual, i, i+1)
    1957            1 :                                 d.mu.compact.manualLen.Store(int32(len(d.mu.compact.manual)))
    1958            1 :                                 break
    1959              :                         }
    1960              :                 }
    1961            1 :                 if doneChannel == nil {
    1962            0 :                         panic(errors.AssertionFailedf("did not find manual compaction with id %d", pc.manualID))
    1963              :                 }
    1964              :         }
    1965              : 
    1966            1 :         d.mu.compact.compactingCount++
    1967            1 :         compaction := newCompaction(pc, d.opts, d.timeNow(), d.ObjProvider(), grantHandle, d.TableFormat(), d.determineCompactionValueSeparation)
    1968            1 :         d.addInProgressCompaction(compaction)
    1969            1 :         go func() {
    1970            1 :                 d.compact(compaction, doneChannel)
    1971            1 :         }()
    1972              : }
    1973              : 
    1974              : // Schedule implements DBForCompaction (it is called by the
    1975              : // CompactionScheduler).
    1976            1 : func (d *DB) Schedule(grantHandle CompactionGrantHandle) bool {
    1977            1 :         d.mu.Lock()
    1978            1 :         defer d.mu.Unlock()
    1979            1 :         d.mu.versions.logLock()
    1980            1 :         defer d.mu.versions.logUnlock()
    1981            1 :         isWaiting := d.mu.versions.pickedCompactionCache.isWaiting()
    1982            1 :         if !isWaiting {
    1983            0 :                 return false
    1984            0 :         }
    1985            1 :         pc := d.mu.versions.pickedCompactionCache.getForRunning()
    1986            1 :         if pc == nil {
    1987            1 :                 env := d.makeCompactionEnvLocked()
    1988            1 :                 if env != nil {
    1989            1 :                         pc = d.pickAnyCompaction(*env)
    1990            1 :                 }
    1991            1 :                 if pc == nil {
    1992            1 :                         d.mu.versions.pickedCompactionCache.setNotWaiting()
    1993            1 :                         return false
    1994            1 :                 }
    1995              :         }
    1996              :         // INVARIANT: pc != nil and is not in the cache. isWaiting is true, since
    1997              :         // there may be more compactions to run.
    1998            1 :         d.runPickedCompaction(pc, grantHandle)
    1999            1 :         return true
    2000              : }
    2001              : 
    2002              : // GetWaitingCompaction implements DBForCompaction (it is called by the
    2003              : // CompactionScheduler).
    2004            1 : func (d *DB) GetWaitingCompaction() (bool, WaitingCompaction) {
    2005            1 :         d.mu.Lock()
    2006            1 :         defer d.mu.Unlock()
    2007            1 :         d.mu.versions.logLock()
    2008            1 :         defer d.mu.versions.logUnlock()
    2009            1 :         isWaiting := d.mu.versions.pickedCompactionCache.isWaiting()
    2010            1 :         if !isWaiting {
    2011            1 :                 return false, WaitingCompaction{}
    2012            1 :         }
    2013            1 :         pc := d.mu.versions.pickedCompactionCache.peek()
    2014            1 :         if pc == nil {
    2015            1 :                 // Need to pick a compaction.
    2016            1 :                 env := d.makeCompactionEnvLocked()
    2017            1 :                 if env != nil {
    2018            1 :                         pc = d.pickAnyCompaction(*env)
    2019            1 :                 }
    2020            1 :                 if pc == nil {
    2021            1 :                         // Call setNotWaiting so that next call to GetWaitingCompaction can
    2022            1 :                         // return early.
    2023            1 :                         d.mu.versions.pickedCompactionCache.setNotWaiting()
    2024            1 :                         return false, WaitingCompaction{}
    2025            1 :                 } else {
    2026            1 :                         d.mu.versions.pickedCompactionCache.add(pc)
    2027            1 :                 }
    2028              :         }
    2029              :         // INVARIANT: pc != nil and is in the cache.
    2030            1 :         return true, makeWaitingCompaction(pc.manualID > 0, pc.kind, pc.score)
    2031              : }
    2032              : 
    2033              : // GetAllowedWithoutPermission implements DBForCompaction (it is called by the
    2034              : // CompactionScheduler).
    2035            1 : func (d *DB) GetAllowedWithoutPermission() int {
    2036            1 :         allowedBasedOnBacklog := int(d.mu.versions.curCompactionConcurrency.Load())
    2037            1 :         allowedBasedOnManual := 0
    2038            1 :         manualBacklog := int(d.mu.compact.manualLen.Load())
    2039            1 :         if manualBacklog > 0 {
    2040            1 :                 _, maxAllowed := d.opts.CompactionConcurrencyRange()
    2041            1 :                 allowedBasedOnManual = min(maxAllowed, manualBacklog+allowedBasedOnBacklog)
    2042            1 :         }
    2043            1 :         return max(allowedBasedOnBacklog, allowedBasedOnManual)
    2044              : }
    2045              : 
    2046              : // tryScheduleDownloadCompactions tries to start download compactions.
    2047              : //
    2048              : // Requires d.mu to be held. Updates d.mu.compact.downloads.
    2049              : //
    2050              : // Returns true iff at least one compaction was started.
    2051            1 : func (d *DB) tryScheduleDownloadCompactions(env compactionEnv, maxConcurrentDownloads int) bool {
    2052            1 :         started := false
    2053            1 :         vers := d.mu.versions.currentVersion()
    2054            1 :         for i := 0; i < len(d.mu.compact.downloads); {
    2055            1 :                 if d.mu.compact.downloadingCount >= maxConcurrentDownloads {
    2056            1 :                         break
    2057              :                 }
    2058            1 :                 download := d.mu.compact.downloads[i]
    2059            1 :                 switch d.tryLaunchDownloadCompaction(download, vers, d.mu.versions.l0Organizer, env, maxConcurrentDownloads) {
    2060            1 :                 case launchedCompaction:
    2061            1 :                         started = true
    2062            1 :                         continue
    2063            1 :                 case didNotLaunchCompaction:
    2064            1 :                         // See if we can launch a compaction for another download task.
    2065            1 :                         i++
    2066            1 :                 case downloadTaskCompleted:
    2067            1 :                         // Task is completed and must be removed.
    2068            1 :                         d.mu.compact.downloads = slices.Delete(d.mu.compact.downloads, i, i+1)
    2069              :                 }
    2070              :         }
    2071            1 :         return started
    2072              : }
    2073              : 
    2074            1 : func (d *DB) pickManualCompaction(env compactionEnv) (pc *pickedCompaction) {
    2075            1 :         v := d.mu.versions.currentVersion()
    2076            1 :         for len(d.mu.compact.manual) > 0 {
    2077            1 :                 manual := d.mu.compact.manual[0]
    2078            1 :                 pc, retryLater := newPickedManualCompaction(v, d.mu.versions.l0Organizer, d.opts, env, d.mu.versions.picker.getBaseLevel(), manual)
    2079            1 :                 if pc != nil {
    2080            1 :                         return pc
    2081            1 :                 }
    2082            1 :                 if retryLater {
    2083            1 :                         // We are not able to run this manual compaction at this time.
    2084            1 :                         // Inability to run the head blocks later manual compactions.
    2085            1 :                         manual.retries++
    2086            1 :                         return nil
    2087            1 :                 }
    2088              :                 // Manual compaction is a no-op. Signal that it's complete.
    2089            1 :                 manual.done <- nil
    2090            1 :                 d.mu.compact.manual = d.mu.compact.manual[1:]
    2091            1 :                 d.mu.compact.manualLen.Store(int32(len(d.mu.compact.manual)))
    2092              :         }
    2093            1 :         return nil
    2094              : }
    2095              : 
    2096              : // tryScheduleDeleteOnlyCompaction tries to kick off a delete-only compaction
    2097              : // for all files that can be deleted as suggested by deletionHints.
    2098              : //
    2099              : // Requires d.mu to be held. Updates d.mu.compact.deletionHints.
    2100              : //
    2101              : // Returns true iff a compaction was started.
    2102            1 : func (d *DB) tryScheduleDeleteOnlyCompaction() bool {
    2103            1 :         if d.opts.private.disableDeleteOnlyCompactions || d.opts.DisableAutomaticCompactions ||
    2104            1 :                 len(d.mu.compact.deletionHints) == 0 {
    2105            1 :                 return false
    2106            1 :         }
    2107            1 :         if _, maxConcurrency := d.opts.CompactionConcurrencyRange(); d.mu.compact.compactingCount >= maxConcurrency {
    2108            1 :                 return false
    2109            1 :         }
    2110            1 :         v := d.mu.versions.currentVersion()
    2111            1 :         snapshots := d.mu.snapshots.toSlice()
    2112            1 :         // We need to save the value of exciseEnabled in the compaction itself, as
    2113            1 :         // it can change dynamically between now and when the compaction runs.
    2114            1 :         exciseEnabled := d.FormatMajorVersion() >= FormatVirtualSSTables &&
    2115            1 :                 d.opts.Experimental.EnableDeleteOnlyCompactionExcises != nil && d.opts.Experimental.EnableDeleteOnlyCompactionExcises()
    2116            1 :         inputs, resolvedHints, unresolvedHints := checkDeleteCompactionHints(d.cmp, v, d.mu.compact.deletionHints, snapshots, exciseEnabled)
    2117            1 :         d.mu.compact.deletionHints = unresolvedHints
    2118            1 : 
    2119            1 :         if len(inputs) > 0 {
    2120            1 :                 c := newDeleteOnlyCompaction(d.opts, v, inputs, d.timeNow(), resolvedHints, exciseEnabled)
    2121            1 :                 d.mu.compact.compactingCount++
    2122            1 :                 d.addInProgressCompaction(c)
    2123            1 :                 go d.compact(c, nil)
    2124            1 :                 return true
    2125            1 :         }
    2126            1 :         return false
    2127              : }
    2128              : 
    2129              : // deleteCompactionHintType indicates whether the deleteCompactionHint was
    2130              : // generated from a span containing a range del (point key only), a range key
    2131              : // delete (range key only), or both a point and range key.
    2132              : type deleteCompactionHintType uint8
    2133              : 
    2134              : const (
    2135              :         // NOTE: While these are primarily used as enumeration types, they are also
    2136              :         // used for some bitwise operations. Care should be taken when updating.
    2137              :         deleteCompactionHintTypeUnknown deleteCompactionHintType = iota
    2138              :         deleteCompactionHintTypePointKeyOnly
    2139              :         deleteCompactionHintTypeRangeKeyOnly
    2140              :         deleteCompactionHintTypePointAndRangeKey
    2141              : )
    2142              : 
    2143              : // String implements fmt.Stringer.
    2144            0 : func (h deleteCompactionHintType) String() string {
    2145            0 :         switch h {
    2146            0 :         case deleteCompactionHintTypeUnknown:
    2147            0 :                 return "unknown"
    2148            0 :         case deleteCompactionHintTypePointKeyOnly:
    2149            0 :                 return "point-key-only"
    2150            0 :         case deleteCompactionHintTypeRangeKeyOnly:
    2151            0 :                 return "range-key-only"
    2152            0 :         case deleteCompactionHintTypePointAndRangeKey:
    2153            0 :                 return "point-and-range-key"
    2154            0 :         default:
    2155            0 :                 panic(fmt.Sprintf("unknown hint type: %d", h))
    2156              :         }
    2157              : }
    2158              : 
    2159              : // compactionHintFromKeys returns a deleteCompactionHintType given a slice of
    2160              : // keyspan.Keys.
    2161            1 : func compactionHintFromKeys(keys []keyspan.Key) deleteCompactionHintType {
    2162            1 :         var hintType deleteCompactionHintType
    2163            1 :         for _, k := range keys {
    2164            1 :                 switch k.Kind() {
    2165            1 :                 case base.InternalKeyKindRangeDelete:
    2166            1 :                         hintType |= deleteCompactionHintTypePointKeyOnly
    2167            1 :                 case base.InternalKeyKindRangeKeyDelete:
    2168            1 :                         hintType |= deleteCompactionHintTypeRangeKeyOnly
    2169            0 :                 default:
    2170            0 :                         panic(fmt.Sprintf("unsupported key kind: %s", k.Kind()))
    2171              :                 }
    2172              :         }
    2173            1 :         return hintType
    2174              : }
    2175              : 
    2176              : // A deleteCompactionHint records a user key and sequence number span that has been
    2177              : // deleted by a range tombstone. A hint is recorded if at least one sstable
    2178              : // falls completely within both the user key and sequence number spans.
    2179              : // Once the tombstones and the observed completely-contained sstables fall
    2180              : // into the same snapshot stripe, a delete-only compaction may delete any
    2181              : // sstables within the range.
    2182              : type deleteCompactionHint struct {
    2183              :         // The type of key span that generated this hint (point key, range key, or
    2184              :         // both).
    2185              :         hintType deleteCompactionHintType
    2186              :         // start and end are user keys specifying a key range [start, end) of
    2187              :         // deleted keys.
    2188              :         start []byte
    2189              :         end   []byte
    2190              :         // The level of the file containing the range tombstone(s) when the hint
    2191              :         // was created. Only lower levels need to be searched for files that may
    2192              :         // be deleted.
    2193              :         tombstoneLevel int
    2194              :         // The file containing the range tombstone(s) that created the hint.
    2195              :         tombstoneFile *manifest.TableMetadata
    2196              :         // The smallest and largest sequence numbers of the abutting tombstones
    2197              :         // merged to form this hint. All of a tables' keys must be less than the
    2198              :         // tombstone smallest sequence number to be deleted. All of a tables'
    2199              :         // sequence numbers must fall into the same snapshot stripe as the
    2200              :         // tombstone largest sequence number to be deleted.
    2201              :         tombstoneLargestSeqNum  base.SeqNum
    2202              :         tombstoneSmallestSeqNum base.SeqNum
    2203              :         // The smallest sequence number of a sstable that was found to be covered
    2204              :         // by this hint. The hint cannot be resolved until this sequence number is
    2205              :         // in the same snapshot stripe as the largest tombstone sequence number.
    2206              :         // This is set when a hint is created, so the LSM may look different and
    2207              :         // notably no longer contain the sstable that contained the key at this
    2208              :         // sequence number.
    2209              :         fileSmallestSeqNum base.SeqNum
    2210              : }
    2211              : 
    2212              : type deletionHintOverlap int8
    2213              : 
    2214              : const (
    2215              :         // hintDoesNotApply indicates that the hint does not apply to the file.
    2216              :         hintDoesNotApply deletionHintOverlap = iota
    2217              :         // hintExcisesFile indicates that the hint excises a portion of the file,
    2218              :         // and the format major version of the DB supports excises.
    2219              :         hintExcisesFile
    2220              :         // hintDeletesFile indicates that the hint deletes the entirety of the file.
    2221              :         hintDeletesFile
    2222              : )
    2223              : 
    2224            0 : func (h deleteCompactionHint) String() string {
    2225            0 :         return fmt.Sprintf(
    2226            0 :                 "L%d.%s %s-%s seqnums(tombstone=%d-%d, file-smallest=%d, type=%s)",
    2227            0 :                 h.tombstoneLevel, h.tombstoneFile.TableNum, h.start, h.end,
    2228            0 :                 h.tombstoneSmallestSeqNum, h.tombstoneLargestSeqNum, h.fileSmallestSeqNum,
    2229            0 :                 h.hintType,
    2230            0 :         )
    2231            0 : }
    2232              : 
    2233              : func (h *deleteCompactionHint) canDeleteOrExcise(
    2234              :         cmp Compare, m *manifest.TableMetadata, snapshots compact.Snapshots, exciseEnabled bool,
    2235            1 : ) deletionHintOverlap {
    2236            1 :         // The file can only be deleted if all of its keys are older than the
    2237            1 :         // earliest tombstone aggregated into the hint. Note that we use
    2238            1 :         // m.LargestSeqNumAbsolute, not m.LargestSeqNum. Consider a compaction that
    2239            1 :         // zeroes sequence numbers. A compaction may zero the sequence number of a
    2240            1 :         // key with a sequence number > h.tombstoneSmallestSeqNum and set it to
    2241            1 :         // zero. If we looked at m.LargestSeqNum, the resulting output file would
    2242            1 :         // appear to not contain any keys more recent than the oldest tombstone. To
    2243            1 :         // avoid this error, the largest pre-zeroing sequence number is maintained
    2244            1 :         // in LargestSeqNumAbsolute and used here to make the determination whether
    2245            1 :         // the file's keys are older than all of the hint's tombstones.
    2246            1 :         if m.LargestSeqNumAbsolute >= h.tombstoneSmallestSeqNum || m.SmallestSeqNum < h.fileSmallestSeqNum {
    2247            1 :                 return hintDoesNotApply
    2248            1 :         }
    2249              : 
    2250              :         // The file's oldest key must  be in the same snapshot stripe as the
    2251              :         // newest tombstone. NB: We already checked the hint's sequence numbers,
    2252              :         // but this file's oldest sequence number might be lower than the hint's
    2253              :         // smallest sequence number despite the file falling within the key range
    2254              :         // if this file was constructed after the hint by a compaction.
    2255            1 :         if snapshots.Index(h.tombstoneLargestSeqNum) != snapshots.Index(m.SmallestSeqNum) {
    2256            0 :                 return hintDoesNotApply
    2257            0 :         }
    2258              : 
    2259            1 :         switch h.hintType {
    2260            1 :         case deleteCompactionHintTypePointKeyOnly:
    2261            1 :                 // A hint generated by a range del span cannot delete tables that contain
    2262            1 :                 // range keys.
    2263            1 :                 if m.HasRangeKeys {
    2264            1 :                         return hintDoesNotApply
    2265            1 :                 }
    2266            1 :         case deleteCompactionHintTypeRangeKeyOnly:
    2267            1 :                 // A hint generated by a range key del span cannot delete tables that
    2268            1 :                 // contain point keys.
    2269            1 :                 if m.HasPointKeys {
    2270            1 :                         return hintDoesNotApply
    2271            1 :                 }
    2272            1 :         case deleteCompactionHintTypePointAndRangeKey:
    2273              :                 // A hint from a span that contains both range dels *and* range keys can
    2274              :                 // only be deleted if both bounds fall within the hint. The next check takes
    2275              :                 // care of this.
    2276            0 :         default:
    2277            0 :                 panic(fmt.Sprintf("pebble: unknown delete compaction hint type: %d", h.hintType))
    2278              :         }
    2279            1 :         if cmp(h.start, m.Smallest().UserKey) <= 0 &&
    2280            1 :                 base.UserKeyExclusive(h.end).CompareUpperBounds(cmp, m.UserKeyBounds().End) >= 0 {
    2281            1 :                 return hintDeletesFile
    2282            1 :         }
    2283            1 :         if !exciseEnabled {
    2284            1 :                 // The file's keys must be completely contained within the hint range; excises
    2285            1 :                 // aren't allowed.
    2286            1 :                 return hintDoesNotApply
    2287            1 :         }
    2288              :         // Check for any overlap. In cases of partial overlap, we can excise the part of the file
    2289              :         // that overlaps with the deletion hint.
    2290            1 :         if cmp(h.end, m.Smallest().UserKey) > 0 &&
    2291            1 :                 (m.UserKeyBounds().End.CompareUpperBounds(cmp, base.UserKeyInclusive(h.start)) >= 0) {
    2292            1 :                 return hintExcisesFile
    2293            1 :         }
    2294            1 :         return hintDoesNotApply
    2295              : }
    2296              : 
    2297              : // checkDeleteCompactionHints checks the passed-in deleteCompactionHints for those that
    2298              : // can be resolved and those that cannot. A hint is considered resolved when its largest
    2299              : // tombstone sequence number and the smallest sequence number of covered files fall in
    2300              : // the same snapshot stripe. No more than maxHintsPerDeleteOnlyCompaction will be resolved
    2301              : // per method call. Resolved and unresolved hints are returned in separate return values.
    2302              : // The files that the resolved hints apply to, are returned as compactionLevels.
    2303              : func checkDeleteCompactionHints(
    2304              :         cmp Compare,
    2305              :         v *manifest.Version,
    2306              :         hints []deleteCompactionHint,
    2307              :         snapshots compact.Snapshots,
    2308              :         exciseEnabled bool,
    2309            1 : ) (levels []compactionLevel, resolved, unresolved []deleteCompactionHint) {
    2310            1 :         var files map[*manifest.TableMetadata]bool
    2311            1 :         var byLevel [numLevels][]*manifest.TableMetadata
    2312            1 : 
    2313            1 :         // Delete-only compactions can be quadratic (O(mn)) in terms of runtime
    2314            1 :         // where m = number of files in the delete-only compaction and n = number
    2315            1 :         // of resolved hints. To prevent these from growing unbounded, we cap
    2316            1 :         // the number of hints we resolve for one delete-only compaction. This
    2317            1 :         // cap only applies if exciseEnabled == true.
    2318            1 :         const maxHintsPerDeleteOnlyCompaction = 10
    2319            1 : 
    2320            1 :         unresolvedHints := hints[:0]
    2321            1 :         // Lazily populate resolvedHints, similar to files above.
    2322            1 :         resolvedHints := make([]deleteCompactionHint, 0)
    2323            1 :         for _, h := range hints {
    2324            1 :                 // Check each compaction hint to see if it's resolvable. Resolvable
    2325            1 :                 // hints are removed and trigger a delete-only compaction if any files
    2326            1 :                 // in the current LSM still meet their criteria. Unresolvable hints
    2327            1 :                 // are saved and don't trigger a delete-only compaction.
    2328            1 :                 //
    2329            1 :                 // When a compaction hint is created, the sequence numbers of the
    2330            1 :                 // range tombstones and the covered file with the oldest key are
    2331            1 :                 // recorded. The largest tombstone sequence number and the smallest
    2332            1 :                 // file sequence number must be in the same snapshot stripe for the
    2333            1 :                 // hint to be resolved. The below graphic models a compaction hint
    2334            1 :                 // covering the keyspace [b, r). The hint completely contains two
    2335            1 :                 // files, 000002 and 000003. The file 000003 contains the lowest
    2336            1 :                 // covered sequence number at #90. The tombstone b.RANGEDEL.230:h has
    2337            1 :                 // the highest tombstone sequence number incorporated into the hint.
    2338            1 :                 // The hint may be resolved only once the snapshots at #100, #180 and
    2339            1 :                 // #210 are all closed. File 000001 is not included within the hint
    2340            1 :                 // because it extends beyond the range tombstones in user key space.
    2341            1 :                 //
    2342            1 :                 // 250
    2343            1 :                 //
    2344            1 :                 //       |-b...230:h-|
    2345            1 :                 // _____________________________________________________ snapshot #210
    2346            1 :                 // 200               |--h.RANGEDEL.200:r--|
    2347            1 :                 //
    2348            1 :                 // _____________________________________________________ snapshot #180
    2349            1 :                 //
    2350            1 :                 // 150                     +--------+
    2351            1 :                 //           +---------+   | 000003 |
    2352            1 :                 //           | 000002  |   |        |
    2353            1 :                 //           +_________+   |        |
    2354            1 :                 // 100_____________________|________|___________________ snapshot #100
    2355            1 :                 //                         +--------+
    2356            1 :                 // _____________________________________________________ snapshot #70
    2357            1 :                 //                             +---------------+
    2358            1 :                 //  50                         | 000001        |
    2359            1 :                 //                             |               |
    2360            1 :                 //                             +---------------+
    2361            1 :                 // ______________________________________________________________
    2362            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
    2363            1 : 
    2364            1 :                 if snapshots.Index(h.tombstoneLargestSeqNum) != snapshots.Index(h.fileSmallestSeqNum) ||
    2365            1 :                         (len(resolvedHints) >= maxHintsPerDeleteOnlyCompaction && exciseEnabled) {
    2366            1 :                         // Cannot resolve yet.
    2367            1 :                         unresolvedHints = append(unresolvedHints, h)
    2368            1 :                         continue
    2369              :                 }
    2370              : 
    2371              :                 // The hint h will be resolved and dropped, if it either affects no files at all
    2372              :                 // or if the number of files it creates (eg. through excision) is less than or
    2373              :                 // equal to the number of files it deletes. First, determine how many files are
    2374              :                 // affected by this hint.
    2375            1 :                 filesDeletedByCurrentHint := 0
    2376            1 :                 var filesDeletedByLevel [7][]*manifest.TableMetadata
    2377            1 :                 for l := h.tombstoneLevel + 1; l < numLevels; l++ {
    2378            1 :                         for m := range v.Overlaps(l, base.UserKeyBoundsEndExclusive(h.start, h.end)).All() {
    2379            1 :                                 doesHintApply := h.canDeleteOrExcise(cmp, m, snapshots, exciseEnabled)
    2380            1 :                                 if m.IsCompacting() || doesHintApply == hintDoesNotApply || files[m] {
    2381            1 :                                         continue
    2382              :                                 }
    2383            1 :                                 switch doesHintApply {
    2384            1 :                                 case hintDeletesFile:
    2385            1 :                                         filesDeletedByCurrentHint++
    2386            1 :                                 case hintExcisesFile:
    2387            1 :                                         // Account for the original file being deleted.
    2388            1 :                                         filesDeletedByCurrentHint++
    2389            1 :                                         // An excise could produce up to 2 new files. If the hint
    2390            1 :                                         // leaves a fragment of the file on the left, decrement
    2391            1 :                                         // the counter once. If the hint leaves a fragment of the
    2392            1 :                                         // file on the right, decrement the counter once.
    2393            1 :                                         if cmp(h.start, m.Smallest().UserKey) > 0 {
    2394            1 :                                                 filesDeletedByCurrentHint--
    2395            1 :                                         }
    2396            1 :                                         if m.UserKeyBounds().End.IsUpperBoundFor(cmp, h.end) {
    2397            1 :                                                 filesDeletedByCurrentHint--
    2398            1 :                                         }
    2399              :                                 }
    2400            1 :                                 filesDeletedByLevel[l] = append(filesDeletedByLevel[l], m)
    2401              :                         }
    2402              :                 }
    2403            1 :                 if filesDeletedByCurrentHint < 0 {
    2404            1 :                         // This hint does not delete a sufficient number of files to warrant
    2405            1 :                         // a delete-only compaction at this stage. Drop it (ie. don't add it
    2406            1 :                         // to either resolved or unresolved hints) so it doesn't stick around
    2407            1 :                         // forever.
    2408            1 :                         continue
    2409              :                 }
    2410              :                 // This hint will be resolved and dropped.
    2411            1 :                 for l := h.tombstoneLevel + 1; l < numLevels; l++ {
    2412            1 :                         byLevel[l] = append(byLevel[l], filesDeletedByLevel[l]...)
    2413            1 :                         for _, m := range filesDeletedByLevel[l] {
    2414            1 :                                 if files == nil {
    2415            1 :                                         // Construct files lazily, assuming most calls will not
    2416            1 :                                         // produce delete-only compactions.
    2417            1 :                                         files = make(map[*manifest.TableMetadata]bool)
    2418            1 :                                 }
    2419            1 :                                 files[m] = true
    2420              :                         }
    2421              :                 }
    2422            1 :                 resolvedHints = append(resolvedHints, h)
    2423              :         }
    2424              : 
    2425            1 :         var compactLevels []compactionLevel
    2426            1 :         for l, files := range byLevel {
    2427            1 :                 if len(files) == 0 {
    2428            1 :                         continue
    2429              :                 }
    2430            1 :                 compactLevels = append(compactLevels, compactionLevel{
    2431            1 :                         level: l,
    2432            1 :                         files: manifest.NewLevelSliceKeySorted(cmp, files),
    2433            1 :                 })
    2434              :         }
    2435            1 :         return compactLevels, resolvedHints, unresolvedHints
    2436              : }
    2437              : 
    2438            1 : func (d *DB) compactionPprofLabels(c *compaction) pprof.LabelSet {
    2439            1 :         activity := "compact"
    2440            1 :         if len(c.flushing) != 0 {
    2441            0 :                 activity = "flush"
    2442            0 :         }
    2443            1 :         level := "L?"
    2444            1 :         // Delete-only compactions don't have an output level.
    2445            1 :         if c.outputLevel != nil {
    2446            1 :                 level = fmt.Sprintf("L%d", c.outputLevel.level)
    2447            1 :         }
    2448            1 :         if kc := d.opts.Experimental.UserKeyCategories; kc.Len() > 0 {
    2449            0 :                 cat := kc.CategorizeKeyRange(c.smallest.UserKey, c.largest.UserKey)
    2450            0 :                 return pprof.Labels("pebble", activity, "output-level", level, "key-type", cat)
    2451            0 :         }
    2452            1 :         return pprof.Labels("pebble", activity, "output-level", level)
    2453              : }
    2454              : 
    2455              : // compact runs one compaction and maybe schedules another call to compact.
    2456            1 : func (d *DB) compact(c *compaction, errChannel chan error) {
    2457            1 :         pprof.Do(context.Background(), d.compactionPprofLabels(c), func(context.Context) {
    2458            1 :                 func() {
    2459            1 :                         d.mu.Lock()
    2460            1 :                         defer d.mu.Unlock()
    2461            1 :                         jobID := d.newJobIDLocked()
    2462            1 : 
    2463            1 :                         c.grantHandle.Started()
    2464            1 :                         compactErr := d.compact1(jobID, c)
    2465            1 :                         // The version stored in the compaction is ref'd when the
    2466            1 :                         // compaction is created. We're responsible for un-refing it
    2467            1 :                         // when the compaction is complete.
    2468            1 :                         //
    2469            1 :                         // Unreferencing the version may have accumulated obsolete
    2470            1 :                         // files, so we schedule a deletion of obsolete files.
    2471            1 :                         c.version.UnrefLocked()
    2472            1 :                         d.deleteObsoleteFiles(jobID)
    2473            1 :                         // We send on the error channel only after we've deleted
    2474            1 :                         // obsolete files so that tests performing manual compactions
    2475            1 :                         // block until the obsolete files are deleted, and the test
    2476            1 :                         // observes the deletion.
    2477            1 :                         if errChannel != nil {
    2478            1 :                                 errChannel <- compactErr
    2479            1 :                         }
    2480            1 :                         if compactErr != nil {
    2481            1 :                                 d.handleCompactFailure(c, compactErr)
    2482            1 :                         }
    2483            1 :                         if c.isDownload {
    2484            1 :                                 d.mu.compact.downloadingCount--
    2485            1 :                         } else {
    2486            1 :                                 d.mu.compact.compactingCount--
    2487            1 :                         }
    2488            1 :                         delete(d.mu.compact.inProgress, c)
    2489            1 :                         // Add this compaction's duration to the cumulative duration. NB: This
    2490            1 :                         // must be atomic with the above removal of c from
    2491            1 :                         // d.mu.compact.InProgress to ensure Metrics.Compact.Duration does not
    2492            1 :                         // miss or double count a completing compaction's duration.
    2493            1 :                         d.mu.compact.duration += d.timeNow().Sub(c.beganAt)
    2494              :                 }()
    2495              :                 // Done must not be called while holding any lock that needs to be
    2496              :                 // acquired by Schedule. Also, it must be called after new Version has
    2497              :                 // been installed, and metadata related to compactingCount and inProgress
    2498              :                 // compactions has been updated. This is because when we are running at
    2499              :                 // the limit of permitted compactions, Done can cause the
    2500              :                 // CompactionScheduler to schedule another compaction. Note that the only
    2501              :                 // compactions that may be scheduled by Done are those integrated with the
    2502              :                 // CompactionScheduler.
    2503            1 :                 c.grantHandle.Done()
    2504            1 :                 c.grantHandle = nil
    2505            1 :                 // The previous compaction may have produced too many files in a level, so
    2506            1 :                 // reschedule another compaction if needed.
    2507            1 :                 //
    2508            1 :                 // The preceding Done call will not necessarily cause a compaction to be
    2509            1 :                 // scheduled, so we also need to call maybeScheduleCompaction. And
    2510            1 :                 // maybeScheduleCompaction encompasses all compactions, and not only those
    2511            1 :                 // scheduled via the CompactionScheduler.
    2512            1 :                 func() {
    2513            1 :                         d.mu.Lock()
    2514            1 :                         defer d.mu.Unlock()
    2515            1 :                         d.maybeScheduleCompaction()
    2516            1 :                         d.mu.compact.cond.Broadcast()
    2517            1 :                 }()
    2518              :         })
    2519              : }
    2520              : 
    2521            1 : func (d *DB) handleCompactFailure(c *compaction, err error) {
    2522            1 :         if errors.Is(err, ErrCancelledCompaction) {
    2523            1 :                 // ErrCancelledCompaction is expected during normal operation, so we don't
    2524            1 :                 // want to report it as a background error.
    2525            1 :                 d.opts.Logger.Infof("%v", err)
    2526            1 :                 return
    2527            1 :         }
    2528              : 
    2529              :         // Record problem spans for a short duration, unless the error is a corruption.
    2530            0 :         expiration := 30 * time.Second
    2531            0 :         if IsCorruptionError(err) {
    2532            0 :                 // TODO(radu): ideally, we should be using the corruption reporting
    2533            0 :                 // mechanism which has a tighter span for the corruption. We would need to
    2534            0 :                 // somehow plumb the level of the file.
    2535            0 :                 expiration = 5 * time.Minute
    2536            0 :         }
    2537            0 :         for i := range c.inputs {
    2538            0 :                 level := c.inputs[i].level
    2539            0 :                 if level == 0 {
    2540            0 :                         // We do not set problem spans on L0, as they could block flushes.
    2541            0 :                         continue
    2542              :                 }
    2543            0 :                 it := c.inputs[i].files.Iter()
    2544            0 :                 for f := it.First(); f != nil; f = it.Next() {
    2545            0 :                         d.problemSpans.Add(level, f.UserKeyBounds(), expiration)
    2546            0 :                 }
    2547              :         }
    2548              : 
    2549              :         // TODO(peter): count consecutive compaction errors and backoff.
    2550            0 :         d.opts.EventListener.BackgroundError(err)
    2551              : }
    2552              : 
    2553              : // cleanupVersionEdit cleans up any on-disk artifacts that were created
    2554              : // for the application of a versionEdit that is no longer going to be applied.
    2555              : //
    2556              : // d.mu must be held when calling this method.
    2557            1 : func (d *DB) cleanupVersionEdit(ve *manifest.VersionEdit) {
    2558            1 :         obsoleteFiles := manifest.ObsoleteFiles{
    2559            1 :                 TableBackings: make([]*manifest.TableBacking, 0, len(ve.NewTables)),
    2560            1 :                 BlobFiles:     make([]*manifest.PhysicalBlobFile, 0, len(ve.NewBlobFiles)),
    2561            1 :         }
    2562            1 :         deletedTables := make(map[base.TableNum]struct{})
    2563            1 :         for key := range ve.DeletedTables {
    2564            1 :                 deletedTables[key.FileNum] = struct{}{}
    2565            1 :         }
    2566            1 :         for i := range ve.NewBlobFiles {
    2567            1 :                 obsoleteFiles.AddBlob(ve.NewBlobFiles[i].Physical)
    2568            1 :                 d.mu.versions.zombieBlobs.Add(objectInfo{
    2569            1 :                         fileInfo: fileInfo{
    2570            1 :                                 FileNum:  ve.NewBlobFiles[i].Physical.FileNum,
    2571            1 :                                 FileSize: ve.NewBlobFiles[i].Physical.Size,
    2572            1 :                         },
    2573            1 :                         isLocal: objstorage.IsLocalBlobFile(d.objProvider, ve.NewBlobFiles[i].Physical.FileNum),
    2574            1 :                 })
    2575            1 :         }
    2576            1 :         for i := range ve.NewTables {
    2577            1 :                 if ve.NewTables[i].Meta.Virtual {
    2578            1 :                         // We handle backing files separately.
    2579            1 :                         continue
    2580              :                 }
    2581            1 :                 if _, ok := deletedTables[ve.NewTables[i].Meta.TableNum]; ok {
    2582            1 :                         // This file is being moved in this ve to a different level.
    2583            1 :                         // Don't mark it as obsolete.
    2584            1 :                         continue
    2585              :                 }
    2586            1 :                 obsoleteFiles.AddBacking(ve.NewTables[i].Meta.PhysicalMeta().TableBacking)
    2587              :         }
    2588            1 :         for i := range ve.CreatedBackingTables {
    2589            1 :                 if ve.CreatedBackingTables[i].IsUnused() {
    2590            0 :                         obsoleteFiles.AddBacking(ve.CreatedBackingTables[i])
    2591            0 :                 }
    2592              :         }
    2593            1 :         for _, of := range obsoleteFiles.TableBackings {
    2594            1 :                 // Add this file to zombie tables as well, as the versionSet
    2595            1 :                 // asserts on whether every obsolete file was at one point
    2596            1 :                 // marked zombie.
    2597            1 :                 d.mu.versions.zombieTables.Add(objectInfo{
    2598            1 :                         fileInfo: fileInfo{
    2599            1 :                                 FileNum:  of.DiskFileNum,
    2600            1 :                                 FileSize: of.Size,
    2601            1 :                         },
    2602            1 :                         isLocal: objstorage.IsLocalTable(d.objProvider, of.DiskFileNum),
    2603            1 :                 })
    2604            1 :         }
    2605            1 :         d.mu.versions.addObsoleteLocked(obsoleteFiles)
    2606              : }
    2607              : 
    2608              : // compact1 runs one compaction.
    2609              : //
    2610              : // d.mu must be held when calling this, but the mutex may be dropped and
    2611              : // re-acquired during the course of this method.
    2612            1 : func (d *DB) compact1(jobID JobID, c *compaction) (err error) {
    2613            1 :         info := c.makeInfo(jobID)
    2614            1 :         d.opts.EventListener.CompactionBegin(info)
    2615            1 :         startTime := d.timeNow()
    2616            1 : 
    2617            1 :         ve, stats, err := d.runCompaction(jobID, c)
    2618            1 : 
    2619            1 :         info.Duration = d.timeNow().Sub(startTime)
    2620            1 :         if err == nil {
    2621            1 :                 validateVersionEdit(ve, d.opts.Comparer.ValidateKey, d.opts.Comparer.FormatKey, d.opts.Logger)
    2622            1 :                 err = d.mu.versions.UpdateVersionLocked(func() (versionUpdate, error) {
    2623            1 :                         // Check if this compaction had a conflicting operation (eg. a d.excise())
    2624            1 :                         // that necessitates it restarting from scratch. Note that since we hold
    2625            1 :                         // the manifest lock, we don't expect this bool to change its value
    2626            1 :                         // as only the holder of the manifest lock will ever write to it.
    2627            1 :                         if c.cancel.Load() {
    2628            1 :                                 err = firstError(err, ErrCancelledCompaction)
    2629            1 :                                 // This is the first time we've seen a cancellation during the
    2630            1 :                                 // life of this compaction (or the original condition on err == nil
    2631            1 :                                 // would not have been true). We should delete any tables already
    2632            1 :                                 // created, as d.runCompaction did not do that.
    2633            1 :                                 d.cleanupVersionEdit(ve)
    2634            1 :                                 // Note that UpdateVersionLocked invalidates the pickedCompactionCache
    2635            1 :                                 // when we return, which is relevant because this failed compaction
    2636            1 :                                 // may be the highest priority to run next.
    2637            1 :                                 return versionUpdate{}, err
    2638            1 :                         }
    2639            1 :                         return versionUpdate{
    2640            1 :                                 VE:                      ve,
    2641            1 :                                 JobID:                   jobID,
    2642            1 :                                 Metrics:                 c.metrics,
    2643            1 :                                 InProgressCompactionsFn: func() []compactionInfo { return d.getInProgressCompactionInfoLocked(c) },
    2644              :                         }, nil
    2645              :                 })
    2646              :         }
    2647              : 
    2648            1 :         info.Done = true
    2649            1 :         info.Err = err
    2650            1 :         if err == nil {
    2651            1 :                 for i := range ve.NewTables {
    2652            1 :                         e := &ve.NewTables[i]
    2653            1 :                         info.Output.Tables = append(info.Output.Tables, e.Meta.TableInfo())
    2654            1 :                 }
    2655            1 :                 d.mu.snapshots.cumulativePinnedCount += stats.CumulativePinnedKeys
    2656            1 :                 d.mu.snapshots.cumulativePinnedSize += stats.CumulativePinnedSize
    2657            1 :                 d.mu.versions.metrics.Keys.MissizedTombstonesCount += stats.CountMissizedDels
    2658              :         }
    2659              : 
    2660              :         // NB: clearing compacting state must occur before updating the read state;
    2661              :         // L0Sublevels initialization depends on it.
    2662            1 :         d.clearCompactingState(c, err != nil)
    2663            1 :         d.mu.versions.incrementCompactions(c.kind, c.extraLevels, c.pickerMetrics, c.bytesWritten.Load(), err)
    2664            1 :         d.mu.versions.incrementCompactionBytes(-c.bytesWritten.Load())
    2665            1 : 
    2666            1 :         info.TotalDuration = d.timeNow().Sub(c.beganAt)
    2667            1 :         d.opts.EventListener.CompactionEnd(info)
    2668            1 : 
    2669            1 :         // Update the read state before deleting obsolete files because the
    2670            1 :         // read-state update will cause the previous version to be unref'd and if
    2671            1 :         // there are no references obsolete tables will be added to the obsolete
    2672            1 :         // table list.
    2673            1 :         if err == nil {
    2674            1 :                 d.updateReadStateLocked(d.opts.DebugCheck)
    2675            1 :                 d.updateTableStatsLocked(ve.NewTables)
    2676            1 :         }
    2677              : 
    2678            1 :         return err
    2679              : }
    2680              : 
    2681              : // runCopyCompaction runs a copy compaction where a new TableNum is created that
    2682              : // is a byte-for-byte copy of the input file or span thereof in some cases. This
    2683              : // is used in lieu of a move compaction when a file is being moved across the
    2684              : // local/remote storage boundary. It could also be used in lieu of a rewrite
    2685              : // compaction as part of a Download() call, which allows copying only a span of
    2686              : // the external file, provided the file does not contain range keys or value
    2687              : // blocks (see sstable.CopySpan).
    2688              : //
    2689              : // d.mu must be held when calling this method. The mutex will be released when
    2690              : // doing IO.
    2691              : func (d *DB) runCopyCompaction(
    2692              :         jobID JobID, c *compaction,
    2693            1 : ) (ve *manifest.VersionEdit, stats compact.Stats, _ error) {
    2694            1 :         if c.cancel.Load() {
    2695            0 :                 return nil, compact.Stats{}, ErrCancelledCompaction
    2696            0 :         }
    2697            1 :         iter := c.startLevel.files.Iter()
    2698            1 :         inputMeta := iter.First()
    2699            1 :         if iter.Next() != nil {
    2700            0 :                 return nil, compact.Stats{}, base.AssertionFailedf("got more than one file for a move compaction")
    2701            0 :         }
    2702            1 :         if inputMeta.BlobReferenceDepth > 0 || len(inputMeta.BlobReferences) > 0 {
    2703            0 :                 return nil, compact.Stats{}, base.AssertionFailedf(
    2704            0 :                         "copy compaction for %s with blob references (depth=%d, refs=%d)",
    2705            0 :                         inputMeta.TableNum, inputMeta.BlobReferenceDepth, len(inputMeta.BlobReferences),
    2706            0 :                 )
    2707            0 :         }
    2708            1 :         ve = &manifest.VersionEdit{
    2709            1 :                 DeletedTables: map[manifest.DeletedTableEntry]*manifest.TableMetadata{
    2710            1 :                         {Level: c.startLevel.level, FileNum: inputMeta.TableNum}: inputMeta,
    2711            1 :                 },
    2712            1 :         }
    2713            1 : 
    2714            1 :         objMeta, err := d.objProvider.Lookup(base.FileTypeTable, inputMeta.TableBacking.DiskFileNum)
    2715            1 :         if err != nil {
    2716            0 :                 return nil, compact.Stats{}, err
    2717            0 :         }
    2718              :         // This code does not support copying a shared table (which should never be necessary).
    2719            1 :         if objMeta.IsShared() {
    2720            0 :                 return nil, compact.Stats{}, base.AssertionFailedf("copy compaction of shared table")
    2721            0 :         }
    2722              : 
    2723              :         // We are in the relatively more complex case where we need to copy this
    2724              :         // file to remote storage. Drop the db mutex while we do the copy
    2725              :         //
    2726              :         // To ease up cleanup of the local file and tracking of refs, we create
    2727              :         // a new FileNum. This has the potential of making the block cache less
    2728              :         // effective, however.
    2729            1 :         newMeta := &manifest.TableMetadata{
    2730            1 :                 Size:                     inputMeta.Size,
    2731            1 :                 CreationTime:             inputMeta.CreationTime,
    2732            1 :                 SmallestSeqNum:           inputMeta.SmallestSeqNum,
    2733            1 :                 LargestSeqNum:            inputMeta.LargestSeqNum,
    2734            1 :                 LargestSeqNumAbsolute:    inputMeta.LargestSeqNumAbsolute,
    2735            1 :                 Stats:                    inputMeta.Stats,
    2736            1 :                 Virtual:                  inputMeta.Virtual,
    2737            1 :                 SyntheticPrefixAndSuffix: inputMeta.SyntheticPrefixAndSuffix,
    2738            1 :         }
    2739            1 :         if inputMeta.HasPointKeys {
    2740            1 :                 newMeta.ExtendPointKeyBounds(c.cmp, inputMeta.PointKeyBounds.Smallest(), inputMeta.PointKeyBounds.Largest())
    2741            1 :         }
    2742            1 :         if inputMeta.HasRangeKeys {
    2743            1 :                 newMeta.ExtendRangeKeyBounds(c.cmp, inputMeta.RangeKeyBounds.Smallest(), inputMeta.RangeKeyBounds.Largest())
    2744            1 :         }
    2745            1 :         newMeta.TableNum = d.mu.versions.getNextTableNum()
    2746            1 :         if objMeta.IsExternal() {
    2747            1 :                 // external -> local/shared copy. File must be virtual.
    2748            1 :                 // We will update this size later after we produce the new backing file.
    2749            1 :                 newMeta.InitVirtualBacking(base.DiskFileNum(newMeta.TableNum), inputMeta.TableBacking.Size)
    2750            1 :         } else {
    2751            1 :                 // local -> shared copy. New file is guaranteed to not be virtual.
    2752            1 :                 newMeta.InitPhysicalBacking()
    2753            1 :         }
    2754              : 
    2755              :         // NB: The order here is reversed, lock after unlock. This is similar to
    2756              :         // runCompaction.
    2757            1 :         d.mu.Unlock()
    2758            1 :         defer d.mu.Lock()
    2759            1 : 
    2760            1 :         deleteOnExit := false
    2761            1 :         defer func() {
    2762            1 :                 if deleteOnExit {
    2763            0 :                         _ = d.objProvider.Remove(base.FileTypeTable, newMeta.TableBacking.DiskFileNum)
    2764            0 :                 }
    2765              :         }()
    2766              : 
    2767              :         // If the src obj is external, we're doing an external to local/shared copy.
    2768            1 :         if objMeta.IsExternal() {
    2769            1 :                 ctx := context.TODO()
    2770            1 :                 src, err := d.objProvider.OpenForReading(
    2771            1 :                         ctx, base.FileTypeTable, inputMeta.TableBacking.DiskFileNum, objstorage.OpenOptions{},
    2772            1 :                 )
    2773            1 :                 if err != nil {
    2774            0 :                         return nil, compact.Stats{}, err
    2775            0 :                 }
    2776            1 :                 defer func() {
    2777            1 :                         if src != nil {
    2778            0 :                                 _ = src.Close()
    2779            0 :                         }
    2780              :                 }()
    2781              : 
    2782            1 :                 w, _, err := d.objProvider.Create(
    2783            1 :                         ctx, base.FileTypeTable, newMeta.TableBacking.DiskFileNum,
    2784            1 :                         objstorage.CreateOptions{
    2785            1 :                                 PreferSharedStorage: d.shouldCreateShared(c.outputLevel.level),
    2786            1 :                         },
    2787            1 :                 )
    2788            1 :                 if err != nil {
    2789            0 :                         return nil, compact.Stats{}, err
    2790            0 :                 }
    2791            1 :                 deleteOnExit = true
    2792            1 : 
    2793            1 :                 start, end := newMeta.Smallest(), newMeta.Largest()
    2794            1 :                 if newMeta.SyntheticPrefixAndSuffix.HasPrefix() {
    2795            1 :                         syntheticPrefix := newMeta.SyntheticPrefixAndSuffix.Prefix()
    2796            1 :                         start.UserKey = syntheticPrefix.Invert(start.UserKey)
    2797            1 :                         end.UserKey = syntheticPrefix.Invert(end.UserKey)
    2798            1 :                 }
    2799            1 :                 if newMeta.SyntheticPrefixAndSuffix.HasSuffix() {
    2800            1 :                         // Extend the bounds as necessary so that the keys don't include suffixes.
    2801            1 :                         start.UserKey = start.UserKey[:c.comparer.Split(start.UserKey)]
    2802            1 :                         if n := c.comparer.Split(end.UserKey); n < len(end.UserKey) {
    2803            0 :                                 end = base.MakeRangeDeleteSentinelKey(c.comparer.ImmediateSuccessor(nil, end.UserKey[:n]))
    2804            0 :                         }
    2805              :                 }
    2806              : 
    2807              :                 // NB: external files are always virtual.
    2808            1 :                 var wrote uint64
    2809            1 :                 err = d.fileCache.withReader(ctx, block.NoReadEnv, inputMeta.VirtualMeta(), func(r *sstable.Reader, env sstable.ReadEnv) error {
    2810            1 :                         var err error
    2811            1 :                         // TODO(radu): plumb a ReadEnv to CopySpan (it could use the buffer pool
    2812            1 :                         // or update category stats).
    2813            1 :                         wrote, err = sstable.CopySpan(ctx,
    2814            1 :                                 src, r, d.opts.MakeReaderOptions(),
    2815            1 :                                 w, d.opts.MakeWriterOptions(c.outputLevel.level, d.TableFormat()),
    2816            1 :                                 start, end,
    2817            1 :                         )
    2818            1 :                         return err
    2819            1 :                 })
    2820              : 
    2821            1 :                 src = nil // We passed src to CopySpan; it's responsible for closing it.
    2822            1 :                 if err != nil {
    2823            0 :                         if errors.Is(err, sstable.ErrEmptySpan) {
    2824            0 :                                 // The virtual table was empty. Just remove the backing file.
    2825            0 :                                 // Note that deleteOnExit is true so we will delete the created object.
    2826            0 :                                 c.metrics[c.outputLevel.level] = &LevelMetrics{
    2827            0 :                                         TableBytesIn: inputMeta.Size,
    2828            0 :                                 }
    2829            0 : 
    2830            0 :                                 return ve, compact.Stats{}, nil
    2831            0 :                         }
    2832            0 :                         return nil, compact.Stats{}, err
    2833              :                 }
    2834            1 :                 newMeta.TableBacking.Size = wrote
    2835            1 :                 newMeta.Size = wrote
    2836            1 :         } else {
    2837            1 :                 _, err := d.objProvider.LinkOrCopyFromLocal(context.TODO(), d.opts.FS,
    2838            1 :                         d.objProvider.Path(objMeta), base.FileTypeTable, newMeta.TableBacking.DiskFileNum,
    2839            1 :                         objstorage.CreateOptions{PreferSharedStorage: true})
    2840            1 :                 if err != nil {
    2841            0 :                         return nil, compact.Stats{}, err
    2842            0 :                 }
    2843            1 :                 deleteOnExit = true
    2844              :         }
    2845            1 :         ve.NewTables = []manifest.NewTableEntry{{
    2846            1 :                 Level: c.outputLevel.level,
    2847            1 :                 Meta:  newMeta,
    2848            1 :         }}
    2849            1 :         if newMeta.Virtual {
    2850            1 :                 ve.CreatedBackingTables = []*manifest.TableBacking{newMeta.TableBacking}
    2851            1 :         }
    2852            1 :         c.metrics[c.outputLevel.level] = &LevelMetrics{
    2853            1 :                 TableBytesIn:        inputMeta.Size,
    2854            1 :                 TableBytesCompacted: newMeta.Size,
    2855            1 :                 TablesCompacted:     1,
    2856            1 :         }
    2857            1 : 
    2858            1 :         if err := d.objProvider.Sync(); err != nil {
    2859            0 :                 return nil, compact.Stats{}, err
    2860            0 :         }
    2861            1 :         deleteOnExit = false
    2862            1 :         return ve, compact.Stats{}, nil
    2863              : }
    2864              : 
    2865              : // applyHintOnFile applies a deleteCompactionHint to a file, and updates the
    2866              : // versionEdit accordingly. It returns a list of new files that were created
    2867              : // if the hint was applied partially to a file (eg. through an exciseTable as opposed
    2868              : // to an outright deletion). levelMetrics is kept up-to-date with the number
    2869              : // of tables deleted or excised.
    2870              : func (d *DB) applyHintOnFile(
    2871              :         h deleteCompactionHint,
    2872              :         f *manifest.TableMetadata,
    2873              :         level int,
    2874              :         levelMetrics *LevelMetrics,
    2875              :         ve *manifest.VersionEdit,
    2876              :         hintOverlap deletionHintOverlap,
    2877            1 : ) (newFiles []manifest.NewTableEntry, err error) {
    2878            1 :         if hintOverlap == hintDoesNotApply {
    2879            0 :                 return nil, nil
    2880            0 :         }
    2881              : 
    2882              :         // The hint overlaps with at least part of the file.
    2883            1 :         if hintOverlap == hintDeletesFile {
    2884            1 :                 // The hint deletes the entirety of this file.
    2885            1 :                 ve.DeletedTables[manifest.DeletedTableEntry{
    2886            1 :                         Level:   level,
    2887            1 :                         FileNum: f.TableNum,
    2888            1 :                 }] = f
    2889            1 :                 levelMetrics.TablesDeleted++
    2890            1 :                 return nil, nil
    2891            1 :         }
    2892              :         // The hint overlaps with only a part of the file, not the entirety of it. We need
    2893              :         // to use d.exciseTable. (hintOverlap == hintExcisesFile)
    2894            1 :         if d.FormatMajorVersion() < FormatVirtualSSTables {
    2895            0 :                 panic("pebble: delete-only compaction hint excising a file is not supported in this version")
    2896              :         }
    2897              : 
    2898            1 :         levelMetrics.TablesExcised++
    2899            1 :         exciseBounds := base.UserKeyBoundsEndExclusive(h.start, h.end)
    2900            1 :         leftTable, rightTable, err := d.exciseTable(context.TODO(), exciseBounds, f, level, tightExciseBounds)
    2901            1 :         if err != nil {
    2902            0 :                 return nil, errors.Wrap(err, "error when running excise for delete-only compaction")
    2903            0 :         }
    2904            1 :         newFiles = applyExciseToVersionEdit(ve, f, leftTable, rightTable, level)
    2905            1 :         return newFiles, nil
    2906              : }
    2907              : 
    2908              : func (d *DB) runDeleteOnlyCompactionForLevel(
    2909              :         cl compactionLevel,
    2910              :         levelMetrics *LevelMetrics,
    2911              :         ve *manifest.VersionEdit,
    2912              :         snapshots compact.Snapshots,
    2913              :         fragments []deleteCompactionHintFragment,
    2914              :         exciseEnabled bool,
    2915            1 : ) error {
    2916            1 :         if cl.level == 0 {
    2917            0 :                 panic("cannot run delete-only compaction for L0")
    2918              :         }
    2919            1 :         curFragment := 0
    2920            1 : 
    2921            1 :         // Outer loop loops on files. Middle loop loops on fragments. Inner loop
    2922            1 :         // loops on raw fragments of hints. Number of fragments are bounded by
    2923            1 :         // the number of hints this compaction was created with, which is capped
    2924            1 :         // in the compaction picker to avoid very CPU-hot loops here.
    2925            1 :         for f := range cl.files.All() {
    2926            1 :                 // curFile usually matches f, except if f got excised in which case
    2927            1 :                 // it maps to a virtual file that replaces f, or nil if f got removed
    2928            1 :                 // in its entirety.
    2929            1 :                 curFile := f
    2930            1 :                 for curFragment < len(fragments) && d.cmp(fragments[curFragment].start, f.Smallest().UserKey) <= 0 {
    2931            1 :                         curFragment++
    2932            1 :                 }
    2933            1 :                 if curFragment > 0 {
    2934            1 :                         curFragment--
    2935            1 :                 }
    2936              : 
    2937            1 :                 for ; curFragment < len(fragments); curFragment++ {
    2938            1 :                         if f.UserKeyBounds().End.CompareUpperBounds(d.cmp, base.UserKeyInclusive(fragments[curFragment].start)) < 0 {
    2939            1 :                                 break
    2940              :                         }
    2941              :                         // Process all overlapping hints with this file. Note that applying
    2942              :                         // a hint twice is idempotent; curFile should have already been excised
    2943              :                         // the first time, resulting in no change the second time.
    2944            1 :                         for _, h := range fragments[curFragment].hints {
    2945            1 :                                 if h.tombstoneLevel >= cl.level {
    2946            1 :                                         // We cannot excise out the deletion tombstone itself, or anything
    2947            1 :                                         // above it.
    2948            1 :                                         continue
    2949              :                                 }
    2950            1 :                                 hintOverlap := h.canDeleteOrExcise(d.cmp, curFile, snapshots, exciseEnabled)
    2951            1 :                                 if hintOverlap == hintDoesNotApply {
    2952            1 :                                         continue
    2953              :                                 }
    2954            1 :                                 newFiles, err := d.applyHintOnFile(h, curFile, cl.level, levelMetrics, ve, hintOverlap)
    2955            1 :                                 if err != nil {
    2956            0 :                                         return err
    2957            0 :                                 }
    2958            1 :                                 if _, ok := ve.DeletedTables[manifest.DeletedTableEntry{Level: cl.level, FileNum: curFile.TableNum}]; ok {
    2959            1 :                                         curFile = nil
    2960            1 :                                 }
    2961            1 :                                 if len(newFiles) > 0 {
    2962            1 :                                         curFile = newFiles[len(newFiles)-1].Meta
    2963            1 :                                 } else if curFile == nil {
    2964            1 :                                         // Nothing remains of the file.
    2965            1 :                                         break
    2966              :                                 }
    2967              :                         }
    2968            1 :                         if curFile == nil {
    2969            1 :                                 // Nothing remains of the file.
    2970            1 :                                 break
    2971              :                         }
    2972              :                 }
    2973            1 :                 if _, ok := ve.DeletedTables[manifest.DeletedTableEntry{
    2974            1 :                         Level:   cl.level,
    2975            1 :                         FileNum: f.TableNum,
    2976            1 :                 }]; !ok {
    2977            0 :                         panic("pebble: delete-only compaction scheduled with hints that did not delete or excise a file")
    2978              :                 }
    2979              :         }
    2980            1 :         return nil
    2981              : }
    2982              : 
    2983              : // deleteCompactionHintFragment represents a fragment of the key space and
    2984              : // contains a set of deleteCompactionHints that apply to that fragment; a
    2985              : // fragment starts at the start field and ends where the next fragment starts.
    2986              : type deleteCompactionHintFragment struct {
    2987              :         start []byte
    2988              :         hints []deleteCompactionHint
    2989              : }
    2990              : 
    2991              : // Delete compaction hints can overlap with each other, and multiple fragments
    2992              : // can apply to a single file. This function takes a list of hints and fragments
    2993              : // them, to make it easier to apply them to non-overlapping files occupying a level;
    2994              : // that way, files and hint fragments can be iterated on in lockstep, while efficiently
    2995              : // being able to apply all hints overlapping with a given file.
    2996              : func fragmentDeleteCompactionHints(
    2997              :         cmp Compare, hints []deleteCompactionHint,
    2998            1 : ) []deleteCompactionHintFragment {
    2999            1 :         fragments := make([]deleteCompactionHintFragment, 0, len(hints)*2)
    3000            1 :         for i := range hints {
    3001            1 :                 fragments = append(fragments, deleteCompactionHintFragment{start: hints[i].start},
    3002            1 :                         deleteCompactionHintFragment{start: hints[i].end})
    3003            1 :         }
    3004            1 :         slices.SortFunc(fragments, func(i, j deleteCompactionHintFragment) int {
    3005            1 :                 return cmp(i.start, j.start)
    3006            1 :         })
    3007            1 :         fragments = slices.CompactFunc(fragments, func(i, j deleteCompactionHintFragment) bool {
    3008            1 :                 return bytes.Equal(i.start, j.start)
    3009            1 :         })
    3010            1 :         for _, h := range hints {
    3011            1 :                 startIdx := sort.Search(len(fragments), func(i int) bool {
    3012            1 :                         return cmp(fragments[i].start, h.start) >= 0
    3013            1 :                 })
    3014            1 :                 endIdx := sort.Search(len(fragments), func(i int) bool {
    3015            1 :                         return cmp(fragments[i].start, h.end) >= 0
    3016            1 :                 })
    3017            1 :                 for i := startIdx; i < endIdx; i++ {
    3018            1 :                         fragments[i].hints = append(fragments[i].hints, h)
    3019            1 :                 }
    3020              :         }
    3021            1 :         return fragments
    3022              : }
    3023              : 
    3024              : // Runs a delete-only compaction.
    3025              : //
    3026              : // d.mu must *not* be held when calling this.
    3027              : func (d *DB) runDeleteOnlyCompaction(
    3028              :         jobID JobID, c *compaction, snapshots compact.Snapshots,
    3029            1 : ) (ve *manifest.VersionEdit, stats compact.Stats, retErr error) {
    3030            1 :         fragments := fragmentDeleteCompactionHints(d.cmp, c.deletionHints)
    3031            1 :         ve = &manifest.VersionEdit{
    3032            1 :                 DeletedTables: map[manifest.DeletedTableEntry]*manifest.TableMetadata{},
    3033            1 :         }
    3034            1 :         for _, cl := range c.inputs {
    3035            1 :                 levelMetrics := &LevelMetrics{}
    3036            1 :                 if err := d.runDeleteOnlyCompactionForLevel(cl, levelMetrics, ve, snapshots, fragments, c.exciseEnabled); err != nil {
    3037            0 :                         return nil, stats, err
    3038            0 :                 }
    3039            1 :                 c.metrics[cl.level] = levelMetrics
    3040              :         }
    3041              :         // Remove any files that were added and deleted in the same versionEdit.
    3042            1 :         ve.NewTables = slices.DeleteFunc(ve.NewTables, func(e manifest.NewTableEntry) bool {
    3043            1 :                 entry := manifest.DeletedTableEntry{Level: e.Level, FileNum: e.Meta.TableNum}
    3044            1 :                 if _, deleted := ve.DeletedTables[entry]; deleted {
    3045            1 :                         delete(ve.DeletedTables, entry)
    3046            1 :                         return true
    3047            1 :                 }
    3048            1 :                 return false
    3049              :         })
    3050              :         // Remove any entries from CreatedBackingTables that are not used in any
    3051              :         // NewFiles.
    3052            1 :         usedBackingFiles := make(map[base.DiskFileNum]struct{})
    3053            1 :         for _, e := range ve.NewTables {
    3054            1 :                 if e.Meta.Virtual {
    3055            1 :                         usedBackingFiles[e.Meta.TableBacking.DiskFileNum] = struct{}{}
    3056            1 :                 }
    3057              :         }
    3058            1 :         ve.CreatedBackingTables = slices.DeleteFunc(ve.CreatedBackingTables, func(b *manifest.TableBacking) bool {
    3059            1 :                 _, used := usedBackingFiles[b.DiskFileNum]
    3060            1 :                 return !used
    3061            1 :         })
    3062              :         // Refresh the disk available statistic whenever a compaction/flush
    3063              :         // completes, before re-acquiring the mutex.
    3064            1 :         d.calculateDiskAvailableBytes()
    3065            1 :         return ve, stats, nil
    3066              : }
    3067              : 
    3068              : func (d *DB) runMoveCompaction(
    3069              :         jobID JobID, c *compaction,
    3070            1 : ) (ve *manifest.VersionEdit, stats compact.Stats, _ error) {
    3071            1 :         iter := c.startLevel.files.Iter()
    3072            1 :         meta := iter.First()
    3073            1 :         if iter.Next() != nil {
    3074            0 :                 return nil, stats, base.AssertionFailedf("got more than one file for a move compaction")
    3075            0 :         }
    3076            1 :         if c.cancel.Load() {
    3077            0 :                 return ve, stats, ErrCancelledCompaction
    3078            0 :         }
    3079            1 :         c.metrics[c.outputLevel.level] = &LevelMetrics{
    3080            1 :                 TableBytesMoved: meta.Size,
    3081            1 :                 TablesMoved:     1,
    3082            1 :         }
    3083            1 :         ve = &manifest.VersionEdit{
    3084            1 :                 DeletedTables: map[manifest.DeletedTableEntry]*manifest.TableMetadata{
    3085            1 :                         {Level: c.startLevel.level, FileNum: meta.TableNum}: meta,
    3086            1 :                 },
    3087            1 :                 NewTables: []manifest.NewTableEntry{
    3088            1 :                         {Level: c.outputLevel.level, Meta: meta},
    3089            1 :                 },
    3090            1 :         }
    3091            1 : 
    3092            1 :         return ve, stats, nil
    3093              : }
    3094              : 
    3095              : // runCompaction runs a compaction that produces new on-disk tables from
    3096              : // memtables or old on-disk tables.
    3097              : //
    3098              : // runCompaction cannot be used for compactionKindIngestedFlushable.
    3099              : //
    3100              : // d.mu must be held when calling this, but the mutex may be dropped and
    3101              : // re-acquired during the course of this method.
    3102              : func (d *DB) runCompaction(
    3103              :         jobID JobID, c *compaction,
    3104            1 : ) (ve *manifest.VersionEdit, stats compact.Stats, retErr error) {
    3105            1 :         if c.cancel.Load() {
    3106            1 :                 return ve, stats, ErrCancelledCompaction
    3107            1 :         }
    3108            1 :         switch c.kind {
    3109            1 :         case compactionKindDeleteOnly:
    3110            1 :                 // Release the d.mu lock while doing I/O.
    3111            1 :                 // Note the unusual order: Unlock and then Lock.
    3112            1 :                 snapshots := d.mu.snapshots.toSlice()
    3113            1 :                 d.mu.Unlock()
    3114            1 :                 defer d.mu.Lock()
    3115            1 :                 return d.runDeleteOnlyCompaction(jobID, c, snapshots)
    3116            1 :         case compactionKindMove:
    3117            1 :                 return d.runMoveCompaction(jobID, c)
    3118            1 :         case compactionKindCopy:
    3119            1 :                 return d.runCopyCompaction(jobID, c)
    3120            0 :         case compactionKindIngestedFlushable:
    3121            0 :                 panic("pebble: runCompaction cannot handle compactionKindIngestedFlushable.")
    3122              :         }
    3123              : 
    3124            1 :         snapshots := d.mu.snapshots.toSlice()
    3125            1 : 
    3126            1 :         // Release the d.mu lock while doing I/O.
    3127            1 :         // Note the unusual order: Unlock and then Lock.
    3128            1 :         d.mu.Unlock()
    3129            1 :         defer d.mu.Lock()
    3130            1 : 
    3131            1 :         // Determine whether we should separate values into blob files.
    3132            1 :         //
    3133            1 :         // TODO(jackson): Currently we never separate values in non-tests. Choose
    3134            1 :         // and initialize the appropriate ValueSeparation implementation based on
    3135            1 :         // Options and the compaction inputs.
    3136            1 :         valueSeparation := c.getValueSeparation(jobID, c, c.tableFormat)
    3137            1 : 
    3138            1 :         result := d.compactAndWrite(jobID, c, snapshots, c.tableFormat, valueSeparation)
    3139            1 :         if result.Err == nil {
    3140            1 :                 ve, result.Err = c.makeVersionEdit(result)
    3141            1 :         }
    3142            1 :         if result.Err != nil {
    3143            1 :                 // Delete any created tables or blob files.
    3144            1 :                 obsoleteFiles := manifest.ObsoleteFiles{
    3145            1 :                         TableBackings: make([]*manifest.TableBacking, 0, len(result.Tables)),
    3146            1 :                         BlobFiles:     make([]*manifest.PhysicalBlobFile, 0, len(result.Blobs)),
    3147            1 :                 }
    3148            1 :                 d.mu.Lock()
    3149            1 :                 for i := range result.Tables {
    3150            1 :                         backing := &manifest.TableBacking{
    3151            1 :                                 DiskFileNum: result.Tables[i].ObjMeta.DiskFileNum,
    3152            1 :                                 Size:        result.Tables[i].WriterMeta.Size,
    3153            1 :                         }
    3154            1 :                         obsoleteFiles.AddBacking(backing)
    3155            1 :                         // Add this file to zombie tables as well, as the versionSet
    3156            1 :                         // asserts on whether every obsolete file was at one point
    3157            1 :                         // marked zombie.
    3158            1 :                         d.mu.versions.zombieTables.AddMetadata(&result.Tables[i].ObjMeta, backing.Size)
    3159            1 :                 }
    3160            1 :                 for i := range result.Blobs {
    3161            0 :                         obsoleteFiles.AddBlob(result.Blobs[i].Metadata)
    3162            0 :                         // Add this file to zombie blobs as well, as the versionSet
    3163            0 :                         // asserts on whether every obsolete file was at one point
    3164            0 :                         // marked zombie.
    3165            0 :                         d.mu.versions.zombieBlobs.AddMetadata(&result.Blobs[i].ObjMeta, result.Blobs[i].Metadata.Size)
    3166            0 :                 }
    3167            1 :                 d.mu.versions.addObsoleteLocked(obsoleteFiles)
    3168            1 :                 d.mu.Unlock()
    3169              :         }
    3170              :         // Refresh the disk available statistic whenever a compaction/flush
    3171              :         // completes, before re-acquiring the mutex.
    3172            1 :         d.calculateDiskAvailableBytes()
    3173            1 :         return ve, result.Stats, result.Err
    3174              : }
    3175              : 
    3176              : // compactAndWrite runs the data part of a compaction, where we set up a
    3177              : // compaction iterator and use it to write output tables.
    3178              : func (d *DB) compactAndWrite(
    3179              :         jobID JobID,
    3180              :         c *compaction,
    3181              :         snapshots compact.Snapshots,
    3182              :         tableFormat sstable.TableFormat,
    3183              :         valueSeparation compact.ValueSeparation,
    3184            1 : ) (result compact.Result) {
    3185            1 :         // Compactions use a pool of buffers to read blocks, avoiding polluting the
    3186            1 :         // block cache with blocks that will not be read again. We initialize the
    3187            1 :         // buffer pool with a size 12. This initial size does not need to be
    3188            1 :         // accurate, because the pool will grow to accommodate the maximum number of
    3189            1 :         // blocks allocated at a given time over the course of the compaction. But
    3190            1 :         // choosing a size larger than that working set avoids any additional
    3191            1 :         // allocations to grow the size of the pool over the course of iteration.
    3192            1 :         //
    3193            1 :         // Justification for initial size 12: In a two-level compaction, at any
    3194            1 :         // given moment we'll have 2 index blocks in-use and 2 data blocks in-use.
    3195            1 :         // Additionally, when decoding a compressed block, we'll temporarily
    3196            1 :         // allocate 1 additional block to hold the compressed buffer. In the worst
    3197            1 :         // case that all input sstables have two-level index blocks (+2), value
    3198            1 :         // blocks (+2), range deletion blocks (+n) and range key blocks (+n), we'll
    3199            1 :         // additionally require 2n+4 blocks where n is the number of input sstables.
    3200            1 :         // Range deletion and range key blocks are relatively rare, and the cost of
    3201            1 :         // an additional allocation or two over the course of the compaction is
    3202            1 :         // considered to be okay. A larger initial size would cause the pool to hold
    3203            1 :         // on to more memory, even when it's not in-use because the pool will
    3204            1 :         // recycle buffers up to the current capacity of the pool. The memory use of
    3205            1 :         // a 12-buffer pool is expected to be within reason, even if all the buffers
    3206            1 :         // grow to the typical size of an index block (256 KiB) which would
    3207            1 :         // translate to 3 MiB per compaction.
    3208            1 :         c.bufferPool.Init(12)
    3209            1 :         defer c.bufferPool.Release()
    3210            1 :         blockReadEnv := block.ReadEnv{
    3211            1 :                 BufferPool: &c.bufferPool,
    3212            1 :                 Stats:      &c.stats,
    3213            1 :                 IterStats: d.fileCache.SSTStatsCollector().Accumulator(
    3214            1 :                         uint64(uintptr(unsafe.Pointer(c))),
    3215            1 :                         categoryCompaction,
    3216            1 :                 ),
    3217            1 :         }
    3218            1 :         c.valueFetcher.Init(&c.version.BlobFiles, d.fileCache, blockReadEnv)
    3219            1 :         iiopts := internalIterOpts{
    3220            1 :                 compaction:       true,
    3221            1 :                 readEnv:          sstable.ReadEnv{Block: blockReadEnv},
    3222            1 :                 blobValueFetcher: &c.valueFetcher,
    3223            1 :         }
    3224            1 :         defer func() { _ = c.valueFetcher.Close() }()
    3225              : 
    3226            1 :         pointIter, rangeDelIter, rangeKeyIter, err := c.newInputIters(d.newIters, d.tableNewRangeKeyIter, iiopts)
    3227            1 :         defer func() {
    3228            1 :                 for _, closer := range c.closers {
    3229            1 :                         closer.FragmentIterator.Close()
    3230            1 :                 }
    3231              :         }()
    3232            1 :         if err != nil {
    3233            0 :                 return compact.Result{Err: err}
    3234            0 :         }
    3235            1 :         c.allowedZeroSeqNum = c.allowZeroSeqNum()
    3236            1 :         cfg := compact.IterConfig{
    3237            1 :                 Comparer:         c.comparer,
    3238            1 :                 Merge:            d.merge,
    3239            1 :                 TombstoneElision: c.delElision,
    3240            1 :                 RangeKeyElision:  c.rangeKeyElision,
    3241            1 :                 Snapshots:        snapshots,
    3242            1 :                 AllowZeroSeqNum:  c.allowedZeroSeqNum,
    3243            1 :                 IneffectualSingleDeleteCallback: func(userKey []byte) {
    3244            1 :                         d.opts.EventListener.PossibleAPIMisuse(PossibleAPIMisuseInfo{
    3245            1 :                                 Kind:    IneffectualSingleDelete,
    3246            1 :                                 UserKey: slices.Clone(userKey),
    3247            1 :                         })
    3248            1 :                 },
    3249            0 :                 NondeterministicSingleDeleteCallback: func(userKey []byte) {
    3250            0 :                         d.opts.EventListener.PossibleAPIMisuse(PossibleAPIMisuseInfo{
    3251            0 :                                 Kind:    NondeterministicSingleDelete,
    3252            0 :                                 UserKey: slices.Clone(userKey),
    3253            0 :                         })
    3254            0 :                 },
    3255            1 :                 MissizedDeleteCallback: func(userKey []byte, elidedSize, expectedSize uint64) {
    3256            1 :                         d.opts.EventListener.PossibleAPIMisuse(PossibleAPIMisuseInfo{
    3257            1 :                                 Kind:      MissizedDelete,
    3258            1 :                                 UserKey:   slices.Clone(userKey),
    3259            1 :                                 ExtraInfo: fmt.Sprintf("elidedSize=%d,expectedSize=%d", elidedSize, expectedSize),
    3260            1 :                         })
    3261            1 :                 },
    3262              :         }
    3263            1 :         iter := compact.NewIter(cfg, pointIter, rangeDelIter, rangeKeyIter)
    3264            1 : 
    3265            1 :         runnerCfg := compact.RunnerConfig{
    3266            1 :                 CompactionBounds:           base.UserKeyBoundsFromInternal(c.smallest, c.largest),
    3267            1 :                 L0SplitKeys:                c.l0Limits,
    3268            1 :                 Grandparents:               c.grandparents,
    3269            1 :                 MaxGrandparentOverlapBytes: c.maxOverlapBytes,
    3270            1 :                 TargetOutputFileSize:       c.maxOutputFileSize,
    3271            1 :                 GrantHandle:                c.grantHandle,
    3272            1 :         }
    3273            1 :         runner := compact.NewRunner(runnerCfg, iter)
    3274            1 : 
    3275            1 :         var spanPolicyValid bool
    3276            1 :         var spanPolicy SpanPolicy
    3277            1 :         // If spanPolicyValid is true and spanPolicyEndKey is empty, then spanPolicy
    3278            1 :         // applies for the rest of the keyspace.
    3279            1 :         var spanPolicyEndKey []byte
    3280            1 : 
    3281            1 :         for runner.MoreDataToWrite() {
    3282            1 :                 if c.cancel.Load() {
    3283            1 :                         return runner.Finish().WithError(ErrCancelledCompaction)
    3284            1 :                 }
    3285              :                 // Create a new table.
    3286            1 :                 firstKey := runner.FirstKey()
    3287            1 :                 if !spanPolicyValid || (len(spanPolicyEndKey) > 0 && d.cmp(firstKey, spanPolicyEndKey) >= 0) {
    3288            1 :                         var err error
    3289            1 :                         spanPolicy, spanPolicyEndKey, err = d.opts.Experimental.SpanPolicyFunc(firstKey)
    3290            1 :                         if err != nil {
    3291            0 :                                 return runner.Finish().WithError(err)
    3292            0 :                         }
    3293            1 :                         spanPolicyValid = true
    3294              :                 }
    3295              : 
    3296            1 :                 writerOpts := d.opts.MakeWriterOptions(c.outputLevel.level, tableFormat)
    3297            1 :                 if spanPolicy.DisableValueSeparationBySuffix {
    3298            0 :                         writerOpts.DisableValueBlocks = true
    3299            0 :                 }
    3300            1 :                 vSep := valueSeparation
    3301            1 :                 if spanPolicy.ValueStoragePolicy == ValueStorageLowReadLatency {
    3302            0 :                         vSep = compact.NeverSeparateValues{}
    3303            0 :                 }
    3304            1 :                 objMeta, tw, err := d.newCompactionOutputTable(jobID, c, writerOpts)
    3305            1 :                 if err != nil {
    3306            0 :                         return runner.Finish().WithError(err)
    3307            0 :                 }
    3308            1 :                 runner.WriteTable(objMeta, tw, spanPolicyEndKey, vSep)
    3309              :         }
    3310            1 :         result = runner.Finish()
    3311            1 :         if result.Err == nil {
    3312            1 :                 result.Err = d.objProvider.Sync()
    3313            1 :         }
    3314            1 :         return result
    3315              : }
    3316              : 
    3317              : // makeVersionEdit creates the version edit for a compaction, based on the
    3318              : // tables in compact.Result.
    3319            1 : func (c *compaction) makeVersionEdit(result compact.Result) (*manifest.VersionEdit, error) {
    3320            1 :         ve := &manifest.VersionEdit{
    3321            1 :                 DeletedTables: map[manifest.DeletedTableEntry]*manifest.TableMetadata{},
    3322            1 :         }
    3323            1 :         for _, cl := range c.inputs {
    3324            1 :                 for f := range cl.files.All() {
    3325            1 :                         ve.DeletedTables[manifest.DeletedTableEntry{
    3326            1 :                                 Level:   cl.level,
    3327            1 :                                 FileNum: f.TableNum,
    3328            1 :                         }] = f
    3329            1 :                 }
    3330              :         }
    3331              :         // Add any newly constructed blob files to the version edit.
    3332            1 :         ve.NewBlobFiles = make([]manifest.BlobFileMetadata, len(result.Blobs))
    3333            1 :         for i := range result.Blobs {
    3334            1 :                 ve.NewBlobFiles[i] = manifest.BlobFileMetadata{
    3335            1 :                         FileID:   base.BlobFileID(result.Blobs[i].Metadata.FileNum),
    3336            1 :                         Physical: result.Blobs[i].Metadata,
    3337            1 :                 }
    3338            1 :         }
    3339              : 
    3340            1 :         startLevelBytes := c.startLevel.files.TableSizeSum()
    3341            1 :         outputMetrics := &LevelMetrics{
    3342            1 :                 TableBytesIn: startLevelBytes,
    3343            1 :                 // TODO(jackson):  This BytesRead value does not include any blob files
    3344            1 :                 // written. It either should, or we should add a separate metric.
    3345            1 :                 TableBytesRead:     c.outputLevel.files.TableSizeSum(),
    3346            1 :                 BlobBytesCompacted: result.Stats.CumulativeBlobFileSize,
    3347            1 :         }
    3348            1 :         if c.flushing != nil {
    3349            1 :                 outputMetrics.BlobBytesFlushed = result.Stats.CumulativeBlobFileSize
    3350            1 :         }
    3351            1 :         if len(c.extraLevels) > 0 {
    3352            1 :                 outputMetrics.TableBytesIn += c.extraLevels[0].files.TableSizeSum()
    3353            1 :         }
    3354            1 :         outputMetrics.TableBytesRead += outputMetrics.TableBytesIn
    3355            1 : 
    3356            1 :         c.metrics[c.outputLevel.level] = outputMetrics
    3357            1 :         if len(c.flushing) == 0 && c.metrics[c.startLevel.level] == nil {
    3358            1 :                 c.metrics[c.startLevel.level] = &LevelMetrics{}
    3359            1 :         }
    3360            1 :         if len(c.extraLevels) > 0 {
    3361            1 :                 c.metrics[c.extraLevels[0].level] = &LevelMetrics{}
    3362            1 :                 outputMetrics.MultiLevel.TableBytesInTop = startLevelBytes
    3363            1 :                 outputMetrics.MultiLevel.TableBytesIn = outputMetrics.TableBytesIn
    3364            1 :                 outputMetrics.MultiLevel.TableBytesRead = outputMetrics.TableBytesRead
    3365            1 :         }
    3366              : 
    3367            1 :         inputLargestSeqNumAbsolute := c.inputLargestSeqNumAbsolute()
    3368            1 :         ve.NewTables = make([]manifest.NewTableEntry, len(result.Tables))
    3369            1 :         for i := range result.Tables {
    3370            1 :                 t := &result.Tables[i]
    3371            1 : 
    3372            1 :                 if t.WriterMeta.Properties.NumValuesInBlobFiles > 0 {
    3373            1 :                         if len(t.BlobReferences) == 0 {
    3374            0 :                                 return nil, base.AssertionFailedf("num values in blob files %d but no blob references",
    3375            0 :                                         t.WriterMeta.Properties.NumValuesInBlobFiles)
    3376            0 :                         }
    3377              :                 }
    3378              : 
    3379            1 :                 fileMeta := &manifest.TableMetadata{
    3380            1 :                         TableNum:           base.PhysicalTableFileNum(t.ObjMeta.DiskFileNum),
    3381            1 :                         CreationTime:       t.CreationTime.Unix(),
    3382            1 :                         Size:               t.WriterMeta.Size,
    3383            1 :                         SmallestSeqNum:     t.WriterMeta.SmallestSeqNum,
    3384            1 :                         LargestSeqNum:      t.WriterMeta.LargestSeqNum,
    3385            1 :                         BlobReferences:     t.BlobReferences,
    3386            1 :                         BlobReferenceDepth: t.BlobReferenceDepth,
    3387            1 :                 }
    3388            1 :                 if c.flushing == nil {
    3389            1 :                         // Set the file's LargestSeqNumAbsolute to be the maximum value of any
    3390            1 :                         // of the compaction's input sstables.
    3391            1 :                         // TODO(jackson): This could be narrowed to be the maximum of input
    3392            1 :                         // sstables that overlap the output sstable's key range.
    3393            1 :                         fileMeta.LargestSeqNumAbsolute = inputLargestSeqNumAbsolute
    3394            1 :                 } else {
    3395            1 :                         fileMeta.LargestSeqNumAbsolute = t.WriterMeta.LargestSeqNum
    3396            1 :                 }
    3397            1 :                 fileMeta.InitPhysicalBacking()
    3398            1 : 
    3399            1 :                 // If the file didn't contain any range deletions, we can fill its
    3400            1 :                 // table stats now, avoiding unnecessarily loading the table later.
    3401            1 :                 maybeSetStatsFromProperties(
    3402            1 :                         fileMeta.PhysicalMeta(), &t.WriterMeta.Properties.CommonProperties, c.logger,
    3403            1 :                 )
    3404            1 : 
    3405            1 :                 if t.WriterMeta.HasPointKeys {
    3406            1 :                         fileMeta.ExtendPointKeyBounds(c.cmp, t.WriterMeta.SmallestPoint, t.WriterMeta.LargestPoint)
    3407            1 :                 }
    3408            1 :                 if t.WriterMeta.HasRangeDelKeys {
    3409            1 :                         fileMeta.ExtendPointKeyBounds(c.cmp, t.WriterMeta.SmallestRangeDel, t.WriterMeta.LargestRangeDel)
    3410            1 :                 }
    3411            1 :                 if t.WriterMeta.HasRangeKeys {
    3412            1 :                         fileMeta.ExtendRangeKeyBounds(c.cmp, t.WriterMeta.SmallestRangeKey, t.WriterMeta.LargestRangeKey)
    3413            1 :                 }
    3414              : 
    3415            1 :                 ve.NewTables[i] = manifest.NewTableEntry{
    3416            1 :                         Level: c.outputLevel.level,
    3417            1 :                         Meta:  fileMeta,
    3418            1 :                 }
    3419            1 : 
    3420            1 :                 // Update metrics.
    3421            1 :                 if c.flushing == nil {
    3422            1 :                         outputMetrics.TablesCompacted++
    3423            1 :                         outputMetrics.TableBytesCompacted += fileMeta.Size
    3424            1 :                 } else {
    3425            1 :                         outputMetrics.TablesFlushed++
    3426            1 :                         outputMetrics.TableBytesFlushed += fileMeta.Size
    3427            1 :                 }
    3428            1 :                 outputMetrics.EstimatedReferencesSize += fileMeta.EstimatedReferenceSize()
    3429            1 :                 outputMetrics.BlobBytesReadEstimate += fileMeta.EstimatedReferenceSize()
    3430            1 :                 outputMetrics.TablesSize += int64(fileMeta.Size)
    3431            1 :                 outputMetrics.TablesCount++
    3432            1 :                 outputMetrics.Additional.BytesWrittenDataBlocks += t.WriterMeta.Properties.DataSize
    3433            1 :                 outputMetrics.Additional.BytesWrittenValueBlocks += t.WriterMeta.Properties.ValueBlocksSize
    3434              :         }
    3435              : 
    3436              :         // Sanity check that the tables are ordered and don't overlap.
    3437            1 :         for i := 1; i < len(ve.NewTables); i++ {
    3438            1 :                 if ve.NewTables[i-1].Meta.UserKeyBounds().End.IsUpperBoundFor(c.cmp, ve.NewTables[i].Meta.Smallest().UserKey) {
    3439            0 :                         return nil, base.AssertionFailedf("pebble: compaction output tables overlap: %s and %s",
    3440            0 :                                 ve.NewTables[i-1].Meta.DebugString(c.formatKey, true),
    3441            0 :                                 ve.NewTables[i].Meta.DebugString(c.formatKey, true),
    3442            0 :                         )
    3443            0 :                 }
    3444              :         }
    3445              : 
    3446            1 :         return ve, nil
    3447              : }
    3448              : 
    3449              : // newCompactionOutputTable creates an object for a new table produced by a
    3450              : // compaction or flush.
    3451              : func (d *DB) newCompactionOutputTable(
    3452              :         jobID JobID, c *compaction, writerOpts sstable.WriterOptions,
    3453            1 : ) (objstorage.ObjectMetadata, sstable.RawWriter, error) {
    3454            1 :         writable, objMeta, err := d.newCompactionOutputObj(c, base.FileTypeTable)
    3455            1 :         if err != nil {
    3456            0 :                 return objstorage.ObjectMetadata{}, nil, err
    3457            0 :         }
    3458            1 :         d.opts.EventListener.TableCreated(TableCreateInfo{
    3459            1 :                 JobID:   int(jobID),
    3460            1 :                 Reason:  c.kind.compactingOrFlushing(),
    3461            1 :                 Path:    d.objProvider.Path(objMeta),
    3462            1 :                 FileNum: objMeta.DiskFileNum,
    3463            1 :         })
    3464            1 :         writerOpts.SetInternal(sstableinternal.WriterOptions{
    3465            1 :                 CacheOpts: sstableinternal.CacheOptions{
    3466            1 :                         CacheHandle: d.cacheHandle,
    3467            1 :                         FileNum:     objMeta.DiskFileNum,
    3468            1 :                 },
    3469            1 :         })
    3470            1 :         tw := sstable.NewRawWriterWithCPUMeasurer(writable, writerOpts, c.grantHandle)
    3471            1 :         return objMeta, tw, nil
    3472              : }
    3473              : 
    3474              : // newCompactionOutputBlob creates an object for a new blob produced by a
    3475              : // compaction or flush.
    3476              : func (d *DB) newCompactionOutputBlob(
    3477              :         jobID JobID, c *compaction,
    3478            1 : ) (objstorage.Writable, objstorage.ObjectMetadata, error) {
    3479            1 :         writable, objMeta, err := d.newCompactionOutputObj(c, base.FileTypeBlob)
    3480            1 :         if err != nil {
    3481            0 :                 return nil, objstorage.ObjectMetadata{}, err
    3482            0 :         }
    3483            1 :         d.opts.EventListener.BlobFileCreated(BlobFileCreateInfo{
    3484            1 :                 JobID:   int(jobID),
    3485            1 :                 Reason:  c.kind.compactingOrFlushing(),
    3486            1 :                 Path:    d.objProvider.Path(objMeta),
    3487            1 :                 FileNum: objMeta.DiskFileNum,
    3488            1 :         })
    3489            1 :         return writable, objMeta, nil
    3490              : }
    3491              : 
    3492              : // newCompactionOutputObj creates an object produced by a compaction or flush.
    3493              : func (d *DB) newCompactionOutputObj(
    3494              :         c *compaction, typ base.FileType,
    3495            1 : ) (objstorage.Writable, objstorage.ObjectMetadata, error) {
    3496            1 :         diskFileNum := d.mu.versions.getNextDiskFileNum()
    3497            1 :         ctx := context.TODO()
    3498            1 : 
    3499            1 :         if objiotracing.Enabled {
    3500            0 :                 ctx = objiotracing.WithLevel(ctx, c.outputLevel.level)
    3501            0 :                 if c.kind == compactionKindFlush {
    3502            0 :                         ctx = objiotracing.WithReason(ctx, objiotracing.ForFlush)
    3503            0 :                 } else {
    3504            0 :                         ctx = objiotracing.WithReason(ctx, objiotracing.ForCompaction)
    3505            0 :                 }
    3506              :         }
    3507              : 
    3508            1 :         writable, objMeta, err := d.objProvider.Create(ctx, typ, diskFileNum, c.objCreateOpts)
    3509            1 :         if err != nil {
    3510            0 :                 return nil, objstorage.ObjectMetadata{}, err
    3511            0 :         }
    3512              : 
    3513            1 :         if c.kind != compactionKindFlush {
    3514            1 :                 writable = &compactionWritable{
    3515            1 :                         Writable: writable,
    3516            1 :                         versions: d.mu.versions,
    3517            1 :                         written:  &c.bytesWritten,
    3518            1 :                 }
    3519            1 :         }
    3520            1 :         return writable, objMeta, nil
    3521              : }
    3522              : 
    3523              : // validateVersionEdit validates that start and end keys across new and deleted
    3524              : // files in a versionEdit pass the given validation function.
    3525              : func validateVersionEdit(
    3526              :         ve *manifest.VersionEdit, vk base.ValidateKey, format base.FormatKey, logger Logger,
    3527            1 : ) {
    3528            1 :         validateKey := func(f *manifest.TableMetadata, key []byte) {
    3529            1 :                 if err := vk.Validate(key); err != nil {
    3530            0 :                         logger.Fatalf("pebble: version edit validation failed (key=%s file=%s): %v", format(key), f, err)
    3531            0 :                 }
    3532              :         }
    3533              : 
    3534              :         // Validate both new and deleted files.
    3535            1 :         for _, f := range ve.NewTables {
    3536            1 :                 validateKey(f.Meta, f.Meta.Smallest().UserKey)
    3537            1 :                 validateKey(f.Meta, f.Meta.Largest().UserKey)
    3538            1 :         }
    3539            1 :         for _, m := range ve.DeletedTables {
    3540            1 :                 validateKey(m, m.Smallest().UserKey)
    3541            1 :                 validateKey(m, m.Largest().UserKey)
    3542            1 :         }
    3543              : }
    3544              : 
    3545            1 : func getDiskWriteCategoryForCompaction(opts *Options, kind compactionKind) vfs.DiskWriteCategory {
    3546            1 :         if opts.EnableSQLRowSpillMetrics {
    3547            0 :                 // In the scenario that the Pebble engine is used for SQL row spills the
    3548            0 :                 // data written to the memtable will correspond to spills to disk and
    3549            0 :                 // should be categorized as such.
    3550            0 :                 return "sql-row-spill"
    3551            1 :         } else if kind == compactionKindFlush {
    3552            1 :                 return "pebble-memtable-flush"
    3553            1 :         } else {
    3554            1 :                 return "pebble-compaction"
    3555            1 :         }
    3556              : }
        

Generated by: LCOV version 2.0-1