LCOV - code coverage report
Current view: top level - pebble - compaction.go (source / functions) Hit Total Coverage
Test: 2024-04-30 08:16Z 3a03bff0 - tests only.lcov Lines: 2024 2222 91.1 %
Date: 2024-04-30 08:16:50 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             :         "io"
      12             :         "math"
      13             :         "runtime/pprof"
      14             :         "slices"
      15             :         "sort"
      16             :         "sync/atomic"
      17             :         "time"
      18             : 
      19             :         "github.com/cockroachdb/errors"
      20             :         "github.com/cockroachdb/pebble/internal/base"
      21             :         "github.com/cockroachdb/pebble/internal/compact"
      22             :         "github.com/cockroachdb/pebble/internal/invalidating"
      23             :         "github.com/cockroachdb/pebble/internal/invariants"
      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/private"
      28             :         "github.com/cockroachdb/pebble/internal/rangedel"
      29             :         "github.com/cockroachdb/pebble/internal/rangekey"
      30             :         "github.com/cockroachdb/pebble/objstorage"
      31             :         "github.com/cockroachdb/pebble/objstorage/objstorageprovider/objiotracing"
      32             :         "github.com/cockroachdb/pebble/objstorage/remote"
      33             :         "github.com/cockroachdb/pebble/sstable"
      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 compactLabels = pprof.Labels("pebble", "compact")
      44             : var flushLabels = pprof.Labels("pebble", "flush")
      45             : var gcLabels = pprof.Labels("pebble", "gc")
      46             : 
      47             : // getInternalWriterProperties accesses a private variable (in the
      48             : // internal/private package) initialized by the sstable Writer. This indirection
      49             : // is necessary to ensure non-Pebble users constructing sstables for ingestion
      50             : // are unable to set internal-only properties.
      51             : var getInternalWriterProperties = private.SSTableInternalProperties.(func(*sstable.Writer) *sstable.Properties)
      52             : 
      53             : // expandedCompactionByteSizeLimit is the maximum number of bytes in all
      54             : // compacted files. We avoid expanding the lower level file set of a compaction
      55             : // if it would make the total compaction cover more than this many bytes.
      56           1 : func expandedCompactionByteSizeLimit(opts *Options, level int, availBytes uint64) uint64 {
      57           1 :         v := uint64(25 * opts.Level(level).TargetFileSize)
      58           1 : 
      59           1 :         // Never expand a compaction beyond half the available capacity, divided
      60           1 :         // by the maximum number of concurrent compactions. Each of the concurrent
      61           1 :         // compactions may expand up to this limit, so this attempts to limit
      62           1 :         // compactions to half of available disk space. Note that this will not
      63           1 :         // prevent compaction picking from pursuing compactions that are larger
      64           1 :         // than this threshold before expansion.
      65           1 :         diskMax := (availBytes / 2) / uint64(opts.MaxConcurrentCompactions())
      66           1 :         if v > diskMax {
      67           1 :                 v = diskMax
      68           1 :         }
      69           1 :         return v
      70             : }
      71             : 
      72             : // maxGrandparentOverlapBytes is the maximum bytes of overlap with level+1
      73             : // before we stop building a single file in a level-1 to level compaction.
      74           1 : func maxGrandparentOverlapBytes(opts *Options, level int) uint64 {
      75           1 :         return uint64(10 * opts.Level(level).TargetFileSize)
      76           1 : }
      77             : 
      78             : // maxReadCompactionBytes is used to prevent read compactions which
      79             : // are too wide.
      80           1 : func maxReadCompactionBytes(opts *Options, level int) uint64 {
      81           1 :         return uint64(10 * opts.Level(level).TargetFileSize)
      82           1 : }
      83             : 
      84             : // noCloseIter wraps around a FragmentIterator, intercepting and eliding
      85             : // calls to Close. It is used during compaction to ensure that rangeDelIters
      86             : // are not closed prematurely.
      87             : type noCloseIter struct {
      88             :         keyspan.FragmentIterator
      89             : }
      90             : 
      91           1 : func (i noCloseIter) Close() error {
      92           1 :         return nil
      93           1 : }
      94             : 
      95             : type compactionLevel struct {
      96             :         level int
      97             :         files manifest.LevelSlice
      98             :         // l0SublevelInfo contains information about L0 sublevels being compacted.
      99             :         // It's only set for the start level of a compaction starting out of L0 and
     100             :         // is nil for all other compactions.
     101             :         l0SublevelInfo []sublevelInfo
     102             : }
     103             : 
     104           1 : func (cl compactionLevel) Clone() compactionLevel {
     105           1 :         newCL := compactionLevel{
     106           1 :                 level: cl.level,
     107           1 :                 files: cl.files.Reslice(func(start, end *manifest.LevelIterator) {}),
     108             :         }
     109           1 :         return newCL
     110             : }
     111           1 : func (cl compactionLevel) String() string {
     112           1 :         return fmt.Sprintf(`Level %d, Files %s`, cl.level, cl.files)
     113           1 : }
     114             : 
     115             : // compactionWritable is a objstorage.Writable wrapper that, on every write,
     116             : // updates a metric in `versions` on bytes written by in-progress compactions so
     117             : // far. It also increments a per-compaction `written` int.
     118             : type compactionWritable struct {
     119             :         objstorage.Writable
     120             : 
     121             :         versions *versionSet
     122             :         written  *int64
     123             : }
     124             : 
     125             : // Write is part of the objstorage.Writable interface.
     126           1 : func (c *compactionWritable) Write(p []byte) error {
     127           1 :         if err := c.Writable.Write(p); err != nil {
     128           0 :                 return err
     129           0 :         }
     130             : 
     131           1 :         *c.written += int64(len(p))
     132           1 :         c.versions.incrementCompactionBytes(int64(len(p)))
     133           1 :         return nil
     134             : }
     135             : 
     136             : type compactionKind int
     137             : 
     138             : const (
     139             :         compactionKindDefault compactionKind = iota
     140             :         compactionKindFlush
     141             :         // compactionKindMove denotes a move compaction where the input file is
     142             :         // retained and linked in a new level without being obsoleted.
     143             :         compactionKindMove
     144             :         // compactionKindCopy denotes a copy compaction where the input file is
     145             :         // copied byte-by-byte into a new file with a new FileNum in the output level.
     146             :         compactionKindCopy
     147             :         // compactionKindDeleteOnly denotes a compaction that only deletes input
     148             :         // files. It can occur when wide range tombstones completely contain sstables.
     149             :         compactionKindDeleteOnly
     150             :         compactionKindElisionOnly
     151             :         compactionKindRead
     152             :         compactionKindRewrite
     153             :         compactionKindIngestedFlushable
     154             : )
     155             : 
     156           1 : func (k compactionKind) String() string {
     157           1 :         switch k {
     158           1 :         case compactionKindDefault:
     159           1 :                 return "default"
     160           0 :         case compactionKindFlush:
     161           0 :                 return "flush"
     162           1 :         case compactionKindMove:
     163           1 :                 return "move"
     164           1 :         case compactionKindDeleteOnly:
     165           1 :                 return "delete-only"
     166           1 :         case compactionKindElisionOnly:
     167           1 :                 return "elision-only"
     168           1 :         case compactionKindRead:
     169           1 :                 return "read"
     170           1 :         case compactionKindRewrite:
     171           1 :                 return "rewrite"
     172           0 :         case compactionKindIngestedFlushable:
     173           0 :                 return "ingested-flushable"
     174           1 :         case compactionKindCopy:
     175           1 :                 return "copy"
     176             :         }
     177           0 :         return "?"
     178             : }
     179             : 
     180             : // compaction is a table compaction from one level to the next, starting from a
     181             : // given version.
     182             : type compaction struct {
     183             :         // cancel is a bool that can be used by other goroutines to signal a compaction
     184             :         // to cancel, such as if a conflicting excise operation raced it to manifest
     185             :         // application. Only holders of the manifest lock will write to this atomic.
     186             :         cancel atomic.Bool
     187             : 
     188             :         kind compactionKind
     189             :         // isDownload is true if this compaction was started as part of a Download
     190             :         // operation. In this case kind is compactionKindCopy or
     191             :         // compactionKindRewrite.
     192             :         isDownload bool
     193             : 
     194             :         cmp       Compare
     195             :         equal     Equal
     196             :         comparer  *base.Comparer
     197             :         formatKey base.FormatKey
     198             :         logger    Logger
     199             :         version   *version
     200             :         stats     base.InternalIteratorStats
     201             :         beganAt   time.Time
     202             :         // versionEditApplied is set to true when a compaction has completed and the
     203             :         // resulting version has been installed (if successful), but the compaction
     204             :         // goroutine is still cleaning up (eg, deleting obsolete files).
     205             :         versionEditApplied bool
     206             :         bufferPool         sstable.BufferPool
     207             : 
     208             :         // startLevel is the level that is being compacted. Inputs from startLevel
     209             :         // and outputLevel will be merged to produce a set of outputLevel files.
     210             :         startLevel *compactionLevel
     211             : 
     212             :         // outputLevel is the level that files are being produced in. outputLevel is
     213             :         // equal to startLevel+1 except when:
     214             :         //    - if startLevel is 0, the output level equals compactionPicker.baseLevel().
     215             :         //    - in multilevel compaction, the output level is the lowest level involved in
     216             :         //      the compaction
     217             :         // A compaction's outputLevel is nil for delete-only compactions.
     218             :         outputLevel *compactionLevel
     219             : 
     220             :         // extraLevels point to additional levels in between the input and output
     221             :         // levels that get compacted in multilevel compactions
     222             :         extraLevels []*compactionLevel
     223             : 
     224             :         inputs []compactionLevel
     225             : 
     226             :         // maxOutputFileSize is the maximum size of an individual table created
     227             :         // during compaction.
     228             :         maxOutputFileSize uint64
     229             :         // maxOverlapBytes is the maximum number of bytes of overlap allowed for a
     230             :         // single output table with the tables in the grandparent level.
     231             :         maxOverlapBytes uint64
     232             : 
     233             :         // flushing contains the flushables (aka memtables) that are being flushed.
     234             :         flushing flushableList
     235             :         // bytesWritten contains the number of bytes that have been written to outputs.
     236             :         bytesWritten int64
     237             : 
     238             :         // The boundaries of the input data.
     239             :         smallest InternalKey
     240             :         largest  InternalKey
     241             : 
     242             :         // rangeDelInterlaving is an interleaving iterator for range deletions, that
     243             :         // interleaves range tombstones among the point keys.
     244             :         rangeDelInterleaving keyspan.InterleavingIter
     245             :         // rangeKeyInterleaving is the interleaving iter for range keys.
     246             :         rangeKeyInterleaving keyspan.InterleavingIter
     247             : 
     248             :         // A list of objects to close when the compaction finishes. Used by input
     249             :         // iteration to keep rangeDelIters open for the lifetime of the compaction,
     250             :         // and only close them when the compaction finishes.
     251             :         closers []io.Closer
     252             : 
     253             :         // grandparents are the tables in level+2 that overlap with the files being
     254             :         // compacted. Used to determine output table boundaries. Do not assume that the actual files
     255             :         // in the grandparent when this compaction finishes will be the same.
     256             :         grandparents manifest.LevelSlice
     257             : 
     258             :         // Boundaries at which flushes to L0 should be split. Determined by
     259             :         // L0Sublevels. If nil, flushes aren't split.
     260             :         l0Limits [][]byte
     261             : 
     262             :         delElision      compact.TombstoneElision
     263             :         rangeKeyElision compact.TombstoneElision
     264             : 
     265             :         // allowedZeroSeqNum is true if seqnums can be zeroed if there are no
     266             :         // snapshots requiring them to be kept. This determination is made by
     267             :         // looking for an sstable which overlaps the bounds of the compaction at a
     268             :         // lower level in the LSM during runCompaction.
     269             :         allowedZeroSeqNum bool
     270             : 
     271             :         metrics map[int]*LevelMetrics
     272             : 
     273             :         pickerMetrics compactionPickerMetrics
     274             : }
     275             : 
     276           1 : func (c *compaction) makeInfo(jobID JobID) CompactionInfo {
     277           1 :         info := CompactionInfo{
     278           1 :                 JobID:       int(jobID),
     279           1 :                 Reason:      c.kind.String(),
     280           1 :                 Input:       make([]LevelInfo, 0, len(c.inputs)),
     281           1 :                 Annotations: []string{},
     282           1 :         }
     283           1 :         if c.isDownload {
     284           1 :                 info.Reason = "download," + info.Reason
     285           1 :         }
     286           1 :         for _, cl := range c.inputs {
     287           1 :                 inputInfo := LevelInfo{Level: cl.level, Tables: nil}
     288           1 :                 iter := cl.files.Iter()
     289           1 :                 for m := iter.First(); m != nil; m = iter.Next() {
     290           1 :                         inputInfo.Tables = append(inputInfo.Tables, m.TableInfo())
     291           1 :                 }
     292           1 :                 info.Input = append(info.Input, inputInfo)
     293             :         }
     294           1 :         if c.outputLevel != nil {
     295           1 :                 info.Output.Level = c.outputLevel.level
     296           1 : 
     297           1 :                 // If there are no inputs from the output level (eg, a move
     298           1 :                 // compaction), add an empty LevelInfo to info.Input.
     299           1 :                 if len(c.inputs) > 0 && c.inputs[len(c.inputs)-1].level != c.outputLevel.level {
     300           0 :                         info.Input = append(info.Input, LevelInfo{Level: c.outputLevel.level})
     301           0 :                 }
     302           1 :         } else {
     303           1 :                 // For a delete-only compaction, set the output level to L6. The
     304           1 :                 // output level is not meaningful here, but complicating the
     305           1 :                 // info.Output interface with a pointer doesn't seem worth the
     306           1 :                 // semantic distinction.
     307           1 :                 info.Output.Level = numLevels - 1
     308           1 :         }
     309             : 
     310           1 :         for i, score := range c.pickerMetrics.scores {
     311           1 :                 info.Input[i].Score = score
     312           1 :         }
     313           1 :         info.SingleLevelOverlappingRatio = c.pickerMetrics.singleLevelOverlappingRatio
     314           1 :         info.MultiLevelOverlappingRatio = c.pickerMetrics.multiLevelOverlappingRatio
     315           1 :         if len(info.Input) > 2 {
     316           1 :                 info.Annotations = append(info.Annotations, "multilevel")
     317           1 :         }
     318           1 :         return info
     319             : }
     320             : 
     321           1 : func (c *compaction) userKeyBounds() base.UserKeyBounds {
     322           1 :         return base.UserKeyBoundsFromInternal(c.smallest, c.largest)
     323           1 : }
     324             : 
     325             : func newCompaction(
     326             :         pc *pickedCompaction, opts *Options, beganAt time.Time, provider objstorage.Provider,
     327           1 : ) *compaction {
     328           1 :         c := &compaction{
     329           1 :                 kind:              compactionKindDefault,
     330           1 :                 cmp:               pc.cmp,
     331           1 :                 equal:             opts.Comparer.Equal,
     332           1 :                 comparer:          opts.Comparer,
     333           1 :                 formatKey:         opts.Comparer.FormatKey,
     334           1 :                 inputs:            pc.inputs,
     335           1 :                 smallest:          pc.smallest,
     336           1 :                 largest:           pc.largest,
     337           1 :                 logger:            opts.Logger,
     338           1 :                 version:           pc.version,
     339           1 :                 beganAt:           beganAt,
     340           1 :                 maxOutputFileSize: pc.maxOutputFileSize,
     341           1 :                 maxOverlapBytes:   pc.maxOverlapBytes,
     342           1 :                 pickerMetrics:     pc.pickerMetrics,
     343           1 :         }
     344           1 :         c.startLevel = &c.inputs[0]
     345           1 :         if pc.startLevel.l0SublevelInfo != nil {
     346           1 :                 c.startLevel.l0SublevelInfo = pc.startLevel.l0SublevelInfo
     347           1 :         }
     348           1 :         c.outputLevel = &c.inputs[1]
     349           1 : 
     350           1 :         if len(pc.extraLevels) > 0 {
     351           1 :                 c.extraLevels = pc.extraLevels
     352           1 :                 c.outputLevel = &c.inputs[len(c.inputs)-1]
     353           1 :         }
     354             :         // Compute the set of outputLevel+1 files that overlap this compaction (these
     355             :         // are the grandparent sstables).
     356           1 :         if c.outputLevel.level+1 < numLevels {
     357           1 :                 c.grandparents = c.version.Overlaps(c.outputLevel.level+1, c.userKeyBounds())
     358           1 :         }
     359           1 :         c.delElision, c.rangeKeyElision = compact.SetupTombstoneElision(
     360           1 :                 c.cmp, c.version, c.outputLevel.level, base.UserKeyBoundsFromInternal(c.smallest, c.largest),
     361           1 :         )
     362           1 :         c.kind = pc.kind
     363           1 : 
     364           1 :         if c.kind == compactionKindDefault && c.outputLevel.files.Empty() && !c.hasExtraLevelData() &&
     365           1 :                 c.startLevel.files.Len() == 1 && c.grandparents.SizeSum() <= c.maxOverlapBytes {
     366           1 :                 // This compaction can be converted into a move or copy from one level
     367           1 :                 // to the next. We avoid such a move if there is lots of overlapping
     368           1 :                 // grandparent data. Otherwise, the move could create a parent file
     369           1 :                 // that will require a very expensive merge later on.
     370           1 :                 iter := c.startLevel.files.Iter()
     371           1 :                 meta := iter.First()
     372           1 :                 isRemote := false
     373           1 :                 // We should always be passed a provider, except in some unit tests.
     374           1 :                 if provider != nil {
     375           1 :                         isRemote = !objstorage.IsLocalTable(provider, meta.FileBacking.DiskFileNum)
     376           1 :                 }
     377             :                 // Avoid a trivial move or copy if all of these are true, as rewriting a
     378             :                 // new file is better:
     379             :                 //
     380             :                 // 1) The source file is a virtual sstable
     381             :                 // 2) The existing file `meta` is on non-remote storage
     382             :                 // 3) The output level prefers shared storage
     383           1 :                 mustCopy := !isRemote && remote.ShouldCreateShared(opts.Experimental.CreateOnShared, c.outputLevel.level)
     384           1 :                 if mustCopy {
     385           1 :                         // If the source is virtual, it's best to just rewrite the file as all
     386           1 :                         // conditions in the above comment are met.
     387           1 :                         if !meta.Virtual {
     388           1 :                                 c.kind = compactionKindCopy
     389           1 :                         }
     390           1 :                 } else {
     391           1 :                         c.kind = compactionKindMove
     392           1 :                 }
     393             :         }
     394           1 :         return c
     395             : }
     396             : 
     397             : func newDeleteOnlyCompaction(
     398             :         opts *Options, cur *version, inputs []compactionLevel, beganAt time.Time,
     399           1 : ) *compaction {
     400           1 :         c := &compaction{
     401           1 :                 kind:      compactionKindDeleteOnly,
     402           1 :                 cmp:       opts.Comparer.Compare,
     403           1 :                 equal:     opts.Comparer.Equal,
     404           1 :                 comparer:  opts.Comparer,
     405           1 :                 formatKey: opts.Comparer.FormatKey,
     406           1 :                 logger:    opts.Logger,
     407           1 :                 version:   cur,
     408           1 :                 beganAt:   beganAt,
     409           1 :                 inputs:    inputs,
     410           1 :         }
     411           1 : 
     412           1 :         // Set c.smallest, c.largest.
     413           1 :         files := make([]manifest.LevelIterator, 0, len(inputs))
     414           1 :         for _, in := range inputs {
     415           1 :                 files = append(files, in.files.Iter())
     416           1 :         }
     417           1 :         c.smallest, c.largest = manifest.KeyRange(opts.Comparer.Compare, files...)
     418           1 :         return c
     419             : }
     420             : 
     421           1 : func adjustGrandparentOverlapBytesForFlush(c *compaction, flushingBytes uint64) {
     422           1 :         // Heuristic to place a lower bound on compaction output file size
     423           1 :         // caused by Lbase. Prior to this heuristic we have observed an L0 in
     424           1 :         // production with 310K files of which 290K files were < 10KB in size.
     425           1 :         // Our hypothesis is that it was caused by L1 having 2600 files and
     426           1 :         // ~10GB, such that each flush got split into many tiny files due to
     427           1 :         // overlapping with most of the files in Lbase.
     428           1 :         //
     429           1 :         // The computation below is general in that it accounts
     430           1 :         // for flushing different volumes of data (e.g. we may be flushing
     431           1 :         // many memtables). For illustration, we consider the typical
     432           1 :         // example of flushing a 64MB memtable. So 12.8MB output,
     433           1 :         // based on the compression guess below. If the compressed bytes
     434           1 :         // guess is an over-estimate we will end up with smaller files,
     435           1 :         // and if an under-estimate we will end up with larger files.
     436           1 :         // With a 2MB target file size, 7 files. We are willing to accept
     437           1 :         // 4x the number of files, if it results in better write amplification
     438           1 :         // when later compacting to Lbase, i.e., ~450KB files (target file
     439           1 :         // size / 4).
     440           1 :         //
     441           1 :         // Note that this is a pessimistic heuristic in that
     442           1 :         // fileCountUpperBoundDueToGrandparents could be far from the actual
     443           1 :         // number of files produced due to the grandparent limits. For
     444           1 :         // example, in the extreme, consider a flush that overlaps with 1000
     445           1 :         // files in Lbase f0...f999, and the initially calculated value of
     446           1 :         // maxOverlapBytes will cause splits at f10, f20,..., f990, which
     447           1 :         // means an upper bound file count of 100 files. Say the input bytes
     448           1 :         // in the flush are such that acceptableFileCount=10. We will fatten
     449           1 :         // up maxOverlapBytes by 10x to ensure that the upper bound file count
     450           1 :         // drops to 10. However, it is possible that in practice, even without
     451           1 :         // this change, we would have produced no more than 10 files, and that
     452           1 :         // this change makes the files unnecessarily wide. Say the input bytes
     453           1 :         // are distributed such that 10% are in f0...f9, 10% in f10...f19, ...
     454           1 :         // 10% in f80...f89 and 10% in f990...f999. The original value of
     455           1 :         // maxOverlapBytes would have actually produced only 10 sstables. But
     456           1 :         // by increasing maxOverlapBytes by 10x, we may produce 1 sstable that
     457           1 :         // spans f0...f89, i.e., a much wider sstable than necessary.
     458           1 :         //
     459           1 :         // We could produce a tighter estimate of
     460           1 :         // fileCountUpperBoundDueToGrandparents if we had knowledge of the key
     461           1 :         // distribution of the flush. The 4x multiplier mentioned earlier is
     462           1 :         // a way to try to compensate for this pessimism.
     463           1 :         //
     464           1 :         // TODO(sumeer): we don't have compression info for the data being
     465           1 :         // flushed, but it is likely that existing files that overlap with
     466           1 :         // this flush in Lbase are representative wrt compression ratio. We
     467           1 :         // could store the uncompressed size in FileMetadata and estimate
     468           1 :         // the compression ratio.
     469           1 :         const approxCompressionRatio = 0.2
     470           1 :         approxOutputBytes := approxCompressionRatio * float64(flushingBytes)
     471           1 :         approxNumFilesBasedOnTargetSize :=
     472           1 :                 int(math.Ceil(approxOutputBytes / float64(c.maxOutputFileSize)))
     473           1 :         acceptableFileCount := float64(4 * approxNumFilesBasedOnTargetSize)
     474           1 :         // The byte calculation is linear in numGrandparentFiles, but we will
     475           1 :         // incur this linear cost in findGrandparentLimit too, so we are also
     476           1 :         // willing to pay it now. We could approximate this cheaply by using
     477           1 :         // the mean file size of Lbase.
     478           1 :         grandparentFileBytes := c.grandparents.SizeSum()
     479           1 :         fileCountUpperBoundDueToGrandparents :=
     480           1 :                 float64(grandparentFileBytes) / float64(c.maxOverlapBytes)
     481           1 :         if fileCountUpperBoundDueToGrandparents > acceptableFileCount {
     482           1 :                 c.maxOverlapBytes = uint64(
     483           1 :                         float64(c.maxOverlapBytes) *
     484           1 :                                 (fileCountUpperBoundDueToGrandparents / acceptableFileCount))
     485           1 :         }
     486             : }
     487             : 
     488             : func newFlush(
     489             :         opts *Options, cur *version, baseLevel int, flushing flushableList, beganAt time.Time,
     490           1 : ) (*compaction, error) {
     491           1 :         c := &compaction{
     492           1 :                 kind:              compactionKindFlush,
     493           1 :                 cmp:               opts.Comparer.Compare,
     494           1 :                 equal:             opts.Comparer.Equal,
     495           1 :                 comparer:          opts.Comparer,
     496           1 :                 formatKey:         opts.Comparer.FormatKey,
     497           1 :                 logger:            opts.Logger,
     498           1 :                 version:           cur,
     499           1 :                 beganAt:           beganAt,
     500           1 :                 inputs:            []compactionLevel{{level: -1}, {level: 0}},
     501           1 :                 maxOutputFileSize: math.MaxUint64,
     502           1 :                 maxOverlapBytes:   math.MaxUint64,
     503           1 :                 flushing:          flushing,
     504           1 :         }
     505           1 :         c.startLevel = &c.inputs[0]
     506           1 :         c.outputLevel = &c.inputs[1]
     507           1 : 
     508           1 :         if len(flushing) > 0 {
     509           1 :                 if _, ok := flushing[0].flushable.(*ingestedFlushable); ok {
     510           1 :                         if len(flushing) != 1 {
     511           0 :                                 panic("pebble: ingestedFlushable must be flushed one at a time.")
     512             :                         }
     513           1 :                         c.kind = compactionKindIngestedFlushable
     514           1 :                         return c, nil
     515             :                 }
     516             :         }
     517             : 
     518             :         // Make sure there's no ingestedFlushable after the first flushable in the
     519             :         // list.
     520           1 :         for _, f := range flushing {
     521           1 :                 if _, ok := f.flushable.(*ingestedFlushable); ok {
     522           0 :                         panic("pebble: flushing shouldn't contain ingestedFlushable flushable")
     523             :                 }
     524             :         }
     525             : 
     526           1 :         if cur.L0Sublevels != nil {
     527           1 :                 c.l0Limits = cur.L0Sublevels.FlushSplitKeys()
     528           1 :         }
     529             : 
     530           1 :         smallestSet, largestSet := false, false
     531           1 :         updatePointBounds := func(iter internalIterator) {
     532           1 :                 if kv := iter.First(); kv != nil {
     533           1 :                         if !smallestSet ||
     534           1 :                                 base.InternalCompare(c.cmp, c.smallest, kv.K) > 0 {
     535           1 :                                 smallestSet = true
     536           1 :                                 c.smallest = kv.K.Clone()
     537           1 :                         }
     538             :                 }
     539           1 :                 if kv := iter.Last(); kv != nil {
     540           1 :                         if !largestSet ||
     541           1 :                                 base.InternalCompare(c.cmp, c.largest, kv.K) < 0 {
     542           1 :                                 largestSet = true
     543           1 :                                 c.largest = kv.K.Clone()
     544           1 :                         }
     545             :                 }
     546             :         }
     547             : 
     548           1 :         updateRangeBounds := func(iter keyspan.FragmentIterator) error {
     549           1 :                 // File bounds require s != nil && !s.Empty(). We only need to check for
     550           1 :                 // s != nil here, as the memtable's FragmentIterator would never surface
     551           1 :                 // empty spans.
     552           1 :                 if s, err := iter.First(); err != nil {
     553           0 :                         return err
     554           1 :                 } else if s != nil {
     555           1 :                         if key := s.SmallestKey(); !smallestSet ||
     556           1 :                                 base.InternalCompare(c.cmp, c.smallest, key) > 0 {
     557           1 :                                 smallestSet = true
     558           1 :                                 c.smallest = key.Clone()
     559           1 :                         }
     560             :                 }
     561           1 :                 if s, err := iter.Last(); err != nil {
     562           0 :                         return err
     563           1 :                 } else if s != nil {
     564           1 :                         if key := s.LargestKey(); !largestSet ||
     565           1 :                                 base.InternalCompare(c.cmp, c.largest, key) < 0 {
     566           1 :                                 largestSet = true
     567           1 :                                 c.largest = key.Clone()
     568           1 :                         }
     569             :                 }
     570           1 :                 return nil
     571             :         }
     572             : 
     573           1 :         var flushingBytes uint64
     574           1 :         for i := range flushing {
     575           1 :                 f := flushing[i]
     576           1 :                 updatePointBounds(f.newIter(nil))
     577           1 :                 if rangeDelIter := f.newRangeDelIter(nil); rangeDelIter != nil {
     578           1 :                         if err := updateRangeBounds(rangeDelIter); err != nil {
     579           0 :                                 return nil, err
     580           0 :                         }
     581             :                 }
     582           1 :                 if rangeKeyIter := f.newRangeKeyIter(nil); rangeKeyIter != nil {
     583           1 :                         if err := updateRangeBounds(rangeKeyIter); err != nil {
     584           0 :                                 return nil, err
     585           0 :                         }
     586             :                 }
     587           1 :                 flushingBytes += f.inuseBytes()
     588             :         }
     589             : 
     590           1 :         if opts.FlushSplitBytes > 0 {
     591           1 :                 c.maxOutputFileSize = uint64(opts.Level(0).TargetFileSize)
     592           1 :                 c.maxOverlapBytes = maxGrandparentOverlapBytes(opts, 0)
     593           1 :                 c.grandparents = c.version.Overlaps(baseLevel, c.userKeyBounds())
     594           1 :                 adjustGrandparentOverlapBytesForFlush(c, flushingBytes)
     595           1 :         }
     596             : 
     597             :         // We don't elide tombstones for flushes.
     598           1 :         c.delElision, c.rangeKeyElision = compact.NoTombstoneElision(), compact.NoTombstoneElision()
     599           1 :         return c, nil
     600             : }
     601             : 
     602           1 : func (c *compaction) hasExtraLevelData() bool {
     603           1 :         if len(c.extraLevels) == 0 {
     604           1 :                 // not a multi level compaction
     605           1 :                 return false
     606           1 :         } else if c.extraLevels[0].files.Empty() {
     607           1 :                 // a multi level compaction without data in the intermediate input level;
     608           1 :                 // e.g. for a multi level compaction with levels 4,5, and 6, this could
     609           1 :                 // occur if there is no files to compact in 5, or in 5 and 6 (i.e. a move).
     610           1 :                 return false
     611           1 :         }
     612           1 :         return true
     613             : }
     614             : 
     615             : // findGrandparentLimit takes the start user key for a table and returns the
     616             : // user key to which that table can extend without excessively overlapping
     617             : // the grandparent level. If no limit is needed considering the grandparent
     618             : // files, this function returns nil. This is done in order to prevent a table
     619             : // at level N from overlapping too much data at level N+1. We want to avoid
     620             : // such large overlaps because they translate into large compactions. The
     621             : // current heuristic stops output of a table if the addition of another key
     622             : // would cause the table to overlap more than 10x the target file size at
     623             : // level N. See maxGrandparentOverlapBytes.
     624           1 : func (c *compaction) findGrandparentLimit(start []byte) []byte {
     625           1 :         iter := c.grandparents.Iter()
     626           1 :         var overlappedBytes uint64
     627           1 :         var greater bool
     628           1 :         for f := iter.SeekGE(c.cmp, start); f != nil; f = iter.Next() {
     629           1 :                 overlappedBytes += f.Size
     630           1 :                 // To ensure forward progress we always return a larger user
     631           1 :                 // key than where we started. See comments above clients of
     632           1 :                 // this function for how this is used.
     633           1 :                 greater = greater || c.cmp(f.Smallest.UserKey, start) > 0
     634           1 :                 if !greater {
     635           1 :                         continue
     636             :                 }
     637             : 
     638             :                 // We return the smallest bound of a sstable rather than the
     639             :                 // largest because the smallest is always inclusive, and limits
     640             :                 // are used exlusively when truncating range tombstones. If we
     641             :                 // truncated an output to the largest key while there's a
     642             :                 // pending tombstone, the next output file would also overlap
     643             :                 // the same grandparent f.
     644           1 :                 if overlappedBytes > c.maxOverlapBytes {
     645           1 :                         return f.Smallest.UserKey
     646           1 :                 }
     647             :         }
     648           1 :         return nil
     649             : }
     650             : 
     651             : // findL0Limit takes the start key for a table and returns the user key to which
     652             : // that table can be extended without hitting the next l0Limit. Having flushed
     653             : // sstables "bridging across" an l0Limit could lead to increased L0 -> LBase
     654             : // compaction sizes as well as elevated read amplification.
     655           1 : func (c *compaction) findL0Limit(start []byte) []byte {
     656           1 :         if c.startLevel.level > -1 || c.outputLevel.level != 0 || len(c.l0Limits) == 0 {
     657           1 :                 return nil
     658           1 :         }
     659           1 :         index := sort.Search(len(c.l0Limits), func(i int) bool {
     660           1 :                 return c.cmp(c.l0Limits[i], start) > 0
     661           1 :         })
     662           1 :         if index < len(c.l0Limits) {
     663           1 :                 return c.l0Limits[index]
     664           1 :         }
     665           1 :         return nil
     666             : }
     667             : 
     668             : // errorOnUserKeyOverlap returns an error if the last two written sstables in
     669             : // this compaction have revisions of the same user key present in both sstables,
     670             : // when it shouldn't (eg. when splitting flushes).
     671           1 : func (c *compaction) errorOnUserKeyOverlap(ve *versionEdit) error {
     672           1 :         if n := len(ve.NewFiles); n > 1 {
     673           1 :                 meta := ve.NewFiles[n-1].Meta
     674           1 :                 prevMeta := ve.NewFiles[n-2].Meta
     675           1 :                 if !prevMeta.Largest.IsExclusiveSentinel() &&
     676           1 :                         c.cmp(prevMeta.Largest.UserKey, meta.Smallest.UserKey) >= 0 {
     677           1 :                         return errors.Errorf("pebble: compaction split user key across two sstables: %s in %s and %s",
     678           1 :                                 prevMeta.Largest.Pretty(c.formatKey),
     679           1 :                                 prevMeta.FileNum,
     680           1 :                                 meta.FileNum)
     681           1 :                 }
     682             :         }
     683           1 :         return nil
     684             : }
     685             : 
     686             : // allowZeroSeqNum returns true if seqnum's can be zeroed if there are no
     687             : // snapshots requiring them to be kept. It performs this determination by
     688             : // looking at the TombstoneElision values which are set up based on sstables
     689             : // which overlap the bounds of the compaction at a lower level in the LSM.
     690           1 : func (c *compaction) allowZeroSeqNum() bool {
     691           1 :         // TODO(peter): we disable zeroing of seqnums during flushing to match
     692           1 :         // RocksDB behavior and to avoid generating overlapping sstables during
     693           1 :         // DB.replayWAL. When replaying WAL files at startup, we flush after each
     694           1 :         // WAL is replayed building up a single version edit that is
     695           1 :         // applied. Because we don't apply the version edit after each flush, this
     696           1 :         // code doesn't know that L0 contains files and zeroing of seqnums should
     697           1 :         // be disabled. That is fixable, but it seems safer to just match the
     698           1 :         // RocksDB behavior for now.
     699           1 :         return len(c.flushing) == 0 && c.delElision.ElidesEverything() && c.rangeKeyElision.ElidesEverything()
     700           1 : }
     701             : 
     702             : // newInputIter returns an iterator over all the input tables in a compaction.
     703             : func (c *compaction) newInputIter(
     704             :         newIters tableNewIters, newRangeKeyIter keyspanimpl.TableNewSpanIter,
     705           1 : ) (_ internalIterator, retErr error) {
     706           1 :         // Validate the ordering of compaction input files for defense in depth.
     707           1 :         if len(c.flushing) == 0 {
     708           1 :                 if c.startLevel.level >= 0 {
     709           1 :                         err := manifest.CheckOrdering(c.cmp, c.formatKey,
     710           1 :                                 manifest.Level(c.startLevel.level), c.startLevel.files.Iter())
     711           1 :                         if err != nil {
     712           1 :                                 return nil, err
     713           1 :                         }
     714             :                 }
     715           1 :                 err := manifest.CheckOrdering(c.cmp, c.formatKey,
     716           1 :                         manifest.Level(c.outputLevel.level), c.outputLevel.files.Iter())
     717           1 :                 if err != nil {
     718           1 :                         return nil, err
     719           1 :                 }
     720           1 :                 if c.startLevel.level == 0 {
     721           1 :                         if c.startLevel.l0SublevelInfo == nil {
     722           0 :                                 panic("l0SublevelInfo not created for compaction out of L0")
     723             :                         }
     724           1 :                         for _, info := range c.startLevel.l0SublevelInfo {
     725           1 :                                 err := manifest.CheckOrdering(c.cmp, c.formatKey,
     726           1 :                                         info.sublevel, info.Iter())
     727           1 :                                 if err != nil {
     728           1 :                                         return nil, err
     729           1 :                                 }
     730             :                         }
     731             :                 }
     732           1 :                 if len(c.extraLevels) > 0 {
     733           1 :                         if len(c.extraLevels) > 1 {
     734           0 :                                 panic("n>2 multi level compaction not implemented yet")
     735             :                         }
     736           1 :                         interLevel := c.extraLevels[0]
     737           1 :                         err := manifest.CheckOrdering(c.cmp, c.formatKey,
     738           1 :                                 manifest.Level(interLevel.level), interLevel.files.Iter())
     739           1 :                         if err != nil {
     740           0 :                                 return nil, err
     741           0 :                         }
     742             :                 }
     743             :         }
     744             : 
     745             :         // There are three classes of keys that a compaction needs to process: point
     746             :         // keys, range deletion tombstones and range keys. Collect all iterators for
     747             :         // all these classes of keys from all the levels. We'll aggregate them
     748             :         // together farther below.
     749             :         //
     750             :         // numInputLevels is an approximation of the number of iterator levels. Due
     751             :         // to idiosyncrasies in iterator construction, we may (rarely) exceed this
     752             :         // initial capacity.
     753           1 :         numInputLevels := max(len(c.flushing), len(c.inputs))
     754           1 :         iters := make([]internalIterator, 0, numInputLevels)
     755           1 :         rangeDelIters := make([]keyspan.FragmentIterator, 0, numInputLevels)
     756           1 :         rangeKeyIters := make([]keyspan.FragmentIterator, 0, numInputLevels)
     757           1 : 
     758           1 :         // If construction of the iterator inputs fails, ensure that we close all
     759           1 :         // the consitutent iterators.
     760           1 :         defer func() {
     761           1 :                 if retErr != nil {
     762           0 :                         for _, iter := range iters {
     763           0 :                                 if iter != nil {
     764           0 :                                         iter.Close()
     765           0 :                                 }
     766             :                         }
     767           0 :                         for _, rangeDelIter := range rangeDelIters {
     768           0 :                                 rangeDelIter.Close()
     769           0 :                         }
     770             :                 }
     771             :         }()
     772           1 :         iterOpts := IterOptions{
     773           1 :                 CategoryAndQoS: sstable.CategoryAndQoS{
     774           1 :                         Category: "pebble-compaction",
     775           1 :                         QoSLevel: sstable.NonLatencySensitiveQoSLevel,
     776           1 :                 },
     777           1 :                 logger: c.logger,
     778           1 :         }
     779           1 : 
     780           1 :         // Populate iters, rangeDelIters and rangeKeyIters with the appropriate
     781           1 :         // constituent iterators. This depends on whether this is a flush or a
     782           1 :         // compaction.
     783           1 :         if len(c.flushing) != 0 {
     784           1 :                 // If flushing, we need to build the input iterators over the memtables
     785           1 :                 // stored in c.flushing.
     786           1 :                 for i := range c.flushing {
     787           1 :                         f := c.flushing[i]
     788           1 :                         iters = append(iters, f.newFlushIter(nil))
     789           1 :                         rangeDelIter := f.newRangeDelIter(nil)
     790           1 :                         if rangeDelIter != nil {
     791           1 :                                 rangeDelIters = append(rangeDelIters, rangeDelIter)
     792           1 :                         }
     793           1 :                         if rangeKeyIter := f.newRangeKeyIter(nil); rangeKeyIter != nil {
     794           1 :                                 rangeKeyIters = append(rangeKeyIters, rangeKeyIter)
     795           1 :                         }
     796             :                 }
     797           1 :         } else {
     798           1 :                 addItersForLevel := func(level *compactionLevel, l manifest.Level) error {
     799           1 :                         // Add a *levelIter for point iterators. Because we don't call
     800           1 :                         // initRangeDel, the levelIter will close and forget the range
     801           1 :                         // deletion iterator when it steps on to a new file. Surfacing range
     802           1 :                         // deletions to compactions are handled below.
     803           1 :                         iters = append(iters, newLevelIter(context.Background(),
     804           1 :                                 iterOpts, c.comparer, newIters, level.files.Iter(), l, internalIterOpts{
     805           1 :                                         compaction: true,
     806           1 :                                         bufferPool: &c.bufferPool,
     807           1 :                                 }))
     808           1 :                         // TODO(jackson): Use keyspanimpl.LevelIter to avoid loading all the range
     809           1 :                         // deletions into memory upfront. (See #2015, which reverted this.) There
     810           1 :                         // will be no user keys that are split between sstables within a level in
     811           1 :                         // Cockroach 23.1, which unblocks this optimization.
     812           1 : 
     813           1 :                         // Add the range deletion iterator for each file as an independent level
     814           1 :                         // in mergingIter, as opposed to making a levelIter out of those. This
     815           1 :                         // is safer as levelIter expects all keys coming from underlying
     816           1 :                         // iterators to be in order. Due to compaction / tombstone writing
     817           1 :                         // logic in finishOutput(), it is possible for range tombstones to not
     818           1 :                         // be strictly ordered across all files in one level.
     819           1 :                         //
     820           1 :                         // Consider this example from the metamorphic tests (also repeated in
     821           1 :                         // finishOutput()), consisting of three L3 files with their bounds
     822           1 :                         // specified in square brackets next to the file name:
     823           1 :                         //
     824           1 :                         // ./000240.sst   [tmgc#391,MERGE-tmgc#391,MERGE]
     825           1 :                         // tmgc#391,MERGE [786e627a]
     826           1 :                         // tmgc-udkatvs#331,RANGEDEL
     827           1 :                         //
     828           1 :                         // ./000241.sst   [tmgc#384,MERGE-tmgc#384,MERGE]
     829           1 :                         // tmgc#384,MERGE [666c7070]
     830           1 :                         // tmgc-tvsalezade#383,RANGEDEL
     831           1 :                         // tmgc-tvsalezade#331,RANGEDEL
     832           1 :                         //
     833           1 :                         // ./000242.sst   [tmgc#383,RANGEDEL-tvsalezade#72057594037927935,RANGEDEL]
     834           1 :                         // tmgc-tvsalezade#383,RANGEDEL
     835           1 :                         // tmgc#375,SET [72646c78766965616c72776865676e79]
     836           1 :                         // tmgc-tvsalezade#356,RANGEDEL
     837           1 :                         //
     838           1 :                         // Here, the range tombstone in 000240.sst falls "after" one in
     839           1 :                         // 000241.sst, despite 000240.sst being ordered "before" 000241.sst for
     840           1 :                         // levelIter's purposes. While each file is still consistent before its
     841           1 :                         // bounds, it's safer to have all rangedel iterators be visible to
     842           1 :                         // mergingIter.
     843           1 :                         iter := level.files.Iter()
     844           1 :                         for f := iter.First(); f != nil; f = iter.Next() {
     845           1 :                                 rangeDelIter, closer, err := c.newRangeDelIter(
     846           1 :                                         newIters, iter.Take(), iterOpts, l)
     847           1 :                                 if err != nil {
     848           0 :                                         // The error will already be annotated with the BackingFileNum, so
     849           0 :                                         // we annotate it with the FileNum.
     850           0 :                                         return errors.Wrapf(err, "pebble: could not open table %s", errors.Safe(f.FileNum))
     851           0 :                                 }
     852           1 :                                 if rangeDelIter == nil {
     853           1 :                                         continue
     854             :                                 }
     855           1 :                                 rangeDelIters = append(rangeDelIters, rangeDelIter)
     856           1 :                                 c.closers = append(c.closers, closer)
     857             :                         }
     858             : 
     859             :                         // Check if this level has any range keys.
     860           1 :                         hasRangeKeys := false
     861           1 :                         for f := iter.First(); f != nil; f = iter.Next() {
     862           1 :                                 if f.HasRangeKeys {
     863           1 :                                         hasRangeKeys = true
     864           1 :                                         break
     865             :                                 }
     866             :                         }
     867           1 :                         if hasRangeKeys {
     868           1 :                                 li := &keyspanimpl.LevelIter{}
     869           1 :                                 newRangeKeyIterWrapper := func(file *manifest.FileMetadata, iterOptions keyspan.SpanIterOptions) (keyspan.FragmentIterator, error) {
     870           1 :                                         iter, err := newRangeKeyIter(file, iterOptions)
     871           1 :                                         if err != nil {
     872           0 :                                                 return nil, err
     873           1 :                                         } else if iter == nil {
     874           0 :                                                 return emptyKeyspanIter, nil
     875           0 :                                         }
     876             :                                         // Ensure that the range key iter is not closed until the compaction is
     877             :                                         // finished. This is necessary because range key processing
     878             :                                         // requires the range keys to be held in memory for up to the
     879             :                                         // lifetime of the compaction.
     880           1 :                                         c.closers = append(c.closers, iter)
     881           1 :                                         iter = noCloseIter{iter}
     882           1 : 
     883           1 :                                         // We do not need to truncate range keys to sstable boundaries, or
     884           1 :                                         // only read within the file's atomic compaction units, unlike with
     885           1 :                                         // range tombstones. This is because range keys were added after we
     886           1 :                                         // stopped splitting user keys across sstables, so all the range keys
     887           1 :                                         // in this sstable must wholly lie within the file's bounds.
     888           1 :                                         return iter, err
     889             :                                 }
     890           1 :                                 li.Init(keyspan.SpanIterOptions{}, c.cmp, newRangeKeyIterWrapper, level.files.Iter(), l, manifest.KeyTypeRange)
     891           1 :                                 rangeKeyIters = append(rangeKeyIters, li)
     892             :                         }
     893           1 :                         return nil
     894             :                 }
     895             : 
     896           1 :                 for i := range c.inputs {
     897           1 :                         // If the level is annotated with l0SublevelInfo, expand it into one
     898           1 :                         // level per sublevel.
     899           1 :                         // TODO(jackson): Perform this expansion even earlier when we pick the
     900           1 :                         // compaction?
     901           1 :                         if len(c.inputs[i].l0SublevelInfo) > 0 {
     902           1 :                                 for _, info := range c.startLevel.l0SublevelInfo {
     903           1 :                                         sublevelCompactionLevel := &compactionLevel{0, info.LevelSlice, nil}
     904           1 :                                         if err := addItersForLevel(sublevelCompactionLevel, info.sublevel); err != nil {
     905           0 :                                                 return nil, err
     906           0 :                                         }
     907             :                                 }
     908           1 :                                 continue
     909             :                         }
     910           1 :                         if err := addItersForLevel(&c.inputs[i], manifest.Level(c.inputs[i].level)); err != nil {
     911           0 :                                 return nil, err
     912           0 :                         }
     913             :                 }
     914             :         }
     915             : 
     916             :         // If there's only one constituent point iterator, we can avoid the overhead
     917             :         // of a *mergingIter. This is possible, for example, when performing a flush
     918             :         // of a single memtable. Otherwise, combine all the iterators into a merging
     919             :         // iter.
     920           1 :         iter := iters[0]
     921           1 :         if len(iters) > 1 {
     922           1 :                 iter = newMergingIter(c.logger, &c.stats, c.cmp, nil, iters...)
     923           1 :         }
     924             : 
     925             :         // In normal operation, levelIter iterates over the point operations in a
     926             :         // level, and initializes a rangeDelIter pointer for the range deletions in
     927             :         // each table. During compaction, we want to iterate over the merged view of
     928             :         // point operations and range deletions. In order to do this we create one
     929             :         // levelIter per level to iterate over the point operations, and collect up
     930             :         // all the range deletion files.
     931             :         //
     932             :         // The range deletion levels are combined with a keyspanimpl.MergingIter. The
     933             :         // resulting merged rangedel iterator is then included using an
     934             :         // InterleavingIter.
     935             :         // TODO(jackson): Consider using a defragmenting iterator to stitch together
     936             :         // logical range deletions that were fragmented due to previous file
     937             :         // boundaries.
     938           1 :         if len(rangeDelIters) > 0 {
     939           1 :                 mi := &keyspanimpl.MergingIter{}
     940           1 :                 mi.Init(c.cmp, keyspan.NoopTransform, new(keyspanimpl.MergingBuffers), rangeDelIters...)
     941           1 :                 c.rangeDelInterleaving.Init(c.comparer, iter, mi, keyspan.InterleavingIterOpts{})
     942           1 :                 iter = &c.rangeDelInterleaving
     943           1 :         }
     944             : 
     945             :         // If there are range key iterators, we need to combine them using
     946             :         // keyspanimpl.MergingIter, and then interleave them among the points.
     947           1 :         if len(rangeKeyIters) > 0 {
     948           1 :                 mi := &keyspanimpl.MergingIter{}
     949           1 :                 mi.Init(c.cmp, keyspan.NoopTransform, new(keyspanimpl.MergingBuffers), rangeKeyIters...)
     950           1 :                 di := &keyspan.DefragmentingIter{}
     951           1 :                 di.Init(c.comparer, mi, keyspan.DefragmentInternal, keyspan.StaticDefragmentReducer, new(keyspan.DefragmentingBuffers))
     952           1 :                 c.rangeKeyInterleaving.Init(c.comparer, iter, di, keyspan.InterleavingIterOpts{})
     953           1 :                 iter = &c.rangeKeyInterleaving
     954           1 :         }
     955           1 :         return iter, nil
     956             : }
     957             : 
     958             : func (c *compaction) newRangeDelIter(
     959             :         newIters tableNewIters, f manifest.LevelFile, opts IterOptions, l manifest.Level,
     960           1 : ) (keyspan.FragmentIterator, io.Closer, error) {
     961           1 :         opts.level = l
     962           1 :         iterSet, err := newIters(context.Background(), f.FileMetadata, &opts,
     963           1 :                 internalIterOpts{
     964           1 :                         compaction: true,
     965           1 :                         bufferPool: &c.bufferPool,
     966           1 :                 }, iterRangeDeletions)
     967           1 :         if err != nil {
     968           0 :                 return nil, nil, err
     969           1 :         } else if iterSet.rangeDeletion == nil {
     970           1 :                 // The file doesn't contain any range deletions.
     971           1 :                 return nil, nil, nil
     972           1 :         }
     973             :         // Ensure that rangeDelIter is not closed until the compaction is
     974             :         // finished. This is necessary because range tombstone processing
     975             :         // requires the range tombstones to be held in memory for up to the
     976             :         // lifetime of the compaction.
     977           1 :         return noCloseIter{iterSet.rangeDeletion}, iterSet.rangeDeletion, nil
     978             : }
     979             : 
     980           1 : func (c *compaction) String() string {
     981           1 :         if len(c.flushing) != 0 {
     982           0 :                 return "flush\n"
     983           0 :         }
     984             : 
     985           1 :         var buf bytes.Buffer
     986           1 :         for level := c.startLevel.level; level <= c.outputLevel.level; level++ {
     987           1 :                 i := level - c.startLevel.level
     988           1 :                 fmt.Fprintf(&buf, "%d:", level)
     989           1 :                 iter := c.inputs[i].files.Iter()
     990           1 :                 for f := iter.First(); f != nil; f = iter.Next() {
     991           1 :                         fmt.Fprintf(&buf, " %s:%s-%s", f.FileNum, f.Smallest, f.Largest)
     992           1 :                 }
     993           1 :                 fmt.Fprintf(&buf, "\n")
     994             :         }
     995           1 :         return buf.String()
     996             : }
     997             : 
     998             : type manualCompaction struct {
     999             :         // Count of the retries either due to too many concurrent compactions, or a
    1000             :         // concurrent compaction to overlapping levels.
    1001             :         retries     int
    1002             :         level       int
    1003             :         outputLevel int
    1004             :         done        chan error
    1005             :         start       []byte
    1006             :         end         []byte
    1007             :         split       bool
    1008             : }
    1009             : 
    1010             : type readCompaction struct {
    1011             :         level int
    1012             :         // [start, end] key ranges are used for de-duping.
    1013             :         start []byte
    1014             :         end   []byte
    1015             : 
    1016             :         // The file associated with the compaction.
    1017             :         // If the file no longer belongs in the same
    1018             :         // level, then we skip the compaction.
    1019             :         fileNum base.FileNum
    1020             : }
    1021             : 
    1022           1 : func (d *DB) addInProgressCompaction(c *compaction) {
    1023           1 :         d.mu.compact.inProgress[c] = struct{}{}
    1024           1 :         var isBase, isIntraL0 bool
    1025           1 :         for _, cl := range c.inputs {
    1026           1 :                 iter := cl.files.Iter()
    1027           1 :                 for f := iter.First(); f != nil; f = iter.Next() {
    1028           1 :                         if f.IsCompacting() {
    1029           0 :                                 d.opts.Logger.Fatalf("L%d->L%d: %s already being compacted", c.startLevel.level, c.outputLevel.level, f.FileNum)
    1030           0 :                         }
    1031           1 :                         f.SetCompactionState(manifest.CompactionStateCompacting)
    1032           1 :                         if c.startLevel != nil && c.outputLevel != nil && c.startLevel.level == 0 {
    1033           1 :                                 if c.outputLevel.level == 0 {
    1034           1 :                                         f.IsIntraL0Compacting = true
    1035           1 :                                         isIntraL0 = true
    1036           1 :                                 } else {
    1037           1 :                                         isBase = true
    1038           1 :                                 }
    1039             :                         }
    1040             :                 }
    1041             :         }
    1042             : 
    1043           1 :         if (isIntraL0 || isBase) && c.version.L0Sublevels != nil {
    1044           1 :                 l0Inputs := []manifest.LevelSlice{c.startLevel.files}
    1045           1 :                 if isIntraL0 {
    1046           1 :                         l0Inputs = append(l0Inputs, c.outputLevel.files)
    1047           1 :                 }
    1048           1 :                 if err := c.version.L0Sublevels.UpdateStateForStartedCompaction(l0Inputs, isBase); err != nil {
    1049           0 :                         d.opts.Logger.Fatalf("could not update state for compaction: %s", err)
    1050           0 :                 }
    1051             :         }
    1052             : }
    1053             : 
    1054             : // Removes compaction markers from files in a compaction. The rollback parameter
    1055             : // indicates whether the compaction state should be rolled back to its original
    1056             : // state in the case of an unsuccessful compaction.
    1057             : //
    1058             : // DB.mu must be held when calling this method, however this method can drop and
    1059             : // re-acquire that mutex. All writes to the manifest for this compaction should
    1060             : // have completed by this point.
    1061           1 : func (d *DB) clearCompactingState(c *compaction, rollback bool) {
    1062           1 :         c.versionEditApplied = true
    1063           1 :         for _, cl := range c.inputs {
    1064           1 :                 iter := cl.files.Iter()
    1065           1 :                 for f := iter.First(); f != nil; f = iter.Next() {
    1066           1 :                         if !f.IsCompacting() {
    1067           0 :                                 d.opts.Logger.Fatalf("L%d->L%d: %s not being compacted", c.startLevel.level, c.outputLevel.level, f.FileNum)
    1068           0 :                         }
    1069           1 :                         if !rollback {
    1070           1 :                                 // On success all compactions other than move-compactions transition the
    1071           1 :                                 // file into the Compacted state. Move-compacted files become eligible
    1072           1 :                                 // for compaction again and transition back to NotCompacting.
    1073           1 :                                 if c.kind != compactionKindMove {
    1074           1 :                                         f.SetCompactionState(manifest.CompactionStateCompacted)
    1075           1 :                                 } else {
    1076           1 :                                         f.SetCompactionState(manifest.CompactionStateNotCompacting)
    1077           1 :                                 }
    1078           1 :                         } else {
    1079           1 :                                 // Else, on rollback, all input files unconditionally transition back to
    1080           1 :                                 // NotCompacting.
    1081           1 :                                 f.SetCompactionState(manifest.CompactionStateNotCompacting)
    1082           1 :                         }
    1083           1 :                         f.IsIntraL0Compacting = false
    1084             :                 }
    1085             :         }
    1086           1 :         l0InProgress := inProgressL0Compactions(d.getInProgressCompactionInfoLocked(c))
    1087           1 :         func() {
    1088           1 :                 // InitCompactingFileInfo requires that no other manifest writes be
    1089           1 :                 // happening in parallel with it, i.e. we're not in the midst of installing
    1090           1 :                 // another version. Otherwise, it's possible that we've created another
    1091           1 :                 // L0Sublevels instance, but not added it to the versions list, causing
    1092           1 :                 // all the indices in FileMetadata to be inaccurate. To ensure this,
    1093           1 :                 // grab the manifest lock.
    1094           1 :                 d.mu.versions.logLock()
    1095           1 :                 defer d.mu.versions.logUnlock()
    1096           1 :                 d.mu.versions.currentVersion().L0Sublevels.InitCompactingFileInfo(l0InProgress)
    1097           1 :         }()
    1098             : }
    1099             : 
    1100           1 : func (d *DB) calculateDiskAvailableBytes() uint64 {
    1101           1 :         if space, err := d.opts.FS.GetDiskUsage(d.dirname); err == nil {
    1102           1 :                 d.diskAvailBytes.Store(space.AvailBytes)
    1103           1 :                 return space.AvailBytes
    1104           1 :         } else if !errors.Is(err, vfs.ErrUnsupported) {
    1105           1 :                 d.opts.EventListener.BackgroundError(err)
    1106           1 :         }
    1107           1 :         return d.diskAvailBytes.Load()
    1108             : }
    1109             : 
    1110             : // maybeScheduleFlush schedules a flush if necessary.
    1111             : //
    1112             : // d.mu must be held when calling this.
    1113           1 : func (d *DB) maybeScheduleFlush() {
    1114           1 :         if d.mu.compact.flushing || d.closed.Load() != nil || d.opts.ReadOnly {
    1115           1 :                 return
    1116           1 :         }
    1117           1 :         if len(d.mu.mem.queue) <= 1 {
    1118           1 :                 return
    1119           1 :         }
    1120             : 
    1121           1 :         if !d.passedFlushThreshold() {
    1122           1 :                 return
    1123           1 :         }
    1124             : 
    1125           1 :         d.mu.compact.flushing = true
    1126           1 :         go d.flush()
    1127             : }
    1128             : 
    1129           1 : func (d *DB) passedFlushThreshold() bool {
    1130           1 :         var n int
    1131           1 :         var size uint64
    1132           1 :         for ; n < len(d.mu.mem.queue)-1; n++ {
    1133           1 :                 if !d.mu.mem.queue[n].readyForFlush() {
    1134           1 :                         break
    1135             :                 }
    1136           1 :                 if d.mu.mem.queue[n].flushForced {
    1137           1 :                         // A flush was forced. Pretend the memtable size is the configured
    1138           1 :                         // size. See minFlushSize below.
    1139           1 :                         size += d.opts.MemTableSize
    1140           1 :                 } else {
    1141           1 :                         size += d.mu.mem.queue[n].totalBytes()
    1142           1 :                 }
    1143             :         }
    1144           1 :         if n == 0 {
    1145           1 :                 // None of the immutable memtables are ready for flushing.
    1146           1 :                 return false
    1147           1 :         }
    1148             : 
    1149             :         // Only flush once the sum of the queued memtable sizes exceeds half the
    1150             :         // configured memtable size. This prevents flushing of memtables at startup
    1151             :         // while we're undergoing the ramp period on the memtable size. See
    1152             :         // DB.newMemTable().
    1153           1 :         minFlushSize := d.opts.MemTableSize / 2
    1154           1 :         return size >= minFlushSize
    1155             : }
    1156             : 
    1157           1 : func (d *DB) maybeScheduleDelayedFlush(tbl *memTable, dur time.Duration) {
    1158           1 :         var mem *flushableEntry
    1159           1 :         for _, m := range d.mu.mem.queue {
    1160           1 :                 if m.flushable == tbl {
    1161           1 :                         mem = m
    1162           1 :                         break
    1163             :                 }
    1164             :         }
    1165           1 :         if mem == nil || mem.flushForced {
    1166           1 :                 return
    1167           1 :         }
    1168           1 :         deadline := d.timeNow().Add(dur)
    1169           1 :         if !mem.delayedFlushForcedAt.IsZero() && deadline.After(mem.delayedFlushForcedAt) {
    1170           1 :                 // Already scheduled to flush sooner than within `dur`.
    1171           1 :                 return
    1172           1 :         }
    1173           1 :         mem.delayedFlushForcedAt = deadline
    1174           1 :         go func() {
    1175           1 :                 timer := time.NewTimer(dur)
    1176           1 :                 defer timer.Stop()
    1177           1 : 
    1178           1 :                 select {
    1179           1 :                 case <-d.closedCh:
    1180           1 :                         return
    1181           1 :                 case <-mem.flushed:
    1182           1 :                         return
    1183           1 :                 case <-timer.C:
    1184           1 :                         d.commit.mu.Lock()
    1185           1 :                         defer d.commit.mu.Unlock()
    1186           1 :                         d.mu.Lock()
    1187           1 :                         defer d.mu.Unlock()
    1188           1 : 
    1189           1 :                         // NB: The timer may fire concurrently with a call to Close.  If a
    1190           1 :                         // Close call beat us to acquiring d.mu, d.closed holds ErrClosed,
    1191           1 :                         // and it's too late to flush anything. Otherwise, the Close call
    1192           1 :                         // will block on locking d.mu until we've finished scheduling the
    1193           1 :                         // flush and set `d.mu.compact.flushing` to true. Close will wait
    1194           1 :                         // for the current flush to complete.
    1195           1 :                         if d.closed.Load() != nil {
    1196           1 :                                 return
    1197           1 :                         }
    1198             : 
    1199           1 :                         if d.mu.mem.mutable == tbl {
    1200           1 :                                 d.makeRoomForWrite(nil)
    1201           1 :                         } else {
    1202           1 :                                 mem.flushForced = true
    1203           1 :                         }
    1204           1 :                         d.maybeScheduleFlush()
    1205             :                 }
    1206             :         }()
    1207             : }
    1208             : 
    1209           1 : func (d *DB) flush() {
    1210           1 :         pprof.Do(context.Background(), flushLabels, func(context.Context) {
    1211           1 :                 flushingWorkStart := time.Now()
    1212           1 :                 d.mu.Lock()
    1213           1 :                 defer d.mu.Unlock()
    1214           1 :                 idleDuration := flushingWorkStart.Sub(d.mu.compact.noOngoingFlushStartTime)
    1215           1 :                 var bytesFlushed uint64
    1216           1 :                 var err error
    1217           1 :                 if bytesFlushed, err = d.flush1(); err != nil {
    1218           1 :                         // TODO(peter): count consecutive flush errors and backoff.
    1219           1 :                         d.opts.EventListener.BackgroundError(err)
    1220           1 :                 }
    1221           1 :                 d.mu.compact.flushing = false
    1222           1 :                 d.mu.compact.noOngoingFlushStartTime = time.Now()
    1223           1 :                 workDuration := d.mu.compact.noOngoingFlushStartTime.Sub(flushingWorkStart)
    1224           1 :                 d.mu.compact.flushWriteThroughput.Bytes += int64(bytesFlushed)
    1225           1 :                 d.mu.compact.flushWriteThroughput.WorkDuration += workDuration
    1226           1 :                 d.mu.compact.flushWriteThroughput.IdleDuration += idleDuration
    1227           1 :                 // More flush work may have arrived while we were flushing, so schedule
    1228           1 :                 // another flush if needed.
    1229           1 :                 d.maybeScheduleFlush()
    1230           1 :                 // The flush may have produced too many files in a level, so schedule a
    1231           1 :                 // compaction if needed.
    1232           1 :                 d.maybeScheduleCompaction()
    1233           1 :                 d.mu.compact.cond.Broadcast()
    1234             :         })
    1235             : }
    1236             : 
    1237             : // runIngestFlush is used to generate a flush version edit for sstables which
    1238             : // were ingested as flushables. Both DB.mu and the manifest lock must be held
    1239             : // while runIngestFlush is called.
    1240           1 : func (d *DB) runIngestFlush(c *compaction) (*manifest.VersionEdit, error) {
    1241           1 :         if len(c.flushing) != 1 {
    1242           0 :                 panic("pebble: ingestedFlushable must be flushed one at a time.")
    1243             :         }
    1244             : 
    1245             :         // Construct the VersionEdit, levelMetrics etc.
    1246           1 :         c.metrics = make(map[int]*LevelMetrics, numLevels)
    1247           1 :         // Finding the target level for ingestion must use the latest version
    1248           1 :         // after the logLock has been acquired.
    1249           1 :         c.version = d.mu.versions.currentVersion()
    1250           1 : 
    1251           1 :         baseLevel := d.mu.versions.picker.getBaseLevel()
    1252           1 :         iterOpts := IterOptions{logger: d.opts.Logger}
    1253           1 :         ve := &versionEdit{}
    1254           1 :         var ingestSplitFiles []ingestSplitFile
    1255           1 :         ingestFlushable := c.flushing[0].flushable.(*ingestedFlushable)
    1256           1 : 
    1257           1 :         updateLevelMetricsOnExcise := func(m *fileMetadata, level int, added []newFileEntry) {
    1258           1 :                 levelMetrics := c.metrics[level]
    1259           1 :                 if levelMetrics == nil {
    1260           1 :                         levelMetrics = &LevelMetrics{}
    1261           1 :                         c.metrics[level] = levelMetrics
    1262           1 :                 }
    1263           1 :                 levelMetrics.NumFiles--
    1264           1 :                 levelMetrics.Size -= int64(m.Size)
    1265           1 :                 for i := range added {
    1266           1 :                         levelMetrics.NumFiles++
    1267           1 :                         levelMetrics.Size += int64(added[i].Meta.Size)
    1268           1 :                 }
    1269             :         }
    1270             : 
    1271           1 :         suggestSplit := d.opts.Experimental.IngestSplit != nil && d.opts.Experimental.IngestSplit() &&
    1272           1 :                 d.FormatMajorVersion() >= FormatVirtualSSTables
    1273           1 : 
    1274           1 :         if suggestSplit || ingestFlushable.exciseSpan.Valid() {
    1275           1 :                 // We could add deleted files to ve.
    1276           1 :                 ve.DeletedFiles = make(map[manifest.DeletedFileEntry]*manifest.FileMetadata)
    1277           1 :         }
    1278             : 
    1279           1 :         replacedFiles := make(map[base.FileNum][]newFileEntry)
    1280           1 :         for _, file := range ingestFlushable.files {
    1281           1 :                 var fileToSplit *fileMetadata
    1282           1 :                 var level int
    1283           1 : 
    1284           1 :                 // This file fits perfectly within the excise span, so we can slot it at L6.
    1285           1 :                 if ingestFlushable.exciseSpan.Valid() &&
    1286           1 :                         ingestFlushable.exciseSpan.Contains(d.cmp, file.FileMetadata.Smallest) &&
    1287           1 :                         ingestFlushable.exciseSpan.Contains(d.cmp, file.FileMetadata.Largest) {
    1288           1 :                         level = 6
    1289           1 :                 } else {
    1290           1 :                         var err error
    1291           1 :                         level, fileToSplit, err = ingestTargetLevel(
    1292           1 :                                 d.newIters, d.tableNewRangeKeyIter, iterOpts, d.opts.Comparer,
    1293           1 :                                 c.version, baseLevel, d.mu.compact.inProgress, file.FileMetadata,
    1294           1 :                                 suggestSplit,
    1295           1 :                         )
    1296           1 :                         if err != nil {
    1297           0 :                                 return nil, err
    1298           0 :                         }
    1299             :                 }
    1300             : 
    1301             :                 // Add the current flushableIngest file to the version.
    1302           1 :                 ve.NewFiles = append(ve.NewFiles, newFileEntry{Level: level, Meta: file.FileMetadata})
    1303           1 :                 if fileToSplit != nil {
    1304           0 :                         ingestSplitFiles = append(ingestSplitFiles, ingestSplitFile{
    1305           0 :                                 ingestFile: file.FileMetadata,
    1306           0 :                                 splitFile:  fileToSplit,
    1307           0 :                                 level:      level,
    1308           0 :                         })
    1309           0 :                 }
    1310           1 :                 levelMetrics := c.metrics[level]
    1311           1 :                 if levelMetrics == nil {
    1312           1 :                         levelMetrics = &LevelMetrics{}
    1313           1 :                         c.metrics[level] = levelMetrics
    1314           1 :                 }
    1315           1 :                 levelMetrics.BytesIngested += file.Size
    1316           1 :                 levelMetrics.TablesIngested++
    1317             :         }
    1318           1 :         if ingestFlushable.exciseSpan.Valid() {
    1319           1 :                 // Iterate through all levels and find files that intersect with exciseSpan.
    1320           1 :                 for l := range c.version.Levels {
    1321           1 :                         overlaps := c.version.Overlaps(l, base.UserKeyBoundsEndExclusive(ingestFlushable.exciseSpan.Start, ingestFlushable.exciseSpan.End))
    1322           1 :                         iter := overlaps.Iter()
    1323           1 : 
    1324           1 :                         for m := iter.First(); m != nil; m = iter.Next() {
    1325           1 :                                 newFiles, err := d.excise(ingestFlushable.exciseSpan.UserKeyBounds(), m, ve, l)
    1326           1 :                                 if err != nil {
    1327           0 :                                         return nil, err
    1328           0 :                                 }
    1329             : 
    1330           1 :                                 if _, ok := ve.DeletedFiles[deletedFileEntry{
    1331           1 :                                         Level:   l,
    1332           1 :                                         FileNum: m.FileNum,
    1333           1 :                                 }]; !ok {
    1334           1 :                                         // We did not excise this file.
    1335           1 :                                         continue
    1336             :                                 }
    1337           1 :                                 replacedFiles[m.FileNum] = newFiles
    1338           1 :                                 updateLevelMetricsOnExcise(m, l, newFiles)
    1339             :                         }
    1340             :                 }
    1341             :         }
    1342             : 
    1343           1 :         if len(ingestSplitFiles) > 0 {
    1344           0 :                 if err := d.ingestSplit(ve, updateLevelMetricsOnExcise, ingestSplitFiles, replacedFiles); err != nil {
    1345           0 :                         return nil, err
    1346           0 :                 }
    1347             :         }
    1348             : 
    1349           1 :         return ve, nil
    1350             : }
    1351             : 
    1352             : // flush runs a compaction that copies the immutable memtables from memory to
    1353             : // disk.
    1354             : //
    1355             : // d.mu must be held when calling this, but the mutex may be dropped and
    1356             : // re-acquired during the course of this method.
    1357           1 : func (d *DB) flush1() (bytesFlushed uint64, err error) {
    1358           1 :         // NB: The flushable queue can contain flushables of type ingestedFlushable.
    1359           1 :         // The sstables in ingestedFlushable.files must be placed into the appropriate
    1360           1 :         // level in the lsm. Let's say the flushable queue contains a prefix of
    1361           1 :         // regular immutable memtables, then an ingestedFlushable, and then the
    1362           1 :         // mutable memtable. When the flush of the ingestedFlushable is performed,
    1363           1 :         // it needs an updated view of the lsm. That is, the prefix of immutable
    1364           1 :         // memtables must have already been flushed. Similarly, if there are two
    1365           1 :         // contiguous ingestedFlushables in the queue, then the first flushable must
    1366           1 :         // be flushed, so that the second flushable can see an updated view of the
    1367           1 :         // lsm.
    1368           1 :         //
    1369           1 :         // Given the above, we restrict flushes to either some prefix of regular
    1370           1 :         // memtables, or a single flushable of type ingestedFlushable. The DB.flush
    1371           1 :         // function will call DB.maybeScheduleFlush again, so a new flush to finish
    1372           1 :         // the remaining flush work should be scheduled right away.
    1373           1 :         //
    1374           1 :         // NB: Large batches placed in the flushable queue share the WAL with the
    1375           1 :         // previous memtable in the queue. We must ensure the property that both the
    1376           1 :         // large batch and the memtable with which it shares a WAL are flushed
    1377           1 :         // together. The property ensures that the minimum unflushed log number
    1378           1 :         // isn't incremented incorrectly. Since a flushableBatch.readyToFlush always
    1379           1 :         // returns true, and since the large batch will always be placed right after
    1380           1 :         // the memtable with which it shares a WAL, the property is naturally
    1381           1 :         // ensured. The large batch will always be placed after the memtable with
    1382           1 :         // which it shares a WAL because we ensure it in DB.commitWrite by holding
    1383           1 :         // the commitPipeline.mu and then holding DB.mu. As an extra defensive
    1384           1 :         // measure, if we try to flush the memtable without also flushing the
    1385           1 :         // flushable batch in the same flush, since the memtable and flushableBatch
    1386           1 :         // have the same logNum, the logNum invariant check below will trigger.
    1387           1 :         var n, inputs int
    1388           1 :         var inputBytes uint64
    1389           1 :         var ingest bool
    1390           1 :         for ; n < len(d.mu.mem.queue)-1; n++ {
    1391           1 :                 if f, ok := d.mu.mem.queue[n].flushable.(*ingestedFlushable); ok {
    1392           1 :                         if n == 0 {
    1393           1 :                                 // The first flushable is of type ingestedFlushable. Since these
    1394           1 :                                 // must be flushed individually, we perform a flush for just
    1395           1 :                                 // this.
    1396           1 :                                 if !f.readyForFlush() {
    1397           0 :                                         // This check is almost unnecessary, but we guard against it
    1398           0 :                                         // just in case this invariant changes in the future.
    1399           0 :                                         panic("pebble: ingestedFlushable should always be ready to flush.")
    1400             :                                 }
    1401             :                                 // By setting n = 1, we ensure that the first flushable(n == 0)
    1402             :                                 // is scheduled for a flush. The number of tables added is equal to the
    1403             :                                 // number of files in the ingest operation.
    1404           1 :                                 n = 1
    1405           1 :                                 inputs = len(f.files)
    1406           1 :                                 ingest = true
    1407           1 :                                 break
    1408           1 :                         } else {
    1409           1 :                                 // There was some prefix of flushables which weren't of type
    1410           1 :                                 // ingestedFlushable. So, perform a flush for those.
    1411           1 :                                 break
    1412             :                         }
    1413             :                 }
    1414           1 :                 if !d.mu.mem.queue[n].readyForFlush() {
    1415           1 :                         break
    1416             :                 }
    1417           1 :                 inputBytes += d.mu.mem.queue[n].inuseBytes()
    1418             :         }
    1419           1 :         if n == 0 {
    1420           0 :                 // None of the immutable memtables are ready for flushing.
    1421           0 :                 return 0, nil
    1422           0 :         }
    1423           1 :         if !ingest {
    1424           1 :                 // Flushes of memtables add the prefix of n memtables from the flushable
    1425           1 :                 // queue.
    1426           1 :                 inputs = n
    1427           1 :         }
    1428             : 
    1429             :         // Require that every memtable being flushed has a log number less than the
    1430             :         // new minimum unflushed log number.
    1431           1 :         minUnflushedLogNum := d.mu.mem.queue[n].logNum
    1432           1 :         if !d.opts.DisableWAL {
    1433           1 :                 for i := 0; i < n; i++ {
    1434           1 :                         if logNum := d.mu.mem.queue[i].logNum; logNum >= minUnflushedLogNum {
    1435           0 :                                 panic(errors.AssertionFailedf("logNum invariant violated: flushing %d items; %d:type=%T,logNum=%d; %d:type=%T,logNum=%d",
    1436           0 :                                         n,
    1437           0 :                                         i, d.mu.mem.queue[i].flushable, logNum,
    1438           0 :                                         n, d.mu.mem.queue[n].flushable, minUnflushedLogNum))
    1439             :                         }
    1440             :                 }
    1441             :         }
    1442             : 
    1443           1 :         c, err := newFlush(d.opts, d.mu.versions.currentVersion(),
    1444           1 :                 d.mu.versions.picker.getBaseLevel(), d.mu.mem.queue[:n], d.timeNow())
    1445           1 :         if err != nil {
    1446           0 :                 return 0, err
    1447           0 :         }
    1448           1 :         d.addInProgressCompaction(c)
    1449           1 : 
    1450           1 :         jobID := d.newJobIDLocked()
    1451           1 :         d.opts.EventListener.FlushBegin(FlushInfo{
    1452           1 :                 JobID:      int(jobID),
    1453           1 :                 Input:      inputs,
    1454           1 :                 InputBytes: inputBytes,
    1455           1 :                 Ingest:     ingest,
    1456           1 :         })
    1457           1 :         startTime := d.timeNow()
    1458           1 : 
    1459           1 :         var ve *manifest.VersionEdit
    1460           1 :         var pendingOutputs []compactionOutput
    1461           1 :         var stats compactStats
    1462           1 :         // To determine the target level of the files in the ingestedFlushable, we
    1463           1 :         // need to acquire the logLock, and not release it for that duration. Since,
    1464           1 :         // we need to acquire the logLock below to perform the logAndApply step
    1465           1 :         // anyway, we create the VersionEdit for ingestedFlushable outside of
    1466           1 :         // runCompaction. For all other flush cases, we construct the VersionEdit
    1467           1 :         // inside runCompaction.
    1468           1 :         if c.kind != compactionKindIngestedFlushable {
    1469           1 :                 ve, pendingOutputs, stats, err = d.runCompaction(jobID, c)
    1470           1 :         }
    1471             : 
    1472             :         // Acquire logLock. This will be released either on an error, by way of
    1473             :         // logUnlock, or through a call to logAndApply if there is no error.
    1474           1 :         d.mu.versions.logLock()
    1475           1 : 
    1476           1 :         if c.kind == compactionKindIngestedFlushable {
    1477           1 :                 ve, err = d.runIngestFlush(c)
    1478           1 :         }
    1479             : 
    1480           1 :         info := FlushInfo{
    1481           1 :                 JobID:      int(jobID),
    1482           1 :                 Input:      inputs,
    1483           1 :                 InputBytes: inputBytes,
    1484           1 :                 Duration:   d.timeNow().Sub(startTime),
    1485           1 :                 Done:       true,
    1486           1 :                 Ingest:     ingest,
    1487           1 :                 Err:        err,
    1488           1 :         }
    1489           1 :         if err == nil {
    1490           1 :                 validateVersionEdit(ve, d.opts.Experimental.KeyValidationFunc, d.opts.Comparer.FormatKey, d.opts.Logger)
    1491           1 :                 for i := range ve.NewFiles {
    1492           1 :                         e := &ve.NewFiles[i]
    1493           1 :                         info.Output = append(info.Output, e.Meta.TableInfo())
    1494           1 :                         // Ingested tables are not necessarily flushed to L0. Record the level of
    1495           1 :                         // each ingested file explicitly.
    1496           1 :                         if ingest {
    1497           1 :                                 info.IngestLevels = append(info.IngestLevels, e.Level)
    1498           1 :                         }
    1499             :                 }
    1500           1 :                 if len(ve.NewFiles) == 0 {
    1501           1 :                         info.Err = errEmptyTable
    1502           1 :                 }
    1503             : 
    1504             :                 // The flush succeeded or it produced an empty sstable. In either case we
    1505             :                 // want to bump the minimum unflushed log number to the log number of the
    1506             :                 // oldest unflushed memtable.
    1507           1 :                 ve.MinUnflushedLogNum = minUnflushedLogNum
    1508           1 :                 if c.kind != compactionKindIngestedFlushable {
    1509           1 :                         metrics := c.metrics[0]
    1510           1 :                         if d.opts.DisableWAL {
    1511           1 :                                 // If the WAL is disabled, every flushable has a zero [logSize],
    1512           1 :                                 // resulting in zero bytes in. Instead, use the number of bytes we
    1513           1 :                                 // flushed as the BytesIn. This ensures we get a reasonable w-amp
    1514           1 :                                 // calculation even when the WAL is disabled.
    1515           1 :                                 metrics.BytesIn = metrics.BytesFlushed
    1516           1 :                         } else {
    1517           1 :                                 metrics := c.metrics[0]
    1518           1 :                                 for i := 0; i < n; i++ {
    1519           1 :                                         metrics.BytesIn += d.mu.mem.queue[i].logSize
    1520           1 :                                 }
    1521             :                         }
    1522           1 :                 } else {
    1523           1 :                         // c.kind == compactionKindIngestedFlushable && we could have deleted files due
    1524           1 :                         // to ingest-time splits or excises.
    1525           1 :                         ingestFlushable := c.flushing[0].flushable.(*ingestedFlushable)
    1526           1 :                         for c2 := range d.mu.compact.inProgress {
    1527           1 :                                 // Check if this compaction overlaps with the excise span. Note that just
    1528           1 :                                 // checking if the inputs individually overlap with the excise span
    1529           1 :                                 // isn't sufficient; for instance, a compaction could have [a,b] and [e,f]
    1530           1 :                                 // as inputs and write it all out as [a,b,e,f] in one sstable. If we're
    1531           1 :                                 // doing a [c,d) excise at the same time as this compaction, we will have
    1532           1 :                                 // to error out the whole compaction as we can't guarantee it hasn't/won't
    1533           1 :                                 // write a file overlapping with the excise span.
    1534           1 :                                 if ingestFlushable.exciseSpan.OverlapsInternalKeyRange(d.cmp, c2.smallest, c2.largest) {
    1535           1 :                                         c2.cancel.Store(true)
    1536           1 :                                         continue
    1537             :                                 }
    1538             :                         }
    1539             : 
    1540           1 :                         if len(ve.DeletedFiles) > 0 {
    1541           1 :                                 // Iterate through all other compactions, and check if their inputs have
    1542           1 :                                 // been replaced due to an ingest-time split or excise. In that case,
    1543           1 :                                 // cancel the compaction.
    1544           1 :                                 for c2 := range d.mu.compact.inProgress {
    1545           1 :                                         for i := range c2.inputs {
    1546           1 :                                                 iter := c2.inputs[i].files.Iter()
    1547           1 :                                                 for f := iter.First(); f != nil; f = iter.Next() {
    1548           1 :                                                         if _, ok := ve.DeletedFiles[deletedFileEntry{FileNum: f.FileNum, Level: c2.inputs[i].level}]; ok {
    1549           1 :                                                                 c2.cancel.Store(true)
    1550           1 :                                                                 break
    1551             :                                                         }
    1552             :                                                 }
    1553             :                                         }
    1554             :                                 }
    1555             :                         }
    1556             :                 }
    1557           1 :                 err = d.mu.versions.logAndApply(jobID, ve, c.metrics, false, /* forceRotation */
    1558           1 :                         func() []compactionInfo { return d.getInProgressCompactionInfoLocked(c) })
    1559           1 :                 if err != nil {
    1560           1 :                         info.Err = err
    1561           1 :                         // TODO(peter): untested.
    1562           1 :                         for _, f := range pendingOutputs {
    1563           1 :                                 // Note that the FileBacking for the file metadata might not have
    1564           1 :                                 // been set yet. So, we directly use the FileNum. Since these
    1565           1 :                                 // files were generated as compaction outputs, these must be
    1566           1 :                                 // physical files on disk. This property might not hold once
    1567           1 :                                 // https://github.com/cockroachdb/pebble/issues/389 is
    1568           1 :                                 // implemented if #389 creates virtual sstables as output files.
    1569           1 :                                 d.mu.versions.obsoleteTables = append(d.mu.versions.obsoleteTables, tableInfo{
    1570           1 :                                         fileInfo: fileInfo{
    1571           1 :                                                 FileNum:  base.PhysicalTableDiskFileNum(f.meta.FileNum),
    1572           1 :                                                 FileSize: f.meta.Size,
    1573           1 :                                         },
    1574           1 :                                         isLocal: f.isLocal,
    1575           1 :                                 })
    1576           1 :                         }
    1577           1 :                         d.mu.versions.updateObsoleteTableMetricsLocked()
    1578             :                 }
    1579           1 :         } else {
    1580           1 :                 // We won't be performing the logAndApply step because of the error,
    1581           1 :                 // so logUnlock.
    1582           1 :                 d.mu.versions.logUnlock()
    1583           1 :         }
    1584             : 
    1585             :         // If err != nil, then the flush will be retried, and we will recalculate
    1586             :         // these metrics.
    1587           1 :         if err == nil {
    1588           1 :                 d.mu.snapshots.cumulativePinnedCount += stats.cumulativePinnedKeys
    1589           1 :                 d.mu.snapshots.cumulativePinnedSize += stats.cumulativePinnedSize
    1590           1 :                 d.mu.versions.metrics.Keys.MissizedTombstonesCount += stats.countMissizedDels
    1591           1 :                 d.maybeUpdateDeleteCompactionHints(c)
    1592           1 :         }
    1593             : 
    1594           1 :         d.clearCompactingState(c, err != nil)
    1595           1 :         delete(d.mu.compact.inProgress, c)
    1596           1 :         d.mu.versions.incrementCompactions(c.kind, c.extraLevels, c.pickerMetrics)
    1597           1 : 
    1598           1 :         var flushed flushableList
    1599           1 :         if err == nil {
    1600           1 :                 flushed = d.mu.mem.queue[:n]
    1601           1 :                 d.mu.mem.queue = d.mu.mem.queue[n:]
    1602           1 :                 d.updateReadStateLocked(d.opts.DebugCheck)
    1603           1 :                 d.updateTableStatsLocked(ve.NewFiles)
    1604           1 :                 if ingest {
    1605           1 :                         d.mu.versions.metrics.Flush.AsIngestCount++
    1606           1 :                         for _, l := range c.metrics {
    1607           1 :                                 d.mu.versions.metrics.Flush.AsIngestBytes += l.BytesIngested
    1608           1 :                                 d.mu.versions.metrics.Flush.AsIngestTableCount += l.TablesIngested
    1609           1 :                         }
    1610             :                 }
    1611           1 :                 d.maybeTransitionSnapshotsToFileOnlyLocked()
    1612             : 
    1613             :         }
    1614             :         // Signal FlushEnd after installing the new readState. This helps for unit
    1615             :         // tests that use the callback to trigger a read using an iterator with
    1616             :         // IterOptions.OnlyReadGuaranteedDurable.
    1617           1 :         info.TotalDuration = d.timeNow().Sub(startTime)
    1618           1 :         d.opts.EventListener.FlushEnd(info)
    1619           1 : 
    1620           1 :         // The order of these operations matters here for ease of testing.
    1621           1 :         // Removing the reader reference first allows tests to be guaranteed that
    1622           1 :         // the memtable reservation has been released by the time a synchronous
    1623           1 :         // flush returns. readerUnrefLocked may also produce obsolete files so the
    1624           1 :         // call to deleteObsoleteFiles must happen after it.
    1625           1 :         for i := range flushed {
    1626           1 :                 flushed[i].readerUnrefLocked(true)
    1627           1 :         }
    1628             : 
    1629           1 :         d.deleteObsoleteFiles(jobID)
    1630           1 : 
    1631           1 :         // Mark all the memtables we flushed as flushed.
    1632           1 :         for i := range flushed {
    1633           1 :                 close(flushed[i].flushed)
    1634           1 :         }
    1635             : 
    1636           1 :         return inputBytes, err
    1637             : }
    1638             : 
    1639             : // maybeTransitionSnapshotsToFileOnlyLocked transitions any "eventually
    1640             : // file-only" snapshots to be file-only if all their visible state has been
    1641             : // flushed to sstables.
    1642             : //
    1643             : // REQUIRES: d.mu.
    1644           1 : func (d *DB) maybeTransitionSnapshotsToFileOnlyLocked() {
    1645           1 :         earliestUnflushedSeqNum := d.getEarliestUnflushedSeqNumLocked()
    1646           1 :         currentVersion := d.mu.versions.currentVersion()
    1647           1 :         for s := d.mu.snapshots.root.next; s != &d.mu.snapshots.root; {
    1648           1 :                 if s.efos == nil {
    1649           1 :                         s = s.next
    1650           1 :                         continue
    1651             :                 }
    1652           1 :                 overlapsFlushable := false
    1653           1 :                 if base.Visible(earliestUnflushedSeqNum, s.efos.seqNum, InternalKeySeqNumMax) {
    1654           1 :                         // There are some unflushed keys that are still visible to the EFOS.
    1655           1 :                         // Check if any memtables older than the EFOS contain keys within a
    1656           1 :                         // protected range of the EFOS. If no, we can transition.
    1657           1 :                         protectedRanges := make([]bounded, len(s.efos.protectedRanges))
    1658           1 :                         for i := range s.efos.protectedRanges {
    1659           1 :                                 protectedRanges[i] = s.efos.protectedRanges[i]
    1660           1 :                         }
    1661           1 :                         for i := range d.mu.mem.queue {
    1662           1 :                                 if !base.Visible(d.mu.mem.queue[i].logSeqNum, s.efos.seqNum, InternalKeySeqNumMax) {
    1663           0 :                                         // All keys in this memtable are newer than the EFOS. Skip this
    1664           0 :                                         // memtable.
    1665           0 :                                         continue
    1666             :                                 }
    1667             :                                 // NB: computePossibleOverlaps could have false positives, such as if
    1668             :                                 // the flushable is a flushable ingest and not a memtable. In that
    1669             :                                 // case we don't open the sstables to check; we just pessimistically
    1670             :                                 // assume an overlap.
    1671           1 :                                 d.mu.mem.queue[i].computePossibleOverlaps(func(b bounded) shouldContinue {
    1672           1 :                                         overlapsFlushable = true
    1673           1 :                                         return stopIteration
    1674           1 :                                 }, protectedRanges...)
    1675           1 :                                 if overlapsFlushable {
    1676           1 :                                         break
    1677             :                                 }
    1678             :                         }
    1679             :                 }
    1680           1 :                 if overlapsFlushable {
    1681           1 :                         s = s.next
    1682           1 :                         continue
    1683             :                 }
    1684           1 :                 currentVersion.Ref()
    1685           1 : 
    1686           1 :                 // NB: s.efos.transitionToFileOnlySnapshot could close s, in which
    1687           1 :                 // case s.next would be nil. Save it before calling it.
    1688           1 :                 next := s.next
    1689           1 :                 _ = s.efos.transitionToFileOnlySnapshot(currentVersion)
    1690           1 :                 s = next
    1691             :         }
    1692             : }
    1693             : 
    1694             : // maybeScheduleCompactionAsync should be used when
    1695             : // we want to possibly schedule a compaction, but don't
    1696             : // want to eat the cost of running maybeScheduleCompaction.
    1697             : // This method should be launched in a separate goroutine.
    1698             : // d.mu must not be held when this is called.
    1699           0 : func (d *DB) maybeScheduleCompactionAsync() {
    1700           0 :         defer d.compactionSchedulers.Done()
    1701           0 : 
    1702           0 :         d.mu.Lock()
    1703           0 :         d.maybeScheduleCompaction()
    1704           0 :         d.mu.Unlock()
    1705           0 : }
    1706             : 
    1707             : // maybeScheduleCompaction schedules a compaction if necessary.
    1708             : //
    1709             : // d.mu must be held when calling this.
    1710           1 : func (d *DB) maybeScheduleCompaction() {
    1711           1 :         d.maybeScheduleCompactionPicker(pickAuto)
    1712           1 : }
    1713             : 
    1714           1 : func pickAuto(picker compactionPicker, env compactionEnv) *pickedCompaction {
    1715           1 :         return picker.pickAuto(env)
    1716           1 : }
    1717             : 
    1718           1 : func pickElisionOnly(picker compactionPicker, env compactionEnv) *pickedCompaction {
    1719           1 :         return picker.pickElisionOnlyCompaction(env)
    1720           1 : }
    1721             : 
    1722             : // tryScheduleDownloadCompaction tries to start a download compaction.
    1723             : //
    1724             : // Returns true if we started a download compaction (or completed it
    1725             : // immediately because it is a no-op or we hit an error).
    1726             : //
    1727             : // Requires d.mu to be held. Updates d.mu.compact.downloads.
    1728           1 : func (d *DB) tryScheduleDownloadCompaction(env compactionEnv, maxConcurrentDownloads int) bool {
    1729           1 :         vers := d.mu.versions.currentVersion()
    1730           1 :         for i := 0; i < len(d.mu.compact.downloads); {
    1731           1 :                 download := d.mu.compact.downloads[i]
    1732           1 :                 switch d.tryLaunchDownloadCompaction(download, vers, env, maxConcurrentDownloads) {
    1733           1 :                 case launchedCompaction:
    1734           1 :                         return true
    1735           0 :                 case didNotLaunchCompaction:
    1736           0 :                         // See if we can launch a compaction for another download task.
    1737           0 :                         i++
    1738           1 :                 case downloadTaskCompleted:
    1739           1 :                         // Task is completed and must be removed.
    1740           1 :                         d.mu.compact.downloads = slices.Delete(d.mu.compact.downloads, i, i+1)
    1741             :                 }
    1742             :         }
    1743           1 :         return false
    1744             : }
    1745             : 
    1746             : // maybeScheduleCompactionPicker schedules a compaction if necessary,
    1747             : // calling `pickFunc` to pick automatic compactions.
    1748             : //
    1749             : // Requires d.mu to be held.
    1750             : func (d *DB) maybeScheduleCompactionPicker(
    1751             :         pickFunc func(compactionPicker, compactionEnv) *pickedCompaction,
    1752           1 : ) {
    1753           1 :         if d.closed.Load() != nil || d.opts.ReadOnly {
    1754           1 :                 return
    1755           1 :         }
    1756           1 :         maxCompactions := d.opts.MaxConcurrentCompactions()
    1757           1 :         maxDownloads := d.opts.MaxConcurrentDownloads()
    1758           1 : 
    1759           1 :         if d.mu.compact.compactingCount >= maxCompactions &&
    1760           1 :                 (len(d.mu.compact.downloads) == 0 || d.mu.compact.downloadingCount >= maxDownloads) {
    1761           1 :                 if len(d.mu.compact.manual) > 0 {
    1762           1 :                         // Inability to run head blocks later manual compactions.
    1763           1 :                         d.mu.compact.manual[0].retries++
    1764           1 :                 }
    1765           1 :                 return
    1766             :         }
    1767             : 
    1768             :         // Compaction picking needs a coherent view of a Version. In particular, we
    1769             :         // need to exclude concurrent ingestions from making a decision on which level
    1770             :         // to ingest into that conflicts with our compaction
    1771             :         // decision. versionSet.logLock provides the necessary mutual exclusion.
    1772           1 :         d.mu.versions.logLock()
    1773           1 :         defer d.mu.versions.logUnlock()
    1774           1 : 
    1775           1 :         // Check for the closed flag again, in case the DB was closed while we were
    1776           1 :         // waiting for logLock().
    1777           1 :         if d.closed.Load() != nil {
    1778           0 :                 return
    1779           0 :         }
    1780             : 
    1781           1 :         env := compactionEnv{
    1782           1 :                 diskAvailBytes:          d.diskAvailBytes.Load(),
    1783           1 :                 earliestSnapshotSeqNum:  d.mu.snapshots.earliest(),
    1784           1 :                 earliestUnflushedSeqNum: d.getEarliestUnflushedSeqNumLocked(),
    1785           1 :         }
    1786           1 : 
    1787           1 :         if d.mu.compact.compactingCount < maxCompactions {
    1788           1 :                 // Check for delete-only compactions first, because they're expected to be
    1789           1 :                 // cheap and reduce future compaction work.
    1790           1 :                 if !d.opts.private.disableDeleteOnlyCompactions &&
    1791           1 :                         !d.opts.DisableAutomaticCompactions &&
    1792           1 :                         len(d.mu.compact.deletionHints) > 0 {
    1793           1 :                         d.tryScheduleDeleteOnlyCompaction()
    1794           1 :                 }
    1795             : 
    1796           1 :                 for len(d.mu.compact.manual) > 0 && d.mu.compact.compactingCount < maxCompactions {
    1797           1 :                         if manual := d.mu.compact.manual[0]; !d.tryScheduleManualCompaction(env, manual) {
    1798           1 :                                 // Inability to run head blocks later manual compactions.
    1799           1 :                                 manual.retries++
    1800           1 :                                 break
    1801             :                         }
    1802           1 :                         d.mu.compact.manual = d.mu.compact.manual[1:]
    1803             :                 }
    1804             : 
    1805           1 :                 for !d.opts.DisableAutomaticCompactions && d.mu.compact.compactingCount < maxCompactions &&
    1806           1 :                         d.tryScheduleAutoCompaction(env, pickFunc) {
    1807           1 :                 }
    1808             :         }
    1809             : 
    1810           1 :         for len(d.mu.compact.downloads) > 0 && d.mu.compact.downloadingCount < maxDownloads &&
    1811           1 :                 d.tryScheduleDownloadCompaction(env, maxDownloads) {
    1812           1 :         }
    1813             : }
    1814             : 
    1815             : // tryScheduleDeleteOnlyCompaction tries to kick off a delete-only compaction
    1816             : // for all files that can be deleted as suggested by deletionHints.
    1817             : //
    1818             : // Requires d.mu to be held. Updates d.mu.compact.deletionHints.
    1819           1 : func (d *DB) tryScheduleDeleteOnlyCompaction() {
    1820           1 :         v := d.mu.versions.currentVersion()
    1821           1 :         snapshots := d.mu.snapshots.toSlice()
    1822           1 :         inputs, unresolvedHints := checkDeleteCompactionHints(d.cmp, v, d.mu.compact.deletionHints, snapshots)
    1823           1 :         d.mu.compact.deletionHints = unresolvedHints
    1824           1 : 
    1825           1 :         if len(inputs) > 0 {
    1826           1 :                 c := newDeleteOnlyCompaction(d.opts, v, inputs, d.timeNow())
    1827           1 :                 d.mu.compact.compactingCount++
    1828           1 :                 d.addInProgressCompaction(c)
    1829           1 :                 go d.compact(c, nil)
    1830           1 :         }
    1831             : }
    1832             : 
    1833             : // tryScheduleManualCompaction tries to kick off the given manual compaction.
    1834             : //
    1835             : // Returns false if we are not able to run this compaction at this time.
    1836             : //
    1837             : // Requires d.mu to be held.
    1838           1 : func (d *DB) tryScheduleManualCompaction(env compactionEnv, manual *manualCompaction) bool {
    1839           1 :         v := d.mu.versions.currentVersion()
    1840           1 :         env.inProgressCompactions = d.getInProgressCompactionInfoLocked(nil)
    1841           1 :         pc, retryLater := pickManualCompaction(v, d.opts, env, d.mu.versions.picker.getBaseLevel(), manual)
    1842           1 :         if pc == nil {
    1843           1 :                 if !retryLater {
    1844           1 :                         // Manual compaction is a no-op. Signal completion and exit.
    1845           1 :                         manual.done <- nil
    1846           1 :                         return true
    1847           1 :                 }
    1848             :                 // We are not able to run this manual compaction at this time.
    1849           1 :                 return false
    1850             :         }
    1851             : 
    1852           1 :         c := newCompaction(pc, d.opts, d.timeNow(), d.ObjProvider())
    1853           1 :         d.mu.compact.compactingCount++
    1854           1 :         d.addInProgressCompaction(c)
    1855           1 :         go d.compact(c, manual.done)
    1856           1 :         return true
    1857             : }
    1858             : 
    1859             : // tryScheduleAutoCompaction tries to kick off an automatic compaction.
    1860             : //
    1861             : // Returns false if no automatic compactions are necessary or able to run at
    1862             : // this time.
    1863             : //
    1864             : // Requires d.mu to be held.
    1865             : func (d *DB) tryScheduleAutoCompaction(
    1866             :         env compactionEnv, pickFunc func(compactionPicker, compactionEnv) *pickedCompaction,
    1867           1 : ) bool {
    1868           1 :         env.inProgressCompactions = d.getInProgressCompactionInfoLocked(nil)
    1869           1 :         env.readCompactionEnv = readCompactionEnv{
    1870           1 :                 readCompactions:          &d.mu.compact.readCompactions,
    1871           1 :                 flushing:                 d.mu.compact.flushing || d.passedFlushThreshold(),
    1872           1 :                 rescheduleReadCompaction: &d.mu.compact.rescheduleReadCompaction,
    1873           1 :         }
    1874           1 :         pc := pickFunc(d.mu.versions.picker, env)
    1875           1 :         if pc == nil {
    1876           1 :                 return false
    1877           1 :         }
    1878           1 :         c := newCompaction(pc, d.opts, d.timeNow(), d.ObjProvider())
    1879           1 :         d.mu.compact.compactingCount++
    1880           1 :         d.addInProgressCompaction(c)
    1881           1 :         go d.compact(c, nil)
    1882           1 :         return true
    1883             : }
    1884             : 
    1885             : // deleteCompactionHintType indicates whether the deleteCompactionHint was
    1886             : // generated from a span containing a range del (point key only), a range key
    1887             : // delete (range key only), or both a point and range key.
    1888             : type deleteCompactionHintType uint8
    1889             : 
    1890             : const (
    1891             :         // NOTE: While these are primarily used as enumeration types, they are also
    1892             :         // used for some bitwise operations. Care should be taken when updating.
    1893             :         deleteCompactionHintTypeUnknown deleteCompactionHintType = iota
    1894             :         deleteCompactionHintTypePointKeyOnly
    1895             :         deleteCompactionHintTypeRangeKeyOnly
    1896             :         deleteCompactionHintTypePointAndRangeKey
    1897             : )
    1898             : 
    1899             : // String implements fmt.Stringer.
    1900           1 : func (h deleteCompactionHintType) String() string {
    1901           1 :         switch h {
    1902           0 :         case deleteCompactionHintTypeUnknown:
    1903           0 :                 return "unknown"
    1904           1 :         case deleteCompactionHintTypePointKeyOnly:
    1905           1 :                 return "point-key-only"
    1906           1 :         case deleteCompactionHintTypeRangeKeyOnly:
    1907           1 :                 return "range-key-only"
    1908           1 :         case deleteCompactionHintTypePointAndRangeKey:
    1909           1 :                 return "point-and-range-key"
    1910           0 :         default:
    1911           0 :                 panic(fmt.Sprintf("unknown hint type: %d", h))
    1912             :         }
    1913             : }
    1914             : 
    1915             : // compactionHintFromKeys returns a deleteCompactionHintType given a slice of
    1916             : // keyspan.Keys.
    1917           1 : func compactionHintFromKeys(keys []keyspan.Key) deleteCompactionHintType {
    1918           1 :         var hintType deleteCompactionHintType
    1919           1 :         for _, k := range keys {
    1920           1 :                 switch k.Kind() {
    1921           1 :                 case base.InternalKeyKindRangeDelete:
    1922           1 :                         hintType |= deleteCompactionHintTypePointKeyOnly
    1923           1 :                 case base.InternalKeyKindRangeKeyDelete:
    1924           1 :                         hintType |= deleteCompactionHintTypeRangeKeyOnly
    1925           0 :                 default:
    1926           0 :                         panic(fmt.Sprintf("unsupported key kind: %s", k.Kind()))
    1927             :                 }
    1928             :         }
    1929           1 :         return hintType
    1930             : }
    1931             : 
    1932             : // A deleteCompactionHint records a user key and sequence number span that has been
    1933             : // deleted by a range tombstone. A hint is recorded if at least one sstable
    1934             : // falls completely within both the user key and sequence number spans.
    1935             : // Once the tombstones and the observed completely-contained sstables fall
    1936             : // into the same snapshot stripe, a delete-only compaction may delete any
    1937             : // sstables within the range.
    1938             : type deleteCompactionHint struct {
    1939             :         // The type of key span that generated this hint (point key, range key, or
    1940             :         // both).
    1941             :         hintType deleteCompactionHintType
    1942             :         // start and end are user keys specifying a key range [start, end) of
    1943             :         // deleted keys.
    1944             :         start []byte
    1945             :         end   []byte
    1946             :         // The level of the file containing the range tombstone(s) when the hint
    1947             :         // was created. Only lower levels need to be searched for files that may
    1948             :         // be deleted.
    1949             :         tombstoneLevel int
    1950             :         // The file containing the range tombstone(s) that created the hint.
    1951             :         tombstoneFile *fileMetadata
    1952             :         // The smallest and largest sequence numbers of the abutting tombstones
    1953             :         // merged to form this hint. All of a tables' keys must be less than the
    1954             :         // tombstone smallest sequence number to be deleted. All of a tables'
    1955             :         // sequence numbers must fall into the same snapshot stripe as the
    1956             :         // tombstone largest sequence number to be deleted.
    1957             :         tombstoneLargestSeqNum  uint64
    1958             :         tombstoneSmallestSeqNum uint64
    1959             :         // The smallest sequence number of a sstable that was found to be covered
    1960             :         // by this hint. The hint cannot be resolved until this sequence number is
    1961             :         // in the same snapshot stripe as the largest tombstone sequence number.
    1962             :         // This is set when a hint is created, so the LSM may look different and
    1963             :         // notably no longer contain the sstable that contained the key at this
    1964             :         // sequence number.
    1965             :         fileSmallestSeqNum uint64
    1966             : }
    1967             : 
    1968           1 : func (h deleteCompactionHint) String() string {
    1969           1 :         return fmt.Sprintf(
    1970           1 :                 "L%d.%s %s-%s seqnums(tombstone=%d-%d, file-smallest=%d, type=%s)",
    1971           1 :                 h.tombstoneLevel, h.tombstoneFile.FileNum, h.start, h.end,
    1972           1 :                 h.tombstoneSmallestSeqNum, h.tombstoneLargestSeqNum, h.fileSmallestSeqNum,
    1973           1 :                 h.hintType,
    1974           1 :         )
    1975           1 : }
    1976             : 
    1977             : func (h *deleteCompactionHint) canDelete(
    1978             :         cmp Compare, m *fileMetadata, snapshots compact.Snapshots,
    1979           1 : ) bool {
    1980           1 :         // The file can only be deleted if all of its keys are older than the
    1981           1 :         // earliest tombstone aggregated into the hint.
    1982           1 :         if m.LargestSeqNum >= h.tombstoneSmallestSeqNum || m.SmallestSeqNum < h.fileSmallestSeqNum {
    1983           1 :                 return false
    1984           1 :         }
    1985             : 
    1986             :         // The file's oldest key must  be in the same snapshot stripe as the
    1987             :         // newest tombstone. NB: We already checked the hint's sequence numbers,
    1988             :         // but this file's oldest sequence number might be lower than the hint's
    1989             :         // smallest sequence number despite the file falling within the key range
    1990             :         // if this file was constructed after the hint by a compaction.
    1991           1 :         if snapshots.Index(h.tombstoneLargestSeqNum) != snapshots.Index(m.SmallestSeqNum) {
    1992           0 :                 return false
    1993           0 :         }
    1994             : 
    1995           1 :         switch h.hintType {
    1996           1 :         case deleteCompactionHintTypePointKeyOnly:
    1997           1 :                 // A hint generated by a range del span cannot delete tables that contain
    1998           1 :                 // range keys.
    1999           1 :                 if m.HasRangeKeys {
    2000           0 :                         return false
    2001           0 :                 }
    2002           1 :         case deleteCompactionHintTypeRangeKeyOnly:
    2003           1 :                 // A hint generated by a range key del span cannot delete tables that
    2004           1 :                 // contain point keys.
    2005           1 :                 if m.HasPointKeys {
    2006           1 :                         return false
    2007           1 :                 }
    2008           1 :         case deleteCompactionHintTypePointAndRangeKey:
    2009             :                 // A hint from a span that contains both range dels *and* range keys can
    2010             :                 // only be deleted if both bounds fall within the hint. The next check takes
    2011             :                 // care of this.
    2012           0 :         default:
    2013           0 :                 panic(fmt.Sprintf("pebble: unknown delete compaction hint type: %d", h.hintType))
    2014             :         }
    2015             : 
    2016             :         // The file's keys must be completely contained within the hint range.
    2017           1 :         return cmp(h.start, m.Smallest.UserKey) <= 0 && cmp(m.Largest.UserKey, h.end) < 0
    2018             : }
    2019             : 
    2020           1 : func (d *DB) maybeUpdateDeleteCompactionHints(c *compaction) {
    2021           1 :         // Compactions that zero sequence numbers can interfere with compaction
    2022           1 :         // deletion hints. Deletion hints apply to tables containing keys older
    2023           1 :         // than a threshold. If a key more recent than the threshold is zeroed in
    2024           1 :         // a compaction, a delete-only compaction may mistake it as meeting the
    2025           1 :         // threshold and drop a table containing live data.
    2026           1 :         //
    2027           1 :         // To avoid this scenario, compactions that zero sequence numbers remove
    2028           1 :         // any conflicting deletion hints. A deletion hint is conflicting if both
    2029           1 :         // of the following conditions apply:
    2030           1 :         // * its key space overlaps with the compaction
    2031           1 :         // * at least one of its inputs contains a key as recent as one of the
    2032           1 :         //   hint's tombstones.
    2033           1 :         //
    2034           1 :         if !c.allowedZeroSeqNum {
    2035           1 :                 return
    2036           1 :         }
    2037             : 
    2038           1 :         updatedHints := d.mu.compact.deletionHints[:0]
    2039           1 :         for _, h := range d.mu.compact.deletionHints {
    2040           1 :                 // If the compaction's key space is disjoint from the hint's key
    2041           1 :                 // space, the zeroing of sequence numbers won't affect the hint. Keep
    2042           1 :                 // the hint.
    2043           1 :                 keysDisjoint := d.cmp(h.end, c.smallest.UserKey) < 0 || d.cmp(h.start, c.largest.UserKey) > 0
    2044           1 :                 if keysDisjoint {
    2045           0 :                         updatedHints = append(updatedHints, h)
    2046           0 :                         continue
    2047             :                 }
    2048             : 
    2049             :                 // All of the compaction's inputs must be older than the hint's
    2050             :                 // tombstones.
    2051           1 :                 inputsOlder := true
    2052           1 :                 for _, in := range c.inputs {
    2053           1 :                         iter := in.files.Iter()
    2054           1 :                         for f := iter.First(); f != nil; f = iter.Next() {
    2055           1 :                                 inputsOlder = inputsOlder && f.LargestSeqNum < h.tombstoneSmallestSeqNum
    2056           1 :                         }
    2057             :                 }
    2058           1 :                 if inputsOlder {
    2059           0 :                         updatedHints = append(updatedHints, h)
    2060           0 :                         continue
    2061             :                 }
    2062             : 
    2063             :                 // Drop h, because the compaction c may have zeroed sequence numbers
    2064             :                 // of keys more recent than some of h's tombstones.
    2065             :         }
    2066           1 :         d.mu.compact.deletionHints = updatedHints
    2067             : }
    2068             : 
    2069             : func checkDeleteCompactionHints(
    2070             :         cmp Compare, v *version, hints []deleteCompactionHint, snapshots compact.Snapshots,
    2071           1 : ) ([]compactionLevel, []deleteCompactionHint) {
    2072           1 :         var files map[*fileMetadata]bool
    2073           1 :         var byLevel [numLevels][]*fileMetadata
    2074           1 : 
    2075           1 :         unresolvedHints := hints[:0]
    2076           1 :         for _, h := range hints {
    2077           1 :                 // Check each compaction hint to see if it's resolvable. Resolvable
    2078           1 :                 // hints are removed and trigger a delete-only compaction if any files
    2079           1 :                 // in the current LSM still meet their criteria. Unresolvable hints
    2080           1 :                 // are saved and don't trigger a delete-only compaction.
    2081           1 :                 //
    2082           1 :                 // When a compaction hint is created, the sequence numbers of the
    2083           1 :                 // range tombstones and the covered file with the oldest key are
    2084           1 :                 // recorded. The largest tombstone sequence number and the smallest
    2085           1 :                 // file sequence number must be in the same snapshot stripe for the
    2086           1 :                 // hint to be resolved. The below graphic models a compaction hint
    2087           1 :                 // covering the keyspace [b, r). The hint completely contains two
    2088           1 :                 // files, 000002 and 000003. The file 000003 contains the lowest
    2089           1 :                 // covered sequence number at #90. The tombstone b.RANGEDEL.230:h has
    2090           1 :                 // the highest tombstone sequence number incorporated into the hint.
    2091           1 :                 // The hint may be resolved only once the snapshots at #100, #180 and
    2092           1 :                 // #210 are all closed. File 000001 is not included within the hint
    2093           1 :                 // because it extends beyond the range tombstones in user key space.
    2094           1 :                 //
    2095           1 :                 // 250
    2096           1 :                 //
    2097           1 :                 //       |-b...230:h-|
    2098           1 :                 // _____________________________________________________ snapshot #210
    2099           1 :                 // 200               |--h.RANGEDEL.200:r--|
    2100           1 :                 //
    2101           1 :                 // _____________________________________________________ snapshot #180
    2102           1 :                 //
    2103           1 :                 // 150                     +--------+
    2104           1 :                 //           +---------+   | 000003 |
    2105           1 :                 //           | 000002  |   |        |
    2106           1 :                 //           +_________+   |        |
    2107           1 :                 // 100_____________________|________|___________________ snapshot #100
    2108           1 :                 //                         +--------+
    2109           1 :                 // _____________________________________________________ snapshot #70
    2110           1 :                 //                             +---------------+
    2111           1 :                 //  50                         | 000001        |
    2112           1 :                 //                             |               |
    2113           1 :                 //                             +---------------+
    2114           1 :                 // ______________________________________________________________
    2115           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
    2116           1 : 
    2117           1 :                 if snapshots.Index(h.tombstoneLargestSeqNum) != snapshots.Index(h.fileSmallestSeqNum) {
    2118           1 :                         // Cannot resolve yet.
    2119           1 :                         unresolvedHints = append(unresolvedHints, h)
    2120           1 :                         continue
    2121             :                 }
    2122             : 
    2123             :                 // The hint h will be resolved and dropped, regardless of whether
    2124             :                 // there are any tables that can be deleted.
    2125           1 :                 for l := h.tombstoneLevel + 1; l < numLevels; l++ {
    2126           1 :                         overlaps := v.Overlaps(l, base.UserKeyBoundsEndExclusive(h.start, h.end))
    2127           1 :                         iter := overlaps.Iter()
    2128           1 :                         for m := iter.First(); m != nil; m = iter.Next() {
    2129           1 :                                 if m.IsCompacting() || !h.canDelete(cmp, m, snapshots) || files[m] {
    2130           1 :                                         continue
    2131             :                                 }
    2132           1 :                                 if files == nil {
    2133           1 :                                         // Construct files lazily, assuming most calls will not
    2134           1 :                                         // produce delete-only compactions.
    2135           1 :                                         files = make(map[*fileMetadata]bool)
    2136           1 :                                 }
    2137           1 :                                 files[m] = true
    2138           1 :                                 byLevel[l] = append(byLevel[l], m)
    2139             :                         }
    2140             :                 }
    2141             :         }
    2142             : 
    2143           1 :         var compactLevels []compactionLevel
    2144           1 :         for l, files := range byLevel {
    2145           1 :                 if len(files) == 0 {
    2146           1 :                         continue
    2147             :                 }
    2148           1 :                 compactLevels = append(compactLevels, compactionLevel{
    2149           1 :                         level: l,
    2150           1 :                         files: manifest.NewLevelSliceKeySorted(cmp, files),
    2151           1 :                 })
    2152             :         }
    2153           1 :         return compactLevels, unresolvedHints
    2154             : }
    2155             : 
    2156             : // compact runs one compaction and maybe schedules another call to compact.
    2157           1 : func (d *DB) compact(c *compaction, errChannel chan error) {
    2158           1 :         pprof.Do(context.Background(), compactLabels, func(context.Context) {
    2159           1 :                 d.mu.Lock()
    2160           1 :                 defer d.mu.Unlock()
    2161           1 :                 if err := d.compact1(c, errChannel); err != nil {
    2162           1 :                         // TODO(peter): count consecutive compaction errors and backoff.
    2163           1 :                         d.opts.EventListener.BackgroundError(err)
    2164           1 :                 }
    2165           1 :                 if c.isDownload {
    2166           1 :                         d.mu.compact.downloadingCount--
    2167           1 :                 } else {
    2168           1 :                         d.mu.compact.compactingCount--
    2169           1 :                 }
    2170           1 :                 delete(d.mu.compact.inProgress, c)
    2171           1 :                 // Add this compaction's duration to the cumulative duration. NB: This
    2172           1 :                 // must be atomic with the above removal of c from
    2173           1 :                 // d.mu.compact.InProgress to ensure Metrics.Compact.Duration does not
    2174           1 :                 // miss or double count a completing compaction's duration.
    2175           1 :                 d.mu.compact.duration += d.timeNow().Sub(c.beganAt)
    2176           1 : 
    2177           1 :                 // The previous compaction may have produced too many files in a
    2178           1 :                 // level, so reschedule another compaction if needed.
    2179           1 :                 d.maybeScheduleCompaction()
    2180           1 :                 d.mu.compact.cond.Broadcast()
    2181             :         })
    2182             : }
    2183             : 
    2184             : // compact1 runs one compaction.
    2185             : //
    2186             : // d.mu must be held when calling this, but the mutex may be dropped and
    2187             : // re-acquired during the course of this method.
    2188           1 : func (d *DB) compact1(c *compaction, errChannel chan error) (err error) {
    2189           1 :         if errChannel != nil {
    2190           1 :                 defer func() {
    2191           1 :                         errChannel <- err
    2192           1 :                 }()
    2193             :         }
    2194             : 
    2195           1 :         jobID := d.newJobIDLocked()
    2196           1 :         info := c.makeInfo(jobID)
    2197           1 :         d.opts.EventListener.CompactionBegin(info)
    2198           1 :         startTime := d.timeNow()
    2199           1 : 
    2200           1 :         ve, pendingOutputs, stats, err := d.runCompaction(jobID, c)
    2201           1 : 
    2202           1 :         info.Duration = d.timeNow().Sub(startTime)
    2203           1 :         if err == nil {
    2204           1 :                 validateVersionEdit(ve, d.opts.Experimental.KeyValidationFunc, d.opts.Comparer.FormatKey, d.opts.Logger)
    2205           1 :                 err = func() error {
    2206           1 :                         var err error
    2207           1 :                         d.mu.versions.logLock()
    2208           1 :                         // Check if this compaction had a conflicting operation (eg. a d.excise())
    2209           1 :                         // that necessitates it restarting from scratch. Note that since we hold
    2210           1 :                         // the manifest lock, we don't expect this bool to change its value
    2211           1 :                         // as only the holder of the manifest lock will ever write to it.
    2212           1 :                         if c.cancel.Load() {
    2213           1 :                                 err = firstError(err, ErrCancelledCompaction)
    2214           1 :                         }
    2215           1 :                         if err != nil {
    2216           1 :                                 // logAndApply calls logUnlock. If we didn't call it, we need to call
    2217           1 :                                 // logUnlock ourselves.
    2218           1 :                                 d.mu.versions.logUnlock()
    2219           1 :                                 return err
    2220           1 :                         }
    2221           1 :                         return d.mu.versions.logAndApply(jobID, ve, c.metrics, false /* forceRotation */, func() []compactionInfo {
    2222           1 :                                 return d.getInProgressCompactionInfoLocked(c)
    2223           1 :                         })
    2224             :                 }()
    2225           1 :                 if err != nil {
    2226           1 :                         // TODO(peter): untested.
    2227           1 :                         for _, f := range pendingOutputs {
    2228           1 :                                 // Note that the FileBacking for the file metadata might not have
    2229           1 :                                 // been set yet. So, we directly use the FileNum. Since these
    2230           1 :                                 // files were generated as compaction outputs, these must be
    2231           1 :                                 // physical files on disk. This property might not hold once
    2232           1 :                                 // https://github.com/cockroachdb/pebble/issues/389 is
    2233           1 :                                 // implemented if #389 creates virtual sstables as output files.
    2234           1 :                                 d.mu.versions.obsoleteTables = append(d.mu.versions.obsoleteTables, tableInfo{
    2235           1 :                                         fileInfo: fileInfo{
    2236           1 :                                                 FileNum:  base.PhysicalTableDiskFileNum(f.meta.FileNum),
    2237           1 :                                                 FileSize: f.meta.Size,
    2238           1 :                                         },
    2239           1 :                                         isLocal: f.isLocal,
    2240           1 :                                 })
    2241           1 :                         }
    2242           1 :                         d.mu.versions.updateObsoleteTableMetricsLocked()
    2243             :                 }
    2244             :         }
    2245             : 
    2246           1 :         info.Done = true
    2247           1 :         info.Err = err
    2248           1 :         if err == nil {
    2249           1 :                 for i := range ve.NewFiles {
    2250           1 :                         e := &ve.NewFiles[i]
    2251           1 :                         info.Output.Tables = append(info.Output.Tables, e.Meta.TableInfo())
    2252           1 :                 }
    2253           1 :                 d.mu.snapshots.cumulativePinnedCount += stats.cumulativePinnedKeys
    2254           1 :                 d.mu.snapshots.cumulativePinnedSize += stats.cumulativePinnedSize
    2255           1 :                 d.mu.versions.metrics.Keys.MissizedTombstonesCount += stats.countMissizedDels
    2256           1 :                 d.maybeUpdateDeleteCompactionHints(c)
    2257             :         }
    2258             : 
    2259             :         // NB: clearing compacting state must occur before updating the read state;
    2260             :         // L0Sublevels initialization depends on it.
    2261           1 :         d.clearCompactingState(c, err != nil)
    2262           1 :         d.mu.versions.incrementCompactions(c.kind, c.extraLevels, c.pickerMetrics)
    2263           1 :         d.mu.versions.incrementCompactionBytes(-c.bytesWritten)
    2264           1 : 
    2265           1 :         info.TotalDuration = d.timeNow().Sub(c.beganAt)
    2266           1 :         d.opts.EventListener.CompactionEnd(info)
    2267           1 : 
    2268           1 :         // Update the read state before deleting obsolete files because the
    2269           1 :         // read-state update will cause the previous version to be unref'd and if
    2270           1 :         // there are no references obsolete tables will be added to the obsolete
    2271           1 :         // table list.
    2272           1 :         if err == nil {
    2273           1 :                 d.updateReadStateLocked(d.opts.DebugCheck)
    2274           1 :                 d.updateTableStatsLocked(ve.NewFiles)
    2275           1 :         }
    2276           1 :         d.deleteObsoleteFiles(jobID)
    2277           1 : 
    2278           1 :         return err
    2279             : }
    2280             : 
    2281             : type compactStats struct {
    2282             :         cumulativePinnedKeys uint64
    2283             :         cumulativePinnedSize uint64
    2284             :         countMissizedDels    uint64
    2285             : }
    2286             : 
    2287             : // runCopyCompaction runs a copy compaction where a new FileNum is created that
    2288             : // is a byte-for-byte copy of the input file or span thereof in some cases. This
    2289             : // is used in lieu of a move compaction when a file is being moved across the
    2290             : // local/remote storage boundary. It could also be used in lieu of a rewrite
    2291             : // compaction as part of a Download() call, which allows copying only a span of
    2292             : // the external file, provided the file does not contain range keys or value
    2293             : // blocks (see sstable.CopySpan).
    2294             : //
    2295             : // d.mu must be held when calling this method. The mutex will be released when
    2296             : // doing IO.
    2297             : func (d *DB) runCopyCompaction(
    2298             :         jobID JobID,
    2299             :         c *compaction,
    2300             :         inputMeta *fileMetadata,
    2301             :         objMeta objstorage.ObjectMetadata,
    2302             :         ve *versionEdit,
    2303           1 : ) (pendingOutputs []compactionOutput, retErr error) {
    2304           1 :         ctx := context.TODO()
    2305           1 : 
    2306           1 :         if !objMeta.IsExternal() {
    2307           1 :                 if objMeta.IsRemote() || !remote.ShouldCreateShared(d.opts.Experimental.CreateOnShared, c.outputLevel.level) {
    2308           0 :                         panic("pebble: scheduled a copy compaction that is not actually moving files to shared storage")
    2309             :                 }
    2310             :                 // Note that based on logic in the compaction picker, we're guaranteed
    2311             :                 // inputMeta.Virtual is false.
    2312           1 :                 if inputMeta.Virtual {
    2313           0 :                         panic(errors.AssertionFailedf("cannot do a copy compaction of a virtual sstable across local/remote storage"))
    2314             :                 }
    2315             :         }
    2316             : 
    2317             :         // We are in the relatively more complex case where we need to copy this
    2318             :         // file to remote storage. Drop the db mutex while we do the copy
    2319             :         //
    2320             :         // To ease up cleanup of the local file and tracking of refs, we create
    2321             :         // a new FileNum. This has the potential of making the block cache less
    2322             :         // effective, however.
    2323           1 :         newMeta := &fileMetadata{
    2324           1 :                 Size:            inputMeta.Size,
    2325           1 :                 CreationTime:    inputMeta.CreationTime,
    2326           1 :                 SmallestSeqNum:  inputMeta.SmallestSeqNum,
    2327           1 :                 LargestSeqNum:   inputMeta.LargestSeqNum,
    2328           1 :                 Stats:           inputMeta.Stats,
    2329           1 :                 Virtual:         inputMeta.Virtual,
    2330           1 :                 SyntheticPrefix: inputMeta.SyntheticPrefix,
    2331           1 :                 SyntheticSuffix: inputMeta.SyntheticSuffix,
    2332           1 :         }
    2333           1 :         if inputMeta.HasPointKeys {
    2334           1 :                 newMeta.ExtendPointKeyBounds(c.cmp, inputMeta.SmallestPointKey, inputMeta.LargestPointKey)
    2335           1 :         }
    2336           1 :         if inputMeta.HasRangeKeys {
    2337           1 :                 newMeta.ExtendRangeKeyBounds(c.cmp, inputMeta.SmallestRangeKey, inputMeta.LargestRangeKey)
    2338           1 :         }
    2339           1 :         newMeta.FileNum = d.mu.versions.getNextFileNum()
    2340           1 :         if objMeta.IsExternal() {
    2341           1 :                 // external -> local/shared copy. File must be virtual.
    2342           1 :                 // We will update this size later after we produce the new backing file.
    2343           1 :                 newMeta.InitProviderBacking(base.DiskFileNum(newMeta.FileNum), inputMeta.FileBacking.Size)
    2344           1 :         } else {
    2345           1 :                 // local -> shared copy. New file is guaranteed to not be virtual.
    2346           1 :                 newMeta.InitPhysicalBacking()
    2347           1 :         }
    2348             : 
    2349           1 :         c.metrics = map[int]*LevelMetrics{
    2350           1 :                 c.outputLevel.level: {
    2351           1 :                         BytesIn:         inputMeta.Size,
    2352           1 :                         BytesCompacted:  inputMeta.Size,
    2353           1 :                         TablesCompacted: 1,
    2354           1 :                 },
    2355           1 :         }
    2356           1 : 
    2357           1 :         // Before dropping the db mutex, grab a ref to the current version. This
    2358           1 :         // prevents any concurrent excises from deleting files that this compaction
    2359           1 :         // needs to read/maintain a reference to.
    2360           1 :         vers := d.mu.versions.currentVersion()
    2361           1 :         vers.Ref()
    2362           1 :         defer vers.UnrefLocked()
    2363           1 : 
    2364           1 :         // NB: The order here is reversed, lock after unlock. This is similar to
    2365           1 :         // runCompaction.
    2366           1 :         d.mu.Unlock()
    2367           1 :         defer d.mu.Lock()
    2368           1 : 
    2369           1 :         // If the src obj is external, we're doing an external to local/shared copy.
    2370           1 :         if objMeta.IsExternal() {
    2371           1 :                 src, err := d.objProvider.OpenForReading(
    2372           1 :                         ctx, fileTypeTable, inputMeta.FileBacking.DiskFileNum, objstorage.OpenOptions{},
    2373           1 :                 )
    2374           1 :                 if err != nil {
    2375           0 :                         return pendingOutputs, err
    2376           0 :                 }
    2377           1 :                 defer func() {
    2378           1 :                         if src != nil {
    2379           0 :                                 src.Close()
    2380           0 :                         }
    2381             :                 }()
    2382             : 
    2383           1 :                 w, outObjMeta, err := d.objProvider.Create(
    2384           1 :                         ctx, fileTypeTable, base.PhysicalTableDiskFileNum(newMeta.FileNum),
    2385           1 :                         objstorage.CreateOptions{
    2386           1 :                                 PreferSharedStorage: remote.ShouldCreateShared(d.opts.Experimental.CreateOnShared, c.outputLevel.level),
    2387           1 :                         },
    2388           1 :                 )
    2389           1 :                 if err != nil {
    2390           0 :                         return pendingOutputs, err
    2391           0 :                 }
    2392           1 :                 pendingOutputs = append(pendingOutputs, compactionOutput{
    2393           1 :                         meta:    newMeta,
    2394           1 :                         isLocal: !outObjMeta.IsRemote(),
    2395           1 :                 })
    2396           1 : 
    2397           1 :                 start, end := newMeta.Smallest, newMeta.Largest
    2398           1 :                 if newMeta.SyntheticPrefix.IsSet() {
    2399           1 :                         start.UserKey = newMeta.SyntheticPrefix.Invert(start.UserKey)
    2400           1 :                         end.UserKey = newMeta.SyntheticPrefix.Invert(end.UserKey)
    2401           1 :                 }
    2402           1 :                 if newMeta.SyntheticSuffix.IsSet() {
    2403           0 :                         // Extend the bounds as necessary so that the keys don't include suffixes.
    2404           0 :                         start.UserKey = start.UserKey[:c.comparer.Split(start.UserKey)]
    2405           0 :                         if n := c.comparer.Split(end.UserKey); n < len(end.UserKey) {
    2406           0 :                                 end = base.MakeRangeDeleteSentinelKey(c.comparer.ImmediateSuccessor(nil, end.UserKey[:n]))
    2407           0 :                         }
    2408             :                 }
    2409             : 
    2410           1 :                 wrote, err := sstable.CopySpan(ctx,
    2411           1 :                         src, d.opts.MakeReaderOptions(),
    2412           1 :                         w, d.opts.MakeWriterOptions(c.outputLevel.level, d.FormatMajorVersion().MaxTableFormat()),
    2413           1 :                         start, end,
    2414           1 :                 )
    2415           1 :                 src = nil // We passed src to CopySpan; it's responsible for closing it.
    2416           1 :                 if err != nil {
    2417           0 :                         return pendingOutputs, err
    2418           0 :                 }
    2419           1 :                 newMeta.FileBacking.Size = wrote
    2420           1 :                 newMeta.Size = wrote
    2421           1 :         } else {
    2422           1 :                 pendingOutputs = append(pendingOutputs, compactionOutput{
    2423           1 :                         meta:    newMeta.PhysicalMeta().FileMetadata,
    2424           1 :                         isLocal: true,
    2425           1 :                 })
    2426           1 :                 _, err := d.objProvider.LinkOrCopyFromLocal(context.TODO(), d.opts.FS,
    2427           1 :                         d.objProvider.Path(objMeta), fileTypeTable, newMeta.FileBacking.DiskFileNum,
    2428           1 :                         objstorage.CreateOptions{PreferSharedStorage: true})
    2429           1 : 
    2430           1 :                 if err != nil {
    2431           0 :                         return pendingOutputs, err
    2432           0 :                 }
    2433             :         }
    2434           1 :         ve.NewFiles[0].Meta = newMeta
    2435           1 :         if newMeta.Virtual {
    2436           1 :                 ve.CreatedBackingTables = []*fileBacking{newMeta.FileBacking}
    2437           1 :         }
    2438             : 
    2439           1 :         if err := d.objProvider.Sync(); err != nil {
    2440           0 :                 return pendingOutputs, err
    2441           0 :         }
    2442           1 :         return pendingOutputs, nil
    2443             : }
    2444             : 
    2445             : type compactionOutput struct {
    2446             :         meta    *fileMetadata
    2447             :         isLocal bool
    2448             : }
    2449             : 
    2450             : func (d *DB) runDeleteOnlyCompaction(
    2451             :         jobID JobID, c *compaction,
    2452           1 : ) (ve *versionEdit, pendingOutputs []compactionOutput, stats compactStats, retErr error) {
    2453           1 :         c.metrics = make(map[int]*LevelMetrics, len(c.inputs))
    2454           1 :         ve = &versionEdit{
    2455           1 :                 DeletedFiles: map[deletedFileEntry]*fileMetadata{},
    2456           1 :         }
    2457           1 :         for _, cl := range c.inputs {
    2458           1 :                 levelMetrics := &LevelMetrics{}
    2459           1 :                 iter := cl.files.Iter()
    2460           1 :                 for f := iter.First(); f != nil; f = iter.Next() {
    2461           1 :                         ve.DeletedFiles[deletedFileEntry{
    2462           1 :                                 Level:   cl.level,
    2463           1 :                                 FileNum: f.FileNum,
    2464           1 :                         }] = f
    2465           1 :                 }
    2466           1 :                 c.metrics[cl.level] = levelMetrics
    2467             :         }
    2468           1 :         return ve, nil, stats, nil
    2469             : }
    2470             : 
    2471             : func (d *DB) runMoveOrCopyCompaction(
    2472             :         jobID JobID, c *compaction,
    2473           1 : ) (ve *versionEdit, pendingOutputs []compactionOutput, stats compactStats, _ error) {
    2474           1 :         iter := c.startLevel.files.Iter()
    2475           1 :         meta := iter.First()
    2476           1 :         if invariants.Enabled {
    2477           1 :                 if iter.Next() != nil {
    2478           0 :                         panic("got more than one file for a move or copy compaction")
    2479             :                 }
    2480             :         }
    2481           1 :         if c.cancel.Load() {
    2482           0 :                 return ve, nil, stats, ErrCancelledCompaction
    2483           0 :         }
    2484           1 :         objMeta, err := d.objProvider.Lookup(fileTypeTable, meta.FileBacking.DiskFileNum)
    2485           1 :         if err != nil {
    2486           0 :                 return ve, pendingOutputs, stats, err
    2487           0 :         }
    2488           1 :         c.metrics = map[int]*LevelMetrics{
    2489           1 :                 c.outputLevel.level: {
    2490           1 :                         BytesMoved:  meta.Size,
    2491           1 :                         TablesMoved: 1,
    2492           1 :                 },
    2493           1 :         }
    2494           1 :         ve = &versionEdit{
    2495           1 :                 DeletedFiles: map[deletedFileEntry]*fileMetadata{
    2496           1 :                         {Level: c.startLevel.level, FileNum: meta.FileNum}: meta,
    2497           1 :                 },
    2498           1 :                 NewFiles: []newFileEntry{
    2499           1 :                         {Level: c.outputLevel.level, Meta: meta},
    2500           1 :                 },
    2501           1 :         }
    2502           1 :         if c.kind == compactionKindMove {
    2503           1 :                 return ve, nil, stats, nil
    2504           1 :         }
    2505             : 
    2506           1 :         pendingOutputs, err = d.runCopyCompaction(jobID, c, meta, objMeta, ve)
    2507           1 :         return ve, pendingOutputs, stats, err
    2508             : }
    2509             : 
    2510             : // runCompaction runs a compaction that produces new on-disk tables from
    2511             : // memtables or old on-disk tables.
    2512             : //
    2513             : // runCompaction cannot be used for compactionKindIngestedFlushable.
    2514             : //
    2515             : // d.mu must be held when calling this, but the mutex may be dropped and
    2516             : // re-acquired during the course of this method.
    2517             : func (d *DB) runCompaction(
    2518             :         jobID JobID, c *compaction,
    2519           1 : ) (ve *versionEdit, pendingOutputs []compactionOutput, stats compactStats, retErr error) {
    2520           1 :         switch c.kind {
    2521           1 :         case compactionKindDeleteOnly:
    2522           1 :                 return d.runDeleteOnlyCompaction(jobID, c)
    2523           1 :         case compactionKindMove, compactionKindCopy:
    2524           1 :                 return d.runMoveOrCopyCompaction(jobID, c)
    2525           0 :         case compactionKindIngestedFlushable:
    2526           0 :                 panic("pebble: runCompaction cannot handle compactionKindIngestedFlushable.")
    2527             :         }
    2528             : 
    2529           1 :         defer func() {
    2530           1 :                 if retErr != nil {
    2531           1 :                         pendingOutputs = nil
    2532           1 :                 }
    2533             :         }()
    2534             : 
    2535           1 :         snapshots := d.mu.snapshots.toSlice()
    2536           1 :         formatVers := d.FormatMajorVersion()
    2537           1 : 
    2538           1 :         if c.flushing == nil {
    2539           1 :                 // Before dropping the db mutex, grab a ref to the current version. This
    2540           1 :                 // prevents any concurrent excises from deleting files that this compaction
    2541           1 :                 // needs to read/maintain a reference to.
    2542           1 :                 //
    2543           1 :                 // Note that unlike user iterators, compactionIter does not maintain a ref
    2544           1 :                 // of the version or read state.
    2545           1 :                 vers := d.mu.versions.currentVersion()
    2546           1 :                 vers.Ref()
    2547           1 :                 defer vers.UnrefLocked()
    2548           1 :         }
    2549             : 
    2550           1 :         if c.cancel.Load() {
    2551           0 :                 return ve, nil, stats, ErrCancelledCompaction
    2552           0 :         }
    2553             : 
    2554             :         // Release the d.mu lock while doing I/O.
    2555             :         // Note the unusual order: Unlock and then Lock.
    2556           1 :         d.mu.Unlock()
    2557           1 :         defer d.mu.Lock()
    2558           1 : 
    2559           1 :         // Compactions use a pool of buffers to read blocks, avoiding polluting the
    2560           1 :         // block cache with blocks that will not be read again. We initialize the
    2561           1 :         // buffer pool with a size 12. This initial size does not need to be
    2562           1 :         // accurate, because the pool will grow to accommodate the maximum number of
    2563           1 :         // blocks allocated at a given time over the course of the compaction. But
    2564           1 :         // choosing a size larger than that working set avoids any additional
    2565           1 :         // allocations to grow the size of the pool over the course of iteration.
    2566           1 :         //
    2567           1 :         // Justification for initial size 12: In a two-level compaction, at any
    2568           1 :         // given moment we'll have 2 index blocks in-use and 2 data blocks in-use.
    2569           1 :         // Additionally, when decoding a compressed block, we'll temporarily
    2570           1 :         // allocate 1 additional block to hold the compressed buffer. In the worst
    2571           1 :         // case that all input sstables have two-level index blocks (+2), value
    2572           1 :         // blocks (+2), range deletion blocks (+n) and range key blocks (+n), we'll
    2573           1 :         // additionally require 2n+4 blocks where n is the number of input sstables.
    2574           1 :         // Range deletion and range key blocks are relatively rare, and the cost of
    2575           1 :         // an additional allocation or two over the course of the compaction is
    2576           1 :         // considered to be okay. A larger initial size would cause the pool to hold
    2577           1 :         // on to more memory, even when it's not in-use because the pool will
    2578           1 :         // recycle buffers up to the current capacity of the pool. The memory use of
    2579           1 :         // a 12-buffer pool is expected to be within reason, even if all the buffers
    2580           1 :         // grow to the typical size of an index block (256 KiB) which would
    2581           1 :         // translate to 3 MiB per compaction.
    2582           1 :         c.bufferPool.Init(12)
    2583           1 :         defer c.bufferPool.Release()
    2584           1 : 
    2585           1 :         iiter, err := c.newInputIter(d.newIters, d.tableNewRangeKeyIter)
    2586           1 :         if err != nil {
    2587           0 :                 return nil, pendingOutputs, stats, err
    2588           0 :         }
    2589           1 :         c.allowedZeroSeqNum = c.allowZeroSeqNum()
    2590           1 :         iiter = invalidating.MaybeWrapIfInvariants(iiter)
    2591           1 :         cfg := compact.IterConfig{
    2592           1 :                 Cmp:                                    c.cmp,
    2593           1 :                 Equal:                                  c.equal,
    2594           1 :                 Merge:                                  d.merge,
    2595           1 :                 TombstoneElision:                       c.delElision,
    2596           1 :                 RangeKeyElision:                        c.rangeKeyElision,
    2597           1 :                 Snapshots:                              snapshots,
    2598           1 :                 AllowZeroSeqNum:                        c.allowedZeroSeqNum,
    2599           1 :                 IneffectualSingleDeleteCallback:        d.opts.Experimental.IneffectualSingleDeleteCallback,
    2600           1 :                 SingleDeleteInvariantViolationCallback: d.opts.Experimental.SingleDeleteInvariantViolationCallback,
    2601           1 :         }
    2602           1 :         iter := compact.NewIter(cfg, iiter)
    2603           1 : 
    2604           1 :         var (
    2605           1 :                 createdFiles    []base.DiskFileNum
    2606           1 :                 tw              *sstable.Writer
    2607           1 :                 pinnedKeySize   uint64
    2608           1 :                 pinnedValueSize uint64
    2609           1 :                 pinnedCount     uint64
    2610           1 :         )
    2611           1 :         defer func() {
    2612           1 :                 if iter != nil {
    2613           1 :                         retErr = firstError(retErr, iter.Close())
    2614           1 :                 }
    2615           1 :                 if tw != nil {
    2616           0 :                         retErr = firstError(retErr, tw.Close())
    2617           0 :                 }
    2618           1 :                 if retErr != nil {
    2619           1 :                         for _, fileNum := range createdFiles {
    2620           1 :                                 _ = d.objProvider.Remove(fileTypeTable, fileNum)
    2621           1 :                         }
    2622             :                 }
    2623           1 :                 for _, closer := range c.closers {
    2624           1 :                         retErr = firstError(retErr, closer.Close())
    2625           1 :                 }
    2626             :         }()
    2627             : 
    2628           1 :         ve = &versionEdit{
    2629           1 :                 DeletedFiles: map[deletedFileEntry]*fileMetadata{},
    2630           1 :         }
    2631           1 : 
    2632           1 :         startLevelBytes := c.startLevel.files.SizeSum()
    2633           1 :         outputMetrics := &LevelMetrics{
    2634           1 :                 BytesIn:   startLevelBytes,
    2635           1 :                 BytesRead: c.outputLevel.files.SizeSum(),
    2636           1 :         }
    2637           1 :         if len(c.extraLevels) > 0 {
    2638           1 :                 outputMetrics.BytesIn += c.extraLevels[0].files.SizeSum()
    2639           1 :         }
    2640           1 :         outputMetrics.BytesRead += outputMetrics.BytesIn
    2641           1 : 
    2642           1 :         c.metrics = map[int]*LevelMetrics{
    2643           1 :                 c.outputLevel.level: outputMetrics,
    2644           1 :         }
    2645           1 :         if len(c.flushing) == 0 && c.metrics[c.startLevel.level] == nil {
    2646           1 :                 c.metrics[c.startLevel.level] = &LevelMetrics{}
    2647           1 :         }
    2648           1 :         if len(c.extraLevels) > 0 {
    2649           1 :                 c.metrics[c.extraLevels[0].level] = &LevelMetrics{}
    2650           1 :                 outputMetrics.MultiLevel.BytesInTop = startLevelBytes
    2651           1 :                 outputMetrics.MultiLevel.BytesIn = outputMetrics.BytesIn
    2652           1 :                 outputMetrics.MultiLevel.BytesRead = outputMetrics.BytesRead
    2653           1 :         }
    2654             : 
    2655             :         // The table is typically written at the maximum allowable format implied by
    2656             :         // the current format major version of the DB.
    2657           1 :         tableFormat := formatVers.MaxTableFormat()
    2658           1 : 
    2659           1 :         // In format major versions with maximum table formats of Pebblev3, value
    2660           1 :         // blocks were conditional on an experimental setting. In format major
    2661           1 :         // versions with maximum table formats of Pebblev4 and higher, value blocks
    2662           1 :         // are always enabled.
    2663           1 :         if tableFormat == sstable.TableFormatPebblev3 &&
    2664           1 :                 (d.opts.Experimental.EnableValueBlocks == nil || !d.opts.Experimental.EnableValueBlocks()) {
    2665           1 :                 tableFormat = sstable.TableFormatPebblev2
    2666           1 :         }
    2667             : 
    2668           1 :         writerOpts := d.opts.MakeWriterOptions(c.outputLevel.level, tableFormat)
    2669           1 : 
    2670           1 :         // prevPointKey is a sstable.WriterOption that provides access to
    2671           1 :         // the last point key written to a writer's sstable. When a new
    2672           1 :         // output begins in newOutput, prevPointKey is updated to point to
    2673           1 :         // the new output's sstable.Writer. This allows the compaction loop
    2674           1 :         // to access the last written point key without requiring the
    2675           1 :         // compaction loop to make a copy of each key ahead of time. Users
    2676           1 :         // must be careful, because the byte slice returned by UnsafeKey
    2677           1 :         // points directly into the Writer's block buffer.
    2678           1 :         var cpuWorkHandle CPUWorkHandle
    2679           1 :         defer func() {
    2680           1 :                 if cpuWorkHandle != nil {
    2681           1 :                         d.opts.Experimental.CPUWorkPermissionGranter.CPUWorkDone(cpuWorkHandle)
    2682           1 :                 }
    2683             :         }()
    2684             : 
    2685           1 :         newOutput := func() error {
    2686           1 :                 // Check if we've been cancelled by a concurrent operation.
    2687           1 :                 if c.cancel.Load() {
    2688           0 :                         return ErrCancelledCompaction
    2689           0 :                 }
    2690           1 :                 d.mu.Lock()
    2691           1 :                 fileNum := d.mu.versions.getNextFileNum()
    2692           1 :                 d.mu.Unlock()
    2693           1 : 
    2694           1 :                 ctx := context.TODO()
    2695           1 :                 if objiotracing.Enabled {
    2696           0 :                         ctx = objiotracing.WithLevel(ctx, c.outputLevel.level)
    2697           0 :                         switch c.kind {
    2698           0 :                         case compactionKindFlush:
    2699           0 :                                 ctx = objiotracing.WithReason(ctx, objiotracing.ForFlush)
    2700           0 :                         default:
    2701           0 :                                 ctx = objiotracing.WithReason(ctx, objiotracing.ForCompaction)
    2702             :                         }
    2703             :                 }
    2704           1 :                 var writeCategory vfs.DiskWriteCategory
    2705           1 :                 switch c.kind {
    2706           1 :                 case compactionKindFlush:
    2707           1 :                         if d.opts.EnableSQLRowSpillMetrics {
    2708           0 :                                 // In the scenario that the Pebble engine is used for SQL row spills the data written to
    2709           0 :                                 // the memtable will correspond to spills to disk and should be categorized as such.
    2710           0 :                                 writeCategory = "sql-row-spill"
    2711           1 :                         } else {
    2712           1 :                                 writeCategory = "pebble-memtable-flush"
    2713           1 :                         }
    2714           1 :                 default:
    2715           1 :                         writeCategory = "pebble-compaction"
    2716             :                 }
    2717             :                 // Prefer shared storage if present.
    2718           1 :                 createOpts := objstorage.CreateOptions{
    2719           1 :                         PreferSharedStorage: remote.ShouldCreateShared(d.opts.Experimental.CreateOnShared, c.outputLevel.level),
    2720           1 :                         WriteCategory:       writeCategory,
    2721           1 :                 }
    2722           1 :                 diskFileNum := base.PhysicalTableDiskFileNum(fileNum)
    2723           1 :                 writable, objMeta, err := d.objProvider.Create(ctx, fileTypeTable, diskFileNum, createOpts)
    2724           1 :                 if err != nil {
    2725           1 :                         return err
    2726           1 :                 }
    2727           1 :                 fileMeta := &fileMetadata{}
    2728           1 :                 fileMeta.FileNum = fileNum
    2729           1 :                 pendingOutputs = append(pendingOutputs, compactionOutput{
    2730           1 :                         meta:    fileMeta.PhysicalMeta().FileMetadata,
    2731           1 :                         isLocal: !objMeta.IsRemote(),
    2732           1 :                 })
    2733           1 : 
    2734           1 :                 reason := "flushing"
    2735           1 :                 if c.flushing == nil {
    2736           1 :                         reason = "compacting"
    2737           1 :                 }
    2738           1 :                 d.opts.EventListener.TableCreated(TableCreateInfo{
    2739           1 :                         JobID:   int(jobID),
    2740           1 :                         Reason:  reason,
    2741           1 :                         Path:    d.objProvider.Path(objMeta),
    2742           1 :                         FileNum: diskFileNum,
    2743           1 :                 })
    2744           1 :                 if c.kind != compactionKindFlush {
    2745           1 :                         writable = &compactionWritable{
    2746           1 :                                 Writable: writable,
    2747           1 :                                 versions: d.mu.versions,
    2748           1 :                                 written:  &c.bytesWritten,
    2749           1 :                         }
    2750           1 :                 }
    2751           1 :                 createdFiles = append(createdFiles, diskFileNum)
    2752           1 :                 cacheOpts := private.SSTableCacheOpts(d.cacheID, diskFileNum).(sstable.WriterOption)
    2753           1 : 
    2754           1 :                 const MaxFileWriteAdditionalCPUTime = time.Millisecond * 100
    2755           1 :                 cpuWorkHandle = d.opts.Experimental.CPUWorkPermissionGranter.GetPermission(
    2756           1 :                         MaxFileWriteAdditionalCPUTime,
    2757           1 :                 )
    2758           1 :                 writerOpts.Parallelism =
    2759           1 :                         d.opts.Experimental.MaxWriterConcurrency > 0 &&
    2760           1 :                                 (cpuWorkHandle.Permitted() || d.opts.Experimental.ForceWriterParallelism)
    2761           1 : 
    2762           1 :                 tw = sstable.NewWriter(writable, writerOpts, cacheOpts)
    2763           1 : 
    2764           1 :                 fileMeta.CreationTime = time.Now().Unix()
    2765           1 :                 ve.NewFiles = append(ve.NewFiles, newFileEntry{
    2766           1 :                         Level: c.outputLevel.level,
    2767           1 :                         Meta:  fileMeta,
    2768           1 :                 })
    2769           1 :                 return nil
    2770             :         }
    2771             : 
    2772             :         // splitL0Outputs is true during flushes and intra-L0 compactions with flush
    2773             :         // splits enabled.
    2774           1 :         splitL0Outputs := c.outputLevel.level == 0 && d.opts.FlushSplitBytes > 0
    2775           1 : 
    2776           1 :         // finishOutput is called with the a user key up to which all tombstones
    2777           1 :         // should be flushed. Typically, this is the first key of the next
    2778           1 :         // sstable or an empty key if this output is the final sstable.
    2779           1 :         finishOutput := func(splitKey []byte) error {
    2780           1 :                 // If we haven't output any point records to the sstable (tw == nil) then the
    2781           1 :                 // sstable will only contain range tombstones and/or range keys. The smallest
    2782           1 :                 // key in the sstable will be the start key of the first range tombstone or
    2783           1 :                 // range key added. We need to ensure that this start key is distinct from
    2784           1 :                 // the splitKey passed to finishOutput (if set), otherwise we would generate
    2785           1 :                 // an sstable where the largest key is smaller than the smallest key due to
    2786           1 :                 // how the largest key boundary is set below. NB: It is permissible for the
    2787           1 :                 // range tombstone / range key start key to be nil.
    2788           1 :                 //
    2789           1 :                 // TODO: It is unfortunate that we have to do this check here rather than
    2790           1 :                 // when we decide to finish the sstable in the runCompaction loop. A better
    2791           1 :                 // structure currently eludes us.
    2792           1 :                 if tw == nil {
    2793           1 :                         startKey := iter.FirstTombstoneStart()
    2794           1 :                         if startKey == nil {
    2795           1 :                                 startKey = iter.FirstRangeKeyStart()
    2796           1 :                         }
    2797           1 :                         if splitKey != nil && d.cmp(startKey, splitKey) == 0 {
    2798           0 :                                 return nil
    2799           0 :                         }
    2800             :                 }
    2801             : 
    2802           1 :                 for _, v := range iter.TombstonesUpTo(splitKey) {
    2803           1 :                         if tw == nil {
    2804           1 :                                 if err := newOutput(); err != nil {
    2805           0 :                                         return err
    2806           0 :                                 }
    2807             :                         }
    2808             :                         // The tombstone being added could be completely outside the
    2809             :                         // eventual bounds of the sstable. Consider this example (bounds
    2810             :                         // in square brackets next to table filename):
    2811             :                         //
    2812             :                         // ./000240.sst   [tmgc#391,MERGE-tmgc#391,MERGE]
    2813             :                         // tmgc#391,MERGE [786e627a]
    2814             :                         // tmgc-udkatvs#331,RANGEDEL
    2815             :                         //
    2816             :                         // ./000241.sst   [tmgc#384,MERGE-tmgc#384,MERGE]
    2817             :                         // tmgc#384,MERGE [666c7070]
    2818             :                         // tmgc-tvsalezade#383,RANGEDEL
    2819             :                         // tmgc-tvsalezade#331,RANGEDEL
    2820             :                         //
    2821             :                         // ./000242.sst   [tmgc#383,RANGEDEL-tvsalezade#72057594037927935,RANGEDEL]
    2822             :                         // tmgc-tvsalezade#383,RANGEDEL
    2823             :                         // tmgc#375,SET [72646c78766965616c72776865676e79]
    2824             :                         // tmgc-tvsalezade#356,RANGEDEL
    2825             :                         //
    2826             :                         // Note that both of the top two SSTables have range tombstones
    2827             :                         // that start after the file's end keys. Since the file bound
    2828             :                         // computation happens well after all range tombstones have been
    2829             :                         // added to the writer, eliding out-of-file range tombstones based
    2830             :                         // on sequence number at this stage is difficult, and necessitates
    2831             :                         // read-time logic to ignore range tombstones outside file bounds.
    2832           1 :                         if err := rangedel.Encode(&v, tw.Add); err != nil {
    2833           0 :                                 return err
    2834           0 :                         }
    2835             :                 }
    2836           1 :                 for _, v := range iter.RangeKeysUpTo(splitKey) {
    2837           1 :                         // Same logic as for range tombstones, except added using tw.AddRangeKey.
    2838           1 :                         if tw == nil {
    2839           1 :                                 if err := newOutput(); err != nil {
    2840           0 :                                         return err
    2841           0 :                                 }
    2842             :                         }
    2843           1 :                         if err := rangekey.Encode(&v, tw.AddRangeKey); err != nil {
    2844           0 :                                 return err
    2845           0 :                         }
    2846             :                 }
    2847             : 
    2848           1 :                 if tw == nil {
    2849           1 :                         return nil
    2850           1 :                 }
    2851           1 :                 {
    2852           1 :                         // Set internal sstable properties.
    2853           1 :                         p := getInternalWriterProperties(tw)
    2854           1 :                         // Set the snapshot pinned totals.
    2855           1 :                         p.SnapshotPinnedKeys = pinnedCount
    2856           1 :                         p.SnapshotPinnedKeySize = pinnedKeySize
    2857           1 :                         p.SnapshotPinnedValueSize = pinnedValueSize
    2858           1 :                         stats.cumulativePinnedKeys += pinnedCount
    2859           1 :                         stats.cumulativePinnedSize += pinnedKeySize + pinnedValueSize
    2860           1 :                         pinnedCount = 0
    2861           1 :                         pinnedKeySize = 0
    2862           1 :                         pinnedValueSize = 0
    2863           1 :                 }
    2864           1 :                 if err := tw.Close(); err != nil {
    2865           1 :                         tw = nil
    2866           1 :                         return err
    2867           1 :                 }
    2868           1 :                 d.opts.Experimental.CPUWorkPermissionGranter.CPUWorkDone(cpuWorkHandle)
    2869           1 :                 cpuWorkHandle = nil
    2870           1 :                 writerMeta, err := tw.Metadata()
    2871           1 :                 if err != nil {
    2872           0 :                         tw = nil
    2873           0 :                         return err
    2874           0 :                 }
    2875           1 :                 tw = nil
    2876           1 :                 meta := ve.NewFiles[len(ve.NewFiles)-1].Meta
    2877           1 :                 meta.Size = writerMeta.Size
    2878           1 :                 meta.SmallestSeqNum = writerMeta.SmallestSeqNum
    2879           1 :                 meta.LargestSeqNum = writerMeta.LargestSeqNum
    2880           1 :                 meta.InitPhysicalBacking()
    2881           1 : 
    2882           1 :                 // If the file didn't contain any range deletions, we can fill its
    2883           1 :                 // table stats now, avoiding unnecessarily loading the table later.
    2884           1 :                 maybeSetStatsFromProperties(
    2885           1 :                         meta.PhysicalMeta(), &writerMeta.Properties,
    2886           1 :                 )
    2887           1 : 
    2888           1 :                 if c.flushing == nil {
    2889           1 :                         outputMetrics.TablesCompacted++
    2890           1 :                         outputMetrics.BytesCompacted += meta.Size
    2891           1 :                 } else {
    2892           1 :                         outputMetrics.TablesFlushed++
    2893           1 :                         outputMetrics.BytesFlushed += meta.Size
    2894           1 :                 }
    2895           1 :                 outputMetrics.Size += int64(meta.Size)
    2896           1 :                 outputMetrics.NumFiles++
    2897           1 :                 outputMetrics.Additional.BytesWrittenDataBlocks += writerMeta.Properties.DataSize
    2898           1 :                 outputMetrics.Additional.BytesWrittenValueBlocks += writerMeta.Properties.ValueBlocksSize
    2899           1 : 
    2900           1 :                 if n := len(ve.NewFiles); n > 1 {
    2901           1 :                         // This is not the first output file. Ensure the sstable boundaries
    2902           1 :                         // are nonoverlapping.
    2903           1 :                         prevMeta := ve.NewFiles[n-2].Meta
    2904           1 :                         if writerMeta.SmallestRangeDel.UserKey != nil {
    2905           1 :                                 c := d.cmp(writerMeta.SmallestRangeDel.UserKey, prevMeta.Largest.UserKey)
    2906           1 :                                 if c < 0 {
    2907           0 :                                         return errors.Errorf(
    2908           0 :                                                 "pebble: smallest range tombstone start key is less than previous sstable largest key: %s < %s",
    2909           0 :                                                 writerMeta.SmallestRangeDel.Pretty(d.opts.Comparer.FormatKey),
    2910           0 :                                                 prevMeta.Largest.Pretty(d.opts.Comparer.FormatKey))
    2911           1 :                                 } else if c == 0 && !prevMeta.Largest.IsExclusiveSentinel() {
    2912           0 :                                         // The user key portion of the range boundary start key is
    2913           0 :                                         // equal to the previous table's largest key user key, and
    2914           0 :                                         // the previous table's largest key is not exclusive. This
    2915           0 :                                         // violates the invariant that tables are key-space
    2916           0 :                                         // partitioned.
    2917           0 :                                         return errors.Errorf(
    2918           0 :                                                 "pebble: invariant violation: previous sstable largest key %s, current sstable smallest rangedel: %s",
    2919           0 :                                                 prevMeta.Largest.Pretty(d.opts.Comparer.FormatKey),
    2920           0 :                                                 writerMeta.SmallestRangeDel.Pretty(d.opts.Comparer.FormatKey),
    2921           0 :                                         )
    2922           0 :                                 }
    2923             :                         }
    2924             :                 }
    2925             : 
    2926             :                 // Verify that all range deletions outputted to the sstable are
    2927             :                 // truncated to split key.
    2928           1 :                 if splitKey != nil && writerMeta.LargestRangeDel.UserKey != nil &&
    2929           1 :                         d.cmp(writerMeta.LargestRangeDel.UserKey, splitKey) > 0 {
    2930           0 :                         return errors.Errorf(
    2931           0 :                                 "pebble: invariant violation: rangedel largest key %q extends beyond split key %q",
    2932           0 :                                 writerMeta.LargestRangeDel.Pretty(d.opts.Comparer.FormatKey),
    2933           0 :                                 d.opts.Comparer.FormatKey(splitKey),
    2934           0 :                         )
    2935           0 :                 }
    2936             : 
    2937           1 :                 if writerMeta.HasPointKeys {
    2938           1 :                         meta.ExtendPointKeyBounds(d.cmp, writerMeta.SmallestPoint, writerMeta.LargestPoint)
    2939           1 :                 }
    2940           1 :                 if writerMeta.HasRangeDelKeys {
    2941           1 :                         meta.ExtendPointKeyBounds(d.cmp, writerMeta.SmallestRangeDel, writerMeta.LargestRangeDel)
    2942           1 :                 }
    2943           1 :                 if writerMeta.HasRangeKeys {
    2944           1 :                         meta.ExtendRangeKeyBounds(d.cmp, writerMeta.SmallestRangeKey, writerMeta.LargestRangeKey)
    2945           1 :                 }
    2946             : 
    2947             :                 // Verify that the sstable bounds fall within the compaction input
    2948             :                 // bounds. This is a sanity check that we don't have a logic error
    2949             :                 // elsewhere that causes the sstable bounds to accidentally expand past the
    2950             :                 // compaction input bounds as doing so could lead to various badness such
    2951             :                 // as keys being deleted by a range tombstone incorrectly.
    2952           1 :                 if c.smallest.UserKey != nil {
    2953           1 :                         switch v := d.cmp(meta.Smallest.UserKey, c.smallest.UserKey); {
    2954           1 :                         case v >= 0:
    2955             :                                 // Nothing to do.
    2956           0 :                         case v < 0:
    2957           0 :                                 return errors.Errorf("pebble: compaction output grew beyond bounds of input: %s < %s",
    2958           0 :                                         meta.Smallest.Pretty(d.opts.Comparer.FormatKey),
    2959           0 :                                         c.smallest.Pretty(d.opts.Comparer.FormatKey))
    2960             :                         }
    2961             :                 }
    2962           1 :                 if c.largest.UserKey != nil {
    2963           1 :                         switch v := d.cmp(meta.Largest.UserKey, c.largest.UserKey); {
    2964           1 :                         case v <= 0:
    2965             :                                 // Nothing to do.
    2966           0 :                         case v > 0:
    2967           0 :                                 return errors.Errorf("pebble: compaction output grew beyond bounds of input: %s > %s",
    2968           0 :                                         meta.Largest.Pretty(d.opts.Comparer.FormatKey),
    2969           0 :                                         c.largest.Pretty(d.opts.Comparer.FormatKey))
    2970             :                         }
    2971             :                 }
    2972             :                 // Verify that we never split different revisions of the same user key
    2973             :                 // across two different sstables.
    2974           1 :                 if err := c.errorOnUserKeyOverlap(ve); err != nil {
    2975           0 :                         return err
    2976           0 :                 }
    2977           1 :                 if err := meta.Validate(d.cmp, d.opts.Comparer.FormatKey); err != nil {
    2978           0 :                         return err
    2979           0 :                 }
    2980           1 :                 return nil
    2981             :         }
    2982             : 
    2983             :         // Build a compactionOutputSplitter that contains all logic to determine
    2984             :         // whether the compaction loop should stop writing to one output sstable and
    2985             :         // switch to a new one. Some splitters can wrap other splitters, and the
    2986             :         // splitterGroup can be composed of multiple splitters. In this case, we
    2987             :         // start off with splitters for file sizes, grandparent limits, and (for L0
    2988             :         // splits) L0 limits, before wrapping them in an splitterGroup.
    2989           1 :         unsafePrevUserKey := func() []byte {
    2990           1 :                 // Return the largest point key written to tw or the start of
    2991           1 :                 // the current range deletion in the fragmenter, whichever is
    2992           1 :                 // greater.
    2993           1 :                 prevPoint := tw.UnsafeLastPointKey()
    2994           1 :                 if c.cmp(prevPoint.UserKey, iter.FirstTombstoneStart()) > 0 {
    2995           1 :                         return prevPoint.UserKey
    2996           1 :                 }
    2997           1 :                 return iter.FirstTombstoneStart()
    2998             :         }
    2999           1 :         outputSplitters := []compact.OutputSplitter{
    3000           1 :                 // We do not split the same user key across different sstables within
    3001           1 :                 // one flush or compaction. The FileSizeSplitter may request a split in
    3002           1 :                 // the middle of a user key, so PreventSplitUserKeys ensures we are at a
    3003           1 :                 // user key change boundary when doing a split.
    3004           1 :                 compact.PreventSplitUserKeys(
    3005           1 :                         c.cmp,
    3006           1 :                         compact.FileSizeSplitter(iter.Frontiers(), c.maxOutputFileSize, c.grandparents.Iter()),
    3007           1 :                         unsafePrevUserKey,
    3008           1 :                 ),
    3009           1 :                 compact.LimitFuncSplitter(iter.Frontiers(), c.findGrandparentLimit),
    3010           1 :         }
    3011           1 :         if splitL0Outputs {
    3012           1 :                 outputSplitters = append(outputSplitters, compact.LimitFuncSplitter(iter.Frontiers(), c.findL0Limit))
    3013           1 :         }
    3014           1 :         splitter := compact.CombineSplitters(c.cmp, outputSplitters...)
    3015           1 : 
    3016           1 :         // Each outer loop iteration produces one output file. An iteration that
    3017           1 :         // produces a file containing point keys (and optionally range tombstones)
    3018           1 :         // guarantees that the input iterator advanced. An iteration that produces
    3019           1 :         // a file containing only range tombstones guarantees the limit passed to
    3020           1 :         // `finishOutput()` advanced to a strictly greater user key corresponding
    3021           1 :         // to a grandparent file largest key, or nil. Taken together, these
    3022           1 :         // progress guarantees ensure that eventually the input iterator will be
    3023           1 :         // exhausted and the range tombstone fragments will all be flushed.
    3024           1 :         for key, val := iter.First(); key != nil || iter.FirstTombstoneStart() != nil || iter.FirstRangeKeyStart() != nil; {
    3025           1 :                 var firstKey []byte
    3026           1 :                 if key != nil {
    3027           1 :                         firstKey = key.UserKey
    3028           1 :                 } else if startKey := iter.FirstTombstoneStart(); startKey != nil {
    3029           1 :                         // Pass the start key of the first pending tombstone to find the
    3030           1 :                         // next limit. All pending tombstones have the same start key. We
    3031           1 :                         // use this as opposed to the end key of the last written sstable to
    3032           1 :                         // effectively handle cases like these:
    3033           1 :                         //
    3034           1 :                         // a.SET.3
    3035           1 :                         // (lf.limit at b)
    3036           1 :                         // d.RANGEDEL.4:f
    3037           1 :                         //
    3038           1 :                         // In this case, the partition after b has only range deletions, so
    3039           1 :                         // if we were to find the limit after the last written key at the
    3040           1 :                         // split point (key a), we'd get the limit b again, and
    3041           1 :                         // finishOutput() would not advance any further because the next
    3042           1 :                         // range tombstone to write does not start until after the L0 split
    3043           1 :                         // point.
    3044           1 :                         firstKey = startKey
    3045           1 :                 }
    3046           1 :                 splitterSuggestion := splitter.OnNewOutput(firstKey)
    3047           1 : 
    3048           1 :                 // Each inner loop iteration processes one key from the input iterator.
    3049           1 :                 for ; key != nil; key, val = iter.Next() {
    3050           1 :                         if split := splitter.ShouldSplitBefore(key, tw); split == compact.SplitNow {
    3051           1 :                                 break
    3052             :                         }
    3053             : 
    3054           1 :                         switch key.Kind() {
    3055           1 :                         case InternalKeyKindRangeDelete:
    3056           1 :                                 // Range tombstones are handled specially. They are not written until
    3057           1 :                                 // later during `finishOutput()`. We add them to the compaction iterator
    3058           1 :                                 // so covered keys in the same snapshot stripe can be elided.
    3059           1 :                                 //
    3060           1 :                                 // Since the keys' Suffix and Value fields are not deep cloned, the
    3061           1 :                                 // underlying blockIter must be kept open for the lifetime of the
    3062           1 :                                 // compaction.
    3063           1 :                                 iter.AddTombstoneSpan(c.rangeDelInterleaving.Span())
    3064           1 :                                 continue
    3065           1 :                         case InternalKeyKindRangeKeySet, InternalKeyKindRangeKeyUnset, InternalKeyKindRangeKeyDelete:
    3066           1 :                                 // Range keys are handled in the same way as range tombstones.
    3067           1 :                                 // Since the keys' Suffix and Value fields are not deep cloned, the
    3068           1 :                                 // underlying blockIter must be kept open for the lifetime of the
    3069           1 :                                 // compaction.
    3070           1 :                                 iter.AddRangeKeySpan(c.rangeKeyInterleaving.Span())
    3071           1 :                                 continue
    3072             :                         }
    3073           1 :                         if tw == nil {
    3074           1 :                                 if err := newOutput(); err != nil {
    3075           1 :                                         return nil, pendingOutputs, stats, err
    3076           1 :                                 }
    3077             :                         }
    3078           1 :                         if err := tw.AddWithForceObsolete(*key, val, iter.ForceObsoleteDueToRangeDel()); err != nil {
    3079           0 :                                 return nil, pendingOutputs, stats, err
    3080           0 :                         }
    3081           1 :                         if iter.SnapshotPinned() {
    3082           1 :                                 // The kv pair we just added to the sstable was only surfaced by
    3083           1 :                                 // the compaction iterator because an open snapshot prevented
    3084           1 :                                 // its elision. Increment the stats.
    3085           1 :                                 pinnedCount++
    3086           1 :                                 pinnedKeySize += uint64(len(key.UserKey)) + base.InternalTrailerLen
    3087           1 :                                 pinnedValueSize += uint64(len(val))
    3088           1 :                         }
    3089             :                 }
    3090             : 
    3091             :                 // A splitter requested a split, and we're ready to finish the output.
    3092             :                 // We need to choose the key at which to split any pending range
    3093             :                 // tombstones. There are two options:
    3094             :                 // 1. splitterSuggestion — The key suggested by the splitter. This key
    3095             :                 //    is guaranteed to be greater than the last key written to the
    3096             :                 //    current output.
    3097             :                 // 2. key.UserKey — the first key of the next sstable output. This user
    3098             :                 //     key is also guaranteed to be greater than the last user key
    3099             :                 //     written to the current output (see userKeyChangeSplitter).
    3100             :                 //
    3101             :                 // Use whichever is smaller. Using the smaller of the two limits
    3102             :                 // overlap with grandparents. Consider the case where the
    3103             :                 // grandparent limit is calculated to be 'b', key is 'x', and
    3104             :                 // there exist many sstables between 'b' and 'x'. If the range
    3105             :                 // deletion fragmenter has a pending tombstone [a,x), splitting
    3106             :                 // at 'x' would cause the output table to overlap many
    3107             :                 // grandparents well beyond the calculated grandparent limit
    3108             :                 // 'b'. Splitting at the smaller `splitterSuggestion` avoids
    3109             :                 // this unbounded overlap with grandparent tables.
    3110           1 :                 splitKey := splitterSuggestion
    3111           1 :                 if key != nil && (splitKey == nil || c.cmp(splitKey, key.UserKey) > 0) {
    3112           1 :                         splitKey = key.UserKey
    3113           1 :                 }
    3114           1 :                 if err := finishOutput(splitKey); err != nil {
    3115           1 :                         return nil, pendingOutputs, stats, err
    3116           1 :                 }
    3117             :         }
    3118             : 
    3119           1 :         for _, cl := range c.inputs {
    3120           1 :                 iter := cl.files.Iter()
    3121           1 :                 for f := iter.First(); f != nil; f = iter.Next() {
    3122           1 :                         ve.DeletedFiles[deletedFileEntry{
    3123           1 :                                 Level:   cl.level,
    3124           1 :                                 FileNum: f.FileNum,
    3125           1 :                         }] = f
    3126           1 :                 }
    3127             :         }
    3128             : 
    3129             :         // The compaction iterator keeps track of a count of the number of DELSIZED
    3130             :         // keys that encoded an incorrect size. Propagate it up as a part of
    3131             :         // compactStats.
    3132           1 :         stats.countMissizedDels = iter.Stats().CountMissizedDels
    3133           1 : 
    3134           1 :         if err := d.objProvider.Sync(); err != nil {
    3135           0 :                 return nil, pendingOutputs, stats, err
    3136           0 :         }
    3137             : 
    3138             :         // Refresh the disk available statistic whenever a compaction/flush
    3139             :         // completes, before re-acquiring the mutex.
    3140           1 :         _ = d.calculateDiskAvailableBytes()
    3141           1 : 
    3142           1 :         return ve, pendingOutputs, stats, nil
    3143             : }
    3144             : 
    3145             : // validateVersionEdit validates that start and end keys across new and deleted
    3146             : // files in a versionEdit pass the given validation function.
    3147             : func validateVersionEdit(
    3148             :         ve *versionEdit, validateFn func([]byte) error, format base.FormatKey, logger Logger,
    3149           1 : ) {
    3150           1 :         validateKey := func(f *manifest.FileMetadata, key []byte) {
    3151           1 :                 if err := validateFn(key); err != nil {
    3152           1 :                         logger.Fatalf("pebble: version edit validation failed (key=%s file=%s): %v", format(key), f, err)
    3153           1 :                 }
    3154             :         }
    3155             : 
    3156             :         // Validate both new and deleted files.
    3157           1 :         for _, f := range ve.NewFiles {
    3158           1 :                 validateKey(f.Meta, f.Meta.Smallest.UserKey)
    3159           1 :                 validateKey(f.Meta, f.Meta.Largest.UserKey)
    3160           1 :         }
    3161           1 :         for _, m := range ve.DeletedFiles {
    3162           1 :                 validateKey(m, m.Smallest.UserKey)
    3163           1 :                 validateKey(m, m.Largest.UserKey)
    3164           1 :         }
    3165             : }

Generated by: LCOV version 1.14