LCOV - code coverage report
Current view: top level - pebble - table_stats.go (source / functions) Hit Total Coverage
Test: 2024-10-05 08:16Z 649e50ad - meta test only.lcov Lines: 599 665 90.1 %
Date: 2024-10-05 08:16:48 Functions: 0 0 -

          Line data    Source code
       1             : // Copyright 2020 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             :         "context"
       9             :         "fmt"
      10             :         "math"
      11             : 
      12             :         "github.com/cockroachdb/errors"
      13             :         "github.com/cockroachdb/pebble/internal/base"
      14             :         "github.com/cockroachdb/pebble/internal/invariants"
      15             :         "github.com/cockroachdb/pebble/internal/keyspan"
      16             :         "github.com/cockroachdb/pebble/internal/keyspan/keyspanimpl"
      17             :         "github.com/cockroachdb/pebble/internal/manifest"
      18             :         "github.com/cockroachdb/pebble/sstable"
      19             :         "github.com/cockroachdb/pebble/sstable/block"
      20             : )
      21             : 
      22             : // In-memory statistics about tables help inform compaction picking, but may
      23             : // be expensive to calculate or load from disk. Every time a database is
      24             : // opened, these statistics must be reloaded or recalculated. To minimize
      25             : // impact on user activity and compactions, we load these statistics
      26             : // asynchronously in the background and store loaded statistics in each
      27             : // table's *FileMetadata.
      28             : //
      29             : // This file implements the asynchronous loading of statistics by maintaining
      30             : // a list of files that require statistics, alongside their LSM levels.
      31             : // Whenever new files are added to the LSM, the files are appended to
      32             : // d.mu.tableStats.pending. If a stats collection job is not currently
      33             : // running, one is started in a separate goroutine.
      34             : //
      35             : // The stats collection job grabs and clears the pending list, computes table
      36             : // statistics relative to the current readState and updates the tables' file
      37             : // metadata. New pending files may accumulate during a stats collection job,
      38             : // so a completing job triggers a new job if necessary. Only one job runs at a
      39             : // time.
      40             : //
      41             : // When an existing database is opened, all files lack in-memory statistics.
      42             : // These files' stats are loaded incrementally whenever the pending list is
      43             : // empty by scanning a current readState for files missing statistics. Once a
      44             : // job completes a scan without finding any remaining files without
      45             : // statistics, it flips a `loadedInitial` flag. From then on, the stats
      46             : // collection job only needs to load statistics for new files appended to the
      47             : // pending list.
      48             : 
      49           1 : func (d *DB) maybeCollectTableStatsLocked() {
      50           1 :         if d.shouldCollectTableStatsLocked() {
      51           1 :                 go d.collectTableStats()
      52           1 :         }
      53             : }
      54             : 
      55             : // updateTableStatsLocked is called when new files are introduced, after the
      56             : // read state has been updated. It may trigger a new stat collection.
      57             : // DB.mu must be locked when calling.
      58           1 : func (d *DB) updateTableStatsLocked(newFiles []manifest.NewFileEntry) {
      59           1 :         var needStats bool
      60           1 :         for _, nf := range newFiles {
      61           1 :                 if !nf.Meta.StatsValid() {
      62           1 :                         needStats = true
      63           1 :                         break
      64             :                 }
      65             :         }
      66           1 :         if !needStats {
      67           1 :                 return
      68           1 :         }
      69             : 
      70           1 :         d.mu.tableStats.pending = append(d.mu.tableStats.pending, newFiles...)
      71           1 :         d.maybeCollectTableStatsLocked()
      72             : }
      73             : 
      74           1 : func (d *DB) shouldCollectTableStatsLocked() bool {
      75           1 :         return !d.mu.tableStats.loading &&
      76           1 :                 d.closed.Load() == nil &&
      77           1 :                 !d.opts.DisableTableStats &&
      78           1 :                 (len(d.mu.tableStats.pending) > 0 || !d.mu.tableStats.loadedInitial)
      79           1 : }
      80             : 
      81             : // collectTableStats runs a table stats collection job, returning true if the
      82             : // invocation did the collection work, false otherwise (e.g. if another job was
      83             : // already running).
      84           1 : func (d *DB) collectTableStats() bool {
      85           1 :         const maxTableStatsPerScan = 50
      86           1 : 
      87           1 :         d.mu.Lock()
      88           1 :         if !d.shouldCollectTableStatsLocked() {
      89           1 :                 d.mu.Unlock()
      90           1 :                 return false
      91           1 :         }
      92             : 
      93           1 :         pending := d.mu.tableStats.pending
      94           1 :         d.mu.tableStats.pending = nil
      95           1 :         d.mu.tableStats.loading = true
      96           1 :         jobID := d.newJobIDLocked()
      97           1 :         loadedInitial := d.mu.tableStats.loadedInitial
      98           1 :         // Drop DB.mu before performing IO.
      99           1 :         d.mu.Unlock()
     100           1 : 
     101           1 :         // Every run of collectTableStats either collects stats from the pending
     102           1 :         // list (if non-empty) or from scanning the version (loadedInitial is
     103           1 :         // false). This job only runs if at least one of those conditions holds.
     104           1 : 
     105           1 :         // Grab a read state to scan for tables.
     106           1 :         rs := d.loadReadState()
     107           1 :         var collected []collectedStats
     108           1 :         var hints []deleteCompactionHint
     109           1 :         if len(pending) > 0 {
     110           1 :                 collected, hints = d.loadNewFileStats(rs, pending)
     111           1 :         } else {
     112           1 :                 var moreRemain bool
     113           1 :                 var buf [maxTableStatsPerScan]collectedStats
     114           1 :                 collected, hints, moreRemain = d.scanReadStateTableStats(rs, buf[:0])
     115           1 :                 loadedInitial = !moreRemain
     116           1 :         }
     117           1 :         rs.unref()
     118           1 : 
     119           1 :         // Update the FileMetadata with the loaded stats while holding d.mu.
     120           1 :         d.mu.Lock()
     121           1 :         defer d.mu.Unlock()
     122           1 :         d.mu.tableStats.loading = false
     123           1 :         if loadedInitial && !d.mu.tableStats.loadedInitial {
     124           1 :                 d.mu.tableStats.loadedInitial = loadedInitial
     125           1 :                 d.opts.EventListener.TableStatsLoaded(TableStatsInfo{
     126           1 :                         JobID: int(jobID),
     127           1 :                 })
     128           1 :         }
     129             : 
     130           1 :         maybeCompact := false
     131           1 :         for _, c := range collected {
     132           1 :                 c.fileMetadata.Stats = c.TableStats
     133           1 :                 maybeCompact = maybeCompact || fileCompensation(c.fileMetadata) > 0
     134           1 :                 c.fileMetadata.StatsMarkValid()
     135           1 :         }
     136             : 
     137           1 :         d.mu.tableStats.cond.Broadcast()
     138           1 :         d.maybeCollectTableStatsLocked()
     139           1 :         if len(hints) > 0 && !d.opts.private.disableDeleteOnlyCompactions {
     140           1 :                 // Verify that all of the hint tombstones' files still exist in the
     141           1 :                 // current version. Otherwise, the tombstone itself may have been
     142           1 :                 // compacted into L6 and more recent keys may have had their sequence
     143           1 :                 // numbers zeroed.
     144           1 :                 //
     145           1 :                 // Note that it's possible that the tombstone file is being compacted
     146           1 :                 // presently. In that case, the file will be present in v. When the
     147           1 :                 // compaction finishes compacting the tombstone file, it will detect
     148           1 :                 // and clear the hint.
     149           1 :                 //
     150           1 :                 // See DB.maybeUpdateDeleteCompactionHints.
     151           1 :                 v := d.mu.versions.currentVersion()
     152           1 :                 keepHints := hints[:0]
     153           1 :                 for _, h := range hints {
     154           1 :                         if v.Contains(h.tombstoneLevel, h.tombstoneFile) {
     155           1 :                                 keepHints = append(keepHints, h)
     156           1 :                         }
     157             :                 }
     158           1 :                 d.mu.compact.deletionHints = append(d.mu.compact.deletionHints, keepHints...)
     159             :         }
     160           1 :         if maybeCompact {
     161           1 :                 d.maybeScheduleCompaction()
     162           1 :         }
     163           1 :         return true
     164             : }
     165             : 
     166             : type collectedStats struct {
     167             :         *fileMetadata
     168             :         manifest.TableStats
     169             : }
     170             : 
     171             : func (d *DB) loadNewFileStats(
     172             :         rs *readState, pending []manifest.NewFileEntry,
     173           1 : ) ([]collectedStats, []deleteCompactionHint) {
     174           1 :         var hints []deleteCompactionHint
     175           1 :         collected := make([]collectedStats, 0, len(pending))
     176           1 :         for _, nf := range pending {
     177           1 :                 // A file's stats might have been populated by an earlier call to
     178           1 :                 // loadNewFileStats if the file was moved.
     179           1 :                 // NB: We're not holding d.mu which protects f.Stats, but only
     180           1 :                 // collectTableStats updates f.Stats for active files, and we
     181           1 :                 // ensure only one goroutine runs it at a time through
     182           1 :                 // d.mu.tableStats.loading.
     183           1 :                 if nf.Meta.StatsValid() {
     184           1 :                         continue
     185             :                 }
     186             : 
     187             :                 // The file isn't guaranteed to still be live in the readState's
     188             :                 // version. It may have been deleted or moved. Skip it if it's not in
     189             :                 // the expected level.
     190           1 :                 if !rs.current.Contains(nf.Level, nf.Meta) {
     191           1 :                         continue
     192             :                 }
     193             : 
     194           1 :                 stats, newHints, err := d.loadTableStats(
     195           1 :                         rs.current, nf.Level,
     196           1 :                         nf.Meta,
     197           1 :                 )
     198           1 :                 if err != nil {
     199           0 :                         d.opts.EventListener.BackgroundError(err)
     200           0 :                         continue
     201             :                 }
     202             :                 // NB: We don't update the FileMetadata yet, because we aren't
     203             :                 // holding DB.mu. We'll copy it to the FileMetadata after we're
     204             :                 // finished with IO.
     205           1 :                 collected = append(collected, collectedStats{
     206           1 :                         fileMetadata: nf.Meta,
     207           1 :                         TableStats:   stats,
     208           1 :                 })
     209           1 :                 hints = append(hints, newHints...)
     210             :         }
     211           1 :         return collected, hints
     212             : }
     213             : 
     214             : // scanReadStateTableStats is run by an active stat collection job when there
     215             : // are no pending new files, but there might be files that existed at Open for
     216             : // which we haven't loaded table stats.
     217             : func (d *DB) scanReadStateTableStats(
     218             :         rs *readState, fill []collectedStats,
     219           1 : ) ([]collectedStats, []deleteCompactionHint, bool) {
     220           1 :         moreRemain := false
     221           1 :         var hints []deleteCompactionHint
     222           1 :         sizesChecked := make(map[base.DiskFileNum]struct{})
     223           1 :         for l, levelMetadata := range rs.current.Levels {
     224           1 :                 iter := levelMetadata.Iter()
     225           1 :                 for f := iter.First(); f != nil; f = iter.Next() {
     226           1 :                         // NB: We're not holding d.mu which protects f.Stats, but only the
     227           1 :                         // active stats collection job updates f.Stats for active files,
     228           1 :                         // and we ensure only one goroutine runs it at a time through
     229           1 :                         // d.mu.tableStats.loading. This makes it safe to read validity
     230           1 :                         // through f.Stats.ValidLocked despite not holding d.mu.
     231           1 :                         if f.StatsValid() {
     232           1 :                                 continue
     233             :                         }
     234             : 
     235             :                         // Limit how much work we do per read state. The older the read
     236             :                         // state is, the higher the likelihood files are no longer being
     237             :                         // used in the current version. If we've exhausted our allowance,
     238             :                         // return true for the last return value to signal there's more
     239             :                         // work to do.
     240           1 :                         if len(fill) == cap(fill) {
     241           1 :                                 moreRemain = true
     242           1 :                                 return fill, hints, moreRemain
     243           1 :                         }
     244             : 
     245             :                         // If the file is remote and not SharedForeign, we should check if its size
     246             :                         // matches. This is because checkConsistency skips over remote files.
     247             :                         //
     248             :                         // SharedForeign and External files are skipped as their sizes are allowed
     249             :                         // to have a mismatch; the size stored in the FileBacking is just the part
     250             :                         // of the file that is referenced by this Pebble instance, not the size of
     251             :                         // the whole object.
     252           1 :                         objMeta, err := d.objProvider.Lookup(fileTypeTable, f.FileBacking.DiskFileNum)
     253           1 :                         if err != nil {
     254           0 :                                 // Set `moreRemain` so we'll try again.
     255           0 :                                 moreRemain = true
     256           0 :                                 d.opts.EventListener.BackgroundError(err)
     257           0 :                                 continue
     258             :                         }
     259             : 
     260           1 :                         shouldCheckSize := objMeta.IsRemote() &&
     261           1 :                                 !d.objProvider.IsSharedForeign(objMeta) &&
     262           1 :                                 !objMeta.IsExternal()
     263           1 :                         if _, ok := sizesChecked[f.FileBacking.DiskFileNum]; !ok && shouldCheckSize {
     264           0 :                                 size, err := d.objProvider.Size(objMeta)
     265           0 :                                 fileSize := f.FileBacking.Size
     266           0 :                                 if err != nil {
     267           0 :                                         moreRemain = true
     268           0 :                                         d.opts.EventListener.BackgroundError(err)
     269           0 :                                         continue
     270             :                                 }
     271           0 :                                 if size != int64(fileSize) {
     272           0 :                                         err := errors.Errorf(
     273           0 :                                                 "during consistency check in loadTableStats: L%d: %s: object size mismatch (%s): %d (provider) != %d (MANIFEST)",
     274           0 :                                                 errors.Safe(l), f.FileNum, d.objProvider.Path(objMeta),
     275           0 :                                                 errors.Safe(size), errors.Safe(fileSize))
     276           0 :                                         d.opts.EventListener.BackgroundError(err)
     277           0 :                                         d.opts.Logger.Fatalf("%s", err)
     278           0 :                                 }
     279             : 
     280           0 :                                 sizesChecked[f.FileBacking.DiskFileNum] = struct{}{}
     281             :                         }
     282             : 
     283           1 :                         stats, newHints, err := d.loadTableStats(
     284           1 :                                 rs.current, l, f,
     285           1 :                         )
     286           1 :                         if err != nil {
     287           0 :                                 // Set `moreRemain` so we'll try again.
     288           0 :                                 moreRemain = true
     289           0 :                                 d.opts.EventListener.BackgroundError(err)
     290           0 :                                 continue
     291             :                         }
     292           1 :                         fill = append(fill, collectedStats{
     293           1 :                                 fileMetadata: f,
     294           1 :                                 TableStats:   stats,
     295           1 :                         })
     296           1 :                         hints = append(hints, newHints...)
     297             :                 }
     298             :         }
     299           1 :         return fill, hints, moreRemain
     300             : }
     301             : 
     302             : func (d *DB) loadTableStats(
     303             :         v *version, level int, meta *fileMetadata,
     304           1 : ) (manifest.TableStats, []deleteCompactionHint, error) {
     305           1 :         var stats manifest.TableStats
     306           1 :         var compactionHints []deleteCompactionHint
     307           1 :         err := d.tableCache.withCommonReader(
     308           1 :                 meta, func(r sstable.CommonReader) (err error) {
     309           1 :                         props := r.CommonProperties()
     310           1 :                         stats.NumEntries = props.NumEntries
     311           1 :                         stats.NumDeletions = props.NumDeletions
     312           1 :                         stats.NumRangeKeySets = props.NumRangeKeySets
     313           1 :                         stats.ValueBlocksSize = props.ValueBlocksSize
     314           1 :                         stats.CompressionType = block.CompressionFromString(props.CompressionName)
     315           1 :                         stats.TombstoneDenseBlocksRatio = float64(props.NumTombstoneDenseBlocks) / float64(props.NumDataBlocks)
     316           1 : 
     317           1 :                         if props.NumPointDeletions() > 0 {
     318           1 :                                 if err = d.loadTablePointKeyStats(props, v, level, meta, &stats); err != nil {
     319           0 :                                         return
     320           0 :                                 }
     321             :                         }
     322           1 :                         if props.NumRangeDeletions > 0 || props.NumRangeKeyDels > 0 {
     323           1 :                                 if compactionHints, err = d.loadTableRangeDelStats(
     324           1 :                                         r, v, level, meta, &stats,
     325           1 :                                 ); err != nil {
     326           0 :                                         return
     327           0 :                                 }
     328             :                         }
     329           1 :                         return
     330             :                 })
     331           1 :         if err != nil {
     332           0 :                 return stats, nil, err
     333           0 :         }
     334           1 :         return stats, compactionHints, nil
     335             : }
     336             : 
     337             : // loadTablePointKeyStats calculates the point key statistics for the given
     338             : // table. The provided manifest.TableStats are updated.
     339             : func (d *DB) loadTablePointKeyStats(
     340             :         props *sstable.CommonProperties,
     341             :         v *version,
     342             :         level int,
     343             :         meta *fileMetadata,
     344             :         stats *manifest.TableStats,
     345           1 : ) error {
     346           1 :         // TODO(jackson): If the file has a wide keyspace, the average
     347           1 :         // value size beneath the entire file might not be representative
     348           1 :         // of the size of the keys beneath the point tombstones.
     349           1 :         // We could write the ranges of 'clusters' of point tombstones to
     350           1 :         // a sstable property and call averageValueSizeBeneath for each of
     351           1 :         // these narrower ranges to improve the estimate.
     352           1 :         avgValLogicalSize, compressionRatio, err := d.estimateSizesBeneath(v, level, meta, props)
     353           1 :         if err != nil {
     354           0 :                 return err
     355           0 :         }
     356           1 :         stats.PointDeletionsBytesEstimate =
     357           1 :                 pointDeletionsBytesEstimate(meta.Size, props, avgValLogicalSize, compressionRatio)
     358           1 :         return nil
     359             : }
     360             : 
     361             : // loadTableRangeDelStats calculates the range deletion and range key deletion
     362             : // statistics for the given table.
     363             : func (d *DB) loadTableRangeDelStats(
     364             :         r sstable.CommonReader, v *version, level int, meta *fileMetadata, stats *manifest.TableStats,
     365           1 : ) ([]deleteCompactionHint, error) {
     366           1 :         iter, err := newCombinedDeletionKeyspanIter(d.opts.Comparer, r, meta)
     367           1 :         if err != nil {
     368           0 :                 return nil, err
     369           0 :         }
     370           1 :         defer iter.Close()
     371           1 :         var compactionHints []deleteCompactionHint
     372           1 :         // We iterate over the defragmented range tombstones and range key deletions,
     373           1 :         // which ensures we don't double count ranges deleted at different sequence
     374           1 :         // numbers. Also, merging abutting tombstones reduces the number of calls to
     375           1 :         // estimateReclaimedSizeBeneath which is costly, and improves the accuracy of
     376           1 :         // our overall estimate.
     377           1 :         s, err := iter.First()
     378           1 :         for ; s != nil; s, err = iter.Next() {
     379           1 :                 start, end := s.Start, s.End
     380           1 :                 // We only need to consider deletion size estimates for tables that contain
     381           1 :                 // RANGEDELs.
     382           1 :                 var maxRangeDeleteSeqNum base.SeqNum
     383           1 :                 for _, k := range s.Keys {
     384           1 :                         if k.Kind() == base.InternalKeyKindRangeDelete && maxRangeDeleteSeqNum < k.SeqNum() {
     385           1 :                                 maxRangeDeleteSeqNum = k.SeqNum()
     386           1 :                                 break
     387             :                         }
     388             :                 }
     389             : 
     390             :                 // If the file is in the last level of the LSM, there is no data beneath
     391             :                 // it. The fact that there is still a range tombstone in a bottommost file
     392             :                 // indicates two possibilites:
     393             :                 //   1. an open snapshot kept the tombstone around, and the data the
     394             :                 //      tombstone deletes is contained within the file itself.
     395             :                 //   2. the file was ingested.
     396             :                 // In the first case, we'd like to estimate disk usage within the file
     397             :                 // itself since compacting the file will drop that covered data. In the
     398             :                 // second case, we expect that compacting the file will NOT drop any
     399             :                 // data and rewriting the file is a waste of write bandwidth. We can
     400             :                 // distinguish these cases by looking at the file metadata's sequence
     401             :                 // numbers. A file's range deletions can only delete data within the
     402             :                 // file at lower sequence numbers. All keys in an ingested sstable adopt
     403             :                 // the same sequence number, preventing tombstones from deleting keys
     404             :                 // within the same file. We check here if the largest RANGEDEL sequence
     405             :                 // number is greater than the file's smallest sequence number. If it is,
     406             :                 // the RANGEDEL could conceivably (although inconclusively) delete data
     407             :                 // within the same file.
     408             :                 //
     409             :                 // Note that this heuristic is imperfect. If a table containing a range
     410             :                 // deletion is ingested into L5 and subsequently compacted into L6 but
     411             :                 // an open snapshot prevents elision of covered keys in L6, the
     412             :                 // resulting RangeDeletionsBytesEstimate will incorrectly include all
     413             :                 // covered keys.
     414             :                 //
     415             :                 // TODO(jackson): We could prevent the above error in the heuristic by
     416             :                 // computing the file's RangeDeletionsBytesEstimate during the
     417             :                 // compaction itself. It's unclear how common this is.
     418             :                 //
     419             :                 // NOTE: If the span `s` wholly contains a table containing range keys,
     420             :                 // the returned size estimate will be slightly inflated by the range key
     421             :                 // block. However, in practice, range keys are expected to be rare, and
     422             :                 // the size of the range key block relative to the overall size of the
     423             :                 // table is expected to be small.
     424           1 :                 if level == numLevels-1 && meta.SmallestSeqNum < maxRangeDeleteSeqNum {
     425           1 :                         size, err := r.EstimateDiskUsage(start, end)
     426           1 :                         if err != nil {
     427           0 :                                 return nil, err
     428           0 :                         }
     429           1 :                         stats.RangeDeletionsBytesEstimate += size
     430           1 : 
     431           1 :                         // As the file is in the bottommost level, there is no need to collect a
     432           1 :                         // deletion hint.
     433           1 :                         continue
     434             :                 }
     435             : 
     436             :                 // While the size estimates for point keys should only be updated if this
     437             :                 // span contains a range del, the sequence numbers are required for the
     438             :                 // hint. Unconditionally descend, but conditionally update the estimates.
     439           1 :                 hintType := compactionHintFromKeys(s.Keys)
     440           1 :                 estimate, hintSeqNum, err := d.estimateReclaimedSizeBeneath(v, level, start, end, hintType)
     441           1 :                 if err != nil {
     442           0 :                         return nil, err
     443           0 :                 }
     444           1 :                 stats.RangeDeletionsBytesEstimate += estimate
     445           1 : 
     446           1 :                 // If any files were completely contained with the range,
     447           1 :                 // hintSeqNum is the smallest sequence number contained in any
     448           1 :                 // such file.
     449           1 :                 if hintSeqNum == math.MaxUint64 {
     450           1 :                         continue
     451             :                 }
     452           1 :                 hint := deleteCompactionHint{
     453           1 :                         hintType:                hintType,
     454           1 :                         start:                   make([]byte, len(start)),
     455           1 :                         end:                     make([]byte, len(end)),
     456           1 :                         tombstoneFile:           meta,
     457           1 :                         tombstoneLevel:          level,
     458           1 :                         tombstoneLargestSeqNum:  s.LargestSeqNum(),
     459           1 :                         tombstoneSmallestSeqNum: s.SmallestSeqNum(),
     460           1 :                         fileSmallestSeqNum:      hintSeqNum,
     461           1 :                 }
     462           1 :                 copy(hint.start, start)
     463           1 :                 copy(hint.end, end)
     464           1 :                 compactionHints = append(compactionHints, hint)
     465             :         }
     466           1 :         if err != nil {
     467           0 :                 return nil, err
     468           0 :         }
     469           1 :         return compactionHints, nil
     470             : }
     471             : 
     472             : func (d *DB) estimateSizesBeneath(
     473             :         v *version, level int, meta *fileMetadata, fileProps *sstable.CommonProperties,
     474           1 : ) (avgValueLogicalSize, compressionRatio float64, err error) {
     475           1 :         // Find all files in lower levels that overlap with meta,
     476           1 :         // summing their value sizes and entry counts.
     477           1 :         file := meta
     478           1 :         var fileSum, keySum, valSum, entryCount uint64
     479           1 :         // Include the file itself. This is important because in some instances, the
     480           1 :         // computed compression ratio is applied to the tombstones contained within
     481           1 :         // `meta` itself. If there are no files beneath `meta` in the LSM, we would
     482           1 :         // calculate a compression ratio of 0 which is not accurate for the file's
     483           1 :         // own tombstones.
     484           1 :         fileSum += file.Size
     485           1 :         entryCount += fileProps.NumEntries
     486           1 :         keySum += fileProps.RawKeySize
     487           1 :         valSum += fileProps.RawValueSize
     488           1 : 
     489           1 :         addPhysicalTableStats := func(r *sstable.Reader) (err error) {
     490           1 :                 fileSum += file.Size
     491           1 :                 entryCount += r.Properties.NumEntries
     492           1 :                 keySum += r.Properties.RawKeySize
     493           1 :                 valSum += r.Properties.RawValueSize
     494           1 :                 return nil
     495           1 :         }
     496           1 :         addVirtualTableStats := func(v sstable.VirtualReader) (err error) {
     497           1 :                 fileSum += file.Size
     498           1 :                 entryCount += file.Stats.NumEntries
     499           1 :                 keySum += v.Properties.RawKeySize
     500           1 :                 valSum += v.Properties.RawValueSize
     501           1 :                 return nil
     502           1 :         }
     503             : 
     504           1 :         for l := level + 1; l < numLevels; l++ {
     505           1 :                 overlaps := v.Overlaps(l, meta.UserKeyBounds())
     506           1 :                 iter := overlaps.Iter()
     507           1 :                 for file = iter.First(); file != nil; file = iter.Next() {
     508           1 :                         var err error
     509           1 :                         if file.Virtual {
     510           1 :                                 err = d.tableCache.withVirtualReader(file.VirtualMeta(), addVirtualTableStats)
     511           1 :                         } else {
     512           1 :                                 err = d.tableCache.withReader(file.PhysicalMeta(), addPhysicalTableStats)
     513           1 :                         }
     514           1 :                         if err != nil {
     515           0 :                                 return 0, 0, err
     516           0 :                         }
     517             :                 }
     518             :         }
     519           1 :         if entryCount == 0 {
     520           0 :                 return 0, 0, nil
     521           0 :         }
     522             :         // RawKeySize and RawValueSize are uncompressed totals. We'll need to scale
     523             :         // the value sum according to the data size to account for compression,
     524             :         // index blocks and metadata overhead. Eg:
     525             :         //
     526             :         //    Compression rate        ×  Average uncompressed value size
     527             :         //
     528             :         //                            ↓
     529             :         //
     530             :         //         FileSize              RawValueSize
     531             :         //   -----------------------  ×  ------------
     532             :         //   RawKeySize+RawValueSize     NumEntries
     533             :         //
     534             :         // We return the average logical value size plus the compression ratio,
     535             :         // leaving the scaling to the caller. This allows the caller to perform
     536             :         // additional compression ratio scaling if necessary.
     537           1 :         uncompressedSum := float64(keySum + valSum)
     538           1 :         compressionRatio = float64(fileSum) / uncompressedSum
     539           1 :         avgValueLogicalSize = (float64(valSum) / float64(entryCount))
     540           1 :         return avgValueLogicalSize, compressionRatio, nil
     541             : }
     542             : 
     543             : func (d *DB) estimateReclaimedSizeBeneath(
     544             :         v *version, level int, start, end []byte, hintType deleteCompactionHintType,
     545           1 : ) (estimate uint64, hintSeqNum base.SeqNum, err error) {
     546           1 :         // Find all files in lower levels that overlap with the deleted range
     547           1 :         // [start, end).
     548           1 :         //
     549           1 :         // An overlapping file might be completely contained by the range
     550           1 :         // tombstone, in which case we can count the entire file size in
     551           1 :         // our estimate without doing any additional I/O.
     552           1 :         //
     553           1 :         // Otherwise, estimating the range for the file requires
     554           1 :         // additional I/O to read the file's index blocks.
     555           1 :         hintSeqNum = math.MaxUint64
     556           1 :         for l := level + 1; l < numLevels; l++ {
     557           1 :                 overlaps := v.Overlaps(l, base.UserKeyBoundsEndExclusive(start, end))
     558           1 :                 iter := overlaps.Iter()
     559           1 :                 for file := iter.First(); file != nil; file = iter.Next() {
     560           1 :                         startCmp := d.cmp(start, file.Smallest.UserKey)
     561           1 :                         endCmp := d.cmp(file.Largest.UserKey, end)
     562           1 :                         if startCmp <= 0 && (endCmp < 0 || endCmp == 0 && file.Largest.IsExclusiveSentinel()) {
     563           1 :                                 // The range fully contains the file, so skip looking it up in table
     564           1 :                                 // cache/looking at its indexes and add the full file size. Whether the
     565           1 :                                 // disk estimate and hint seqnums are updated depends on a) the type of
     566           1 :                                 // hint that requested the estimate and b) the keys contained in this
     567           1 :                                 // current file.
     568           1 :                                 var updateEstimates, updateHints bool
     569           1 :                                 switch hintType {
     570           1 :                                 case deleteCompactionHintTypePointKeyOnly:
     571           1 :                                         // The range deletion byte estimates should only be updated if this
     572           1 :                                         // table contains point keys. This ends up being an overestimate in
     573           1 :                                         // the case that table also has range keys, but such keys are expected
     574           1 :                                         // to contribute a negligible amount of the table's overall size,
     575           1 :                                         // relative to point keys.
     576           1 :                                         if file.HasPointKeys {
     577           1 :                                                 updateEstimates = true
     578           1 :                                         }
     579             :                                         // As the initiating span contained only range dels, hints can only be
     580             :                                         // updated if this table does _not_ contain range keys.
     581           1 :                                         if !file.HasRangeKeys {
     582           1 :                                                 updateHints = true
     583           1 :                                         }
     584           1 :                                 case deleteCompactionHintTypeRangeKeyOnly:
     585           1 :                                         // The initiating span contained only range key dels. The estimates
     586           1 :                                         // apply only to point keys, and are therefore not updated.
     587           1 :                                         updateEstimates = false
     588           1 :                                         // As the initiating span contained only range key dels, hints can
     589           1 :                                         // only be updated if this table does _not_ contain point keys.
     590           1 :                                         if !file.HasPointKeys {
     591           1 :                                                 updateHints = true
     592           1 :                                         }
     593           1 :                                 case deleteCompactionHintTypePointAndRangeKey:
     594           1 :                                         // Always update the estimates and hints, as this hint type can drop a
     595           1 :                                         // file, irrespective of the mixture of keys. Similar to above, the
     596           1 :                                         // range del bytes estimates is an overestimate.
     597           1 :                                         updateEstimates, updateHints = true, true
     598           0 :                                 default:
     599           0 :                                         panic(fmt.Sprintf("pebble: unknown hint type %s", hintType))
     600             :                                 }
     601           1 :                                 if updateEstimates {
     602           1 :                                         estimate += file.Size
     603           1 :                                 }
     604           1 :                                 if updateHints && hintSeqNum > file.SmallestSeqNum {
     605           1 :                                         hintSeqNum = file.SmallestSeqNum
     606           1 :                                 }
     607           1 :                         } else if d.cmp(file.Smallest.UserKey, end) <= 0 && d.cmp(start, file.Largest.UserKey) <= 0 {
     608           1 :                                 // Partial overlap.
     609           1 :                                 if hintType == deleteCompactionHintTypeRangeKeyOnly {
     610           1 :                                         // If the hint that generated this overlap contains only range keys,
     611           1 :                                         // there is no need to calculate disk usage, as the reclaimable space
     612           1 :                                         // is expected to be minimal relative to point keys.
     613           1 :                                         continue
     614             :                                 }
     615           1 :                                 var size uint64
     616           1 :                                 var err error
     617           1 :                                 if file.Virtual {
     618           1 :                                         err = d.tableCache.withVirtualReader(
     619           1 :                                                 file.VirtualMeta(), func(r sstable.VirtualReader) (err error) {
     620           1 :                                                         size, err = r.EstimateDiskUsage(start, end)
     621           1 :                                                         return err
     622           1 :                                                 })
     623           1 :                                 } else {
     624           1 :                                         err = d.tableCache.withReader(
     625           1 :                                                 file.PhysicalMeta(), func(r *sstable.Reader) (err error) {
     626           1 :                                                         size, err = r.EstimateDiskUsage(start, end)
     627           1 :                                                         return err
     628           1 :                                                 })
     629             :                                 }
     630             : 
     631           1 :                                 if err != nil {
     632           0 :                                         return 0, hintSeqNum, err
     633           0 :                                 }
     634           1 :                                 estimate += size
     635             :                         }
     636             :                 }
     637             :         }
     638           1 :         return estimate, hintSeqNum, nil
     639             : }
     640             : 
     641           1 : func maybeSetStatsFromProperties(meta physicalMeta, props *sstable.Properties) bool {
     642           1 :         // If a table contains range deletions or range key deletions, we defer the
     643           1 :         // stats collection. There are two main reasons for this:
     644           1 :         //
     645           1 :         //  1. Estimating the potential for reclaimed space due to a range deletion
     646           1 :         //     tombstone requires scanning the LSM - a potentially expensive operation
     647           1 :         //     that should be deferred.
     648           1 :         //  2. Range deletions and / or range key deletions present an opportunity to
     649           1 :         //     compute "deletion hints", which also requires a scan of the LSM to
     650           1 :         //     compute tables that would be eligible for deletion.
     651           1 :         //
     652           1 :         // These two tasks are deferred to the table stats collector goroutine.
     653           1 :         if props.NumRangeDeletions != 0 || props.NumRangeKeyDels != 0 {
     654           1 :                 return false
     655           1 :         }
     656             : 
     657             :         // If a table is more than 10% point deletions without user-provided size
     658             :         // estimates, don't calculate the PointDeletionsBytesEstimate statistic
     659             :         // using our limited knowledge. The table stats collector can populate the
     660             :         // stats and calculate an average of value size of all the tables beneath
     661             :         // the table in the LSM, which will be more accurate.
     662           1 :         if unsizedDels := (props.NumDeletions - props.NumSizedDeletions); unsizedDels > props.NumEntries/10 {
     663           1 :                 return false
     664           1 :         }
     665             : 
     666           1 :         var pointEstimate uint64
     667           1 :         if props.NumEntries > 0 {
     668           1 :                 // Use the file's own average key and value sizes as an estimate. This
     669           1 :                 // doesn't require any additional IO and since the number of point
     670           1 :                 // deletions in the file is low, the error introduced by this crude
     671           1 :                 // estimate is expected to be small.
     672           1 :                 commonProps := &props.CommonProperties
     673           1 :                 avgValSize, compressionRatio := estimatePhysicalSizes(meta.Size, commonProps)
     674           1 :                 pointEstimate = pointDeletionsBytesEstimate(meta.Size, commonProps, avgValSize, compressionRatio)
     675           1 :         }
     676             : 
     677           1 :         meta.Stats.NumEntries = props.NumEntries
     678           1 :         meta.Stats.NumDeletions = props.NumDeletions
     679           1 :         meta.Stats.NumRangeKeySets = props.NumRangeKeySets
     680           1 :         meta.Stats.PointDeletionsBytesEstimate = pointEstimate
     681           1 :         meta.Stats.RangeDeletionsBytesEstimate = 0
     682           1 :         meta.Stats.ValueBlocksSize = props.ValueBlocksSize
     683           1 :         meta.Stats.CompressionType = block.CompressionFromString(props.CompressionName)
     684           1 :         meta.StatsMarkValid()
     685           1 :         return true
     686             : }
     687             : 
     688             : func pointDeletionsBytesEstimate(
     689             :         fileSize uint64, props *sstable.CommonProperties, avgValLogicalSize, compressionRatio float64,
     690           1 : ) (estimate uint64) {
     691           1 :         if props.NumEntries == 0 {
     692           0 :                 return 0
     693           0 :         }
     694           1 :         numPointDels := props.NumPointDeletions()
     695           1 :         if numPointDels == 0 {
     696           1 :                 return 0
     697           1 :         }
     698             :         // Estimate the potential space to reclaim using the table's own properties.
     699             :         // There may or may not be keys covered by any individual point tombstone.
     700             :         // If not, compacting the point tombstone into L6 will at least allow us to
     701             :         // drop the point deletion key and will reclaim the tombstone's key bytes.
     702             :         // If there are covered key(s), we also get to drop key and value bytes for
     703             :         // each covered key.
     704             :         //
     705             :         // Some point tombstones (DELSIZEDs) carry a user-provided estimate of the
     706             :         // uncompressed size of entries that will be elided by fully compacting the
     707             :         // tombstone. For these tombstones, there's no guesswork—we use the
     708             :         // RawPointTombstoneValueSizeHint property which is the sum of all these
     709             :         // tombstones' encoded values.
     710             :         //
     711             :         // For un-sized point tombstones (DELs), we estimate assuming that each
     712             :         // point tombstone on average covers 1 key and using average value sizes.
     713             :         // This is almost certainly an overestimate, but that's probably okay
     714             :         // because point tombstones can slow range iterations even when they don't
     715             :         // cover a key.
     716             :         //
     717             :         // TODO(jackson): This logic doesn't directly incorporate fixed per-key
     718             :         // overhead (8-byte trailer, plus at least 1 byte encoding the length of the
     719             :         // key and 1 byte encoding the length of the value). This overhead is
     720             :         // indirectly incorporated through the compression ratios, but that results
     721             :         // in the overhead being smeared per key-byte and value-byte, rather than
     722             :         // per-entry. This per-key fixed overhead can be nontrivial, especially for
     723             :         // dense swaths of point tombstones. Give some thought as to whether we
     724             :         // should directly include fixed per-key overhead in the calculations.
     725             : 
     726             :         // Below, we calculate the tombstone contributions and the shadowed keys'
     727             :         // contributions separately.
     728           1 :         var tombstonesLogicalSize float64
     729           1 :         var shadowedLogicalSize float64
     730           1 : 
     731           1 :         // 1. Calculate the contribution of the tombstone keys themselves.
     732           1 :         if props.RawPointTombstoneKeySize > 0 {
     733           1 :                 tombstonesLogicalSize += float64(props.RawPointTombstoneKeySize)
     734           1 :         } else {
     735           0 :                 // This sstable predates the existence of the RawPointTombstoneKeySize
     736           0 :                 // property. We can use the average key size within the file itself and
     737           0 :                 // the count of point deletions to estimate the size.
     738           0 :                 tombstonesLogicalSize += float64(numPointDels * props.RawKeySize / props.NumEntries)
     739           0 :         }
     740             : 
     741             :         // 2. Calculate the contribution of the keys shadowed by tombstones.
     742             :         //
     743             :         // 2a. First account for keys shadowed by DELSIZED tombstones. THE DELSIZED
     744             :         // tombstones encode the size of both the key and value of the shadowed KV
     745             :         // entries. These sizes are aggregated into a sstable property.
     746           1 :         shadowedLogicalSize += float64(props.RawPointTombstoneValueSize)
     747           1 : 
     748           1 :         // 2b. Calculate the contribution of the KV entries shadowed by ordinary DEL
     749           1 :         // keys.
     750           1 :         numUnsizedDels := numPointDels - props.NumSizedDeletions
     751           1 :         {
     752           1 :                 // The shadowed keys have the same exact user keys as the tombstones
     753           1 :                 // themselves, so we can use the `tombstonesLogicalSize` we computed
     754           1 :                 // earlier as an estimate. There's a complication that
     755           1 :                 // `tombstonesLogicalSize` may include DELSIZED keys we already
     756           1 :                 // accounted for.
     757           1 :                 shadowedLogicalSize += float64(tombstonesLogicalSize) / float64(numPointDels) * float64(numUnsizedDels)
     758           1 : 
     759           1 :                 // Calculate the contribution of the deleted values. The caller has
     760           1 :                 // already computed an average logical size (possibly computed across
     761           1 :                 // many sstables).
     762           1 :                 shadowedLogicalSize += float64(numUnsizedDels) * avgValLogicalSize
     763           1 :         }
     764             : 
     765             :         // Scale both tombstone and shadowed totals by logical:physical ratios to
     766             :         // account for compression, metadata overhead, etc.
     767             :         //
     768             :         //      Physical             FileSize
     769             :         //     -----------  = -----------------------
     770             :         //      Logical       RawKeySize+RawValueSize
     771             :         //
     772           1 :         return uint64((tombstonesLogicalSize + shadowedLogicalSize) * compressionRatio)
     773             : }
     774             : 
     775             : func estimatePhysicalSizes(
     776             :         fileSize uint64, props *sstable.CommonProperties,
     777           1 : ) (avgValLogicalSize, compressionRatio float64) {
     778           1 :         // RawKeySize and RawValueSize are uncompressed totals. Scale according to
     779           1 :         // the data size to account for compression, index blocks and metadata
     780           1 :         // overhead. Eg:
     781           1 :         //
     782           1 :         //    Compression rate        ×  Average uncompressed value size
     783           1 :         //
     784           1 :         //                            ↓
     785           1 :         //
     786           1 :         //         FileSize              RawValSize
     787           1 :         //   -----------------------  ×  ----------
     788           1 :         //   RawKeySize+RawValueSize     NumEntries
     789           1 :         //
     790           1 :         uncompressedSum := props.RawKeySize + props.RawValueSize
     791           1 :         compressionRatio = float64(fileSize) / float64(uncompressedSum)
     792           1 :         avgValLogicalSize = (float64(props.RawValueSize) / float64(props.NumEntries))
     793           1 :         return avgValLogicalSize, compressionRatio
     794           1 : }
     795             : 
     796             : // newCombinedDeletionKeyspanIter returns a keyspan.FragmentIterator that
     797             : // returns "ranged deletion" spans for a single table, providing a combined view
     798             : // of both range deletion and range key deletion spans. The
     799             : // tableRangedDeletionIter is intended for use in the specific case of computing
     800             : // the statistics and deleteCompactionHints for a single table.
     801             : //
     802             : // As an example, consider the following set of spans from the range deletion
     803             : // and range key blocks of a table:
     804             : //
     805             : //                    |---------|     |---------|         |-------| RANGEKEYDELs
     806             : //              |-----------|-------------|           |-----|       RANGEDELs
     807             : //        __________________________________________________________
     808             : //              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
     809             : //
     810             : // The tableRangedDeletionIter produces the following set of output spans, where
     811             : // '1' indicates a span containing only range deletions, '2' is a span
     812             : // containing only range key deletions, and '3' is a span containing a mixture
     813             : // of both range deletions and range key deletions.
     814             : //
     815             : //                 1       3       1    3    2          1  3   2
     816             : //              |-----|---------|-----|---|-----|     |---|-|-----|
     817             : //        __________________________________________________________
     818             : //              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
     819             : //
     820             : // Algorithm.
     821             : //
     822             : // The iterator first defragments the range deletion and range key blocks
     823             : // separately. During this defragmentation, the range key block is also filtered
     824             : // so that keys other than range key deletes are ignored. The range delete and
     825             : // range key delete keyspaces are then merged.
     826             : //
     827             : // Note that the only fragmentation introduced by merging is from where a range
     828             : // del span overlaps with a range key del span. Within the bounds of any overlap
     829             : // there is guaranteed to be no further fragmentation, as the constituent spans
     830             : // have already been defragmented. To the left and right of any overlap, the
     831             : // same reasoning applies. For example,
     832             : //
     833             : //                       |--------|         |-------| RANGEKEYDEL
     834             : //              |---------------------------|         RANGEDEL
     835             : //              |----1---|----3---|----1----|---2---| Merged, fragmented spans.
     836             : //        __________________________________________________________
     837             : //              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
     838             : //
     839             : // Any fragmented abutting spans produced by the merging iter will be of
     840             : // differing types (i.e. a transition from a span with homogenous key kinds to a
     841             : // heterogeneous span, or a transition from a span with exclusively range dels
     842             : // to a span with exclusively range key dels). Therefore, further
     843             : // defragmentation is not required.
     844             : //
     845             : // Each span returned by the tableRangeDeletionIter will have at most four keys,
     846             : // corresponding to the largest and smallest sequence numbers encountered across
     847             : // the range deletes and range keys deletes that comprised the merged spans.
     848             : func newCombinedDeletionKeyspanIter(
     849             :         comparer *base.Comparer, cr sstable.CommonReader, m *fileMetadata,
     850           1 : ) (keyspan.FragmentIterator, error) {
     851           1 :         // The range del iter and range key iter are each wrapped in their own
     852           1 :         // defragmenting iter. For each iter, abutting spans can always be merged.
     853           1 :         var equal = keyspan.DefragmentMethodFunc(func(_ base.CompareSuffixes, a, b *keyspan.Span) bool { return true })
     854             :         // Reduce keys by maintaining a slice of at most length two, corresponding to
     855             :         // the largest and smallest keys in the defragmented span. This maintains the
     856             :         // contract that the emitted slice is sorted by (SeqNum, Kind) descending.
     857           1 :         reducer := func(current, incoming []keyspan.Key) []keyspan.Key {
     858           1 :                 if len(current) == 0 && len(incoming) == 0 {
     859           0 :                         // While this should never occur in practice, a defensive return is used
     860           0 :                         // here to preserve correctness.
     861           0 :                         return current
     862           0 :                 }
     863           1 :                 var largest, smallest keyspan.Key
     864           1 :                 var set bool
     865           1 :                 for _, keys := range [2][]keyspan.Key{current, incoming} {
     866           1 :                         if len(keys) == 0 {
     867           0 :                                 continue
     868             :                         }
     869           1 :                         first, last := keys[0], keys[len(keys)-1]
     870           1 :                         if !set {
     871           1 :                                 largest, smallest = first, last
     872           1 :                                 set = true
     873           1 :                                 continue
     874             :                         }
     875           1 :                         if first.Trailer > largest.Trailer {
     876           1 :                                 largest = first
     877           1 :                         }
     878           1 :                         if last.Trailer < smallest.Trailer {
     879           1 :                                 smallest = last
     880           1 :                         }
     881             :                 }
     882           1 :                 if largest.Equal(comparer.CompareSuffixes, smallest) {
     883           1 :                         current = append(current[:0], largest)
     884           1 :                 } else {
     885           1 :                         current = append(current[:0], largest, smallest)
     886           1 :                 }
     887           1 :                 return current
     888             :         }
     889             : 
     890             :         // The separate iters for the range dels and range keys are wrapped in a
     891             :         // merging iter to join the keyspaces into a single keyspace. The separate
     892             :         // iters are only added if the particular key kind is present.
     893           1 :         mIter := &keyspanimpl.MergingIter{}
     894           1 :         var transform = keyspan.TransformerFunc(func(_ base.CompareSuffixes, in keyspan.Span, out *keyspan.Span) error {
     895           1 :                 if in.KeysOrder != keyspan.ByTrailerDesc {
     896           0 :                         panic("pebble: combined deletion iter encountered keys in non-trailer descending order")
     897             :                 }
     898           1 :                 out.Start, out.End = in.Start, in.End
     899           1 :                 out.Keys = append(out.Keys[:0], in.Keys...)
     900           1 :                 out.KeysOrder = keyspan.ByTrailerDesc
     901           1 :                 // NB: The order of by-trailer descending may have been violated,
     902           1 :                 // because we've layered rangekey and rangedel iterators from the same
     903           1 :                 // sstable into the same keyspanimpl.MergingIter. The MergingIter will
     904           1 :                 // return the keys in the order that the child iterators were provided.
     905           1 :                 // Sort the keys to ensure they're sorted by trailer descending.
     906           1 :                 keyspan.SortKeysByTrailer(out.Keys)
     907           1 :                 return nil
     908             :         })
     909           1 :         mIter.Init(comparer, transform, new(keyspanimpl.MergingBuffers))
     910           1 : 
     911           1 :         iter, err := cr.NewRawRangeDelIter(context.TODO(), m.FragmentIterTransforms())
     912           1 :         if err != nil {
     913           0 :                 return nil, err
     914           0 :         }
     915           1 :         if iter != nil {
     916           1 :                 // Assert expected bounds. In previous versions of Pebble, range
     917           1 :                 // deletions persisted to sstables could exceed the bounds of the
     918           1 :                 // containing files due to "split user keys." This required readers to
     919           1 :                 // constrain the tombstones' bounds to the containing file at read time.
     920           1 :                 // See docs/range_deletions.md for an extended discussion of the design
     921           1 :                 // and invariants at that time.
     922           1 :                 //
     923           1 :                 // We've since compacted away all 'split user-keys' and in the process
     924           1 :                 // eliminated all "untruncated range tombstones" for physical sstables.
     925           1 :                 // We no longer need to perform truncation at read time for these
     926           1 :                 // sstables.
     927           1 :                 //
     928           1 :                 // At the same time, we've also introduced the concept of "virtual
     929           1 :                 // SSTables" where the file metadata's effective bounds can again be
     930           1 :                 // reduced to be narrower than the contained tombstones. These virtual
     931           1 :                 // SSTables handle truncation differently, performing it using
     932           1 :                 // keyspan.Truncate when the sstable's range deletion iterator is
     933           1 :                 // opened.
     934           1 :                 //
     935           1 :                 // Together, these mean that we should never see untruncated range
     936           1 :                 // tombstones any more—and the merging iterator no longer accounts for
     937           1 :                 // their existence. Since there's abundant subtlety that we're relying
     938           1 :                 // on, we choose to be conservative and assert that these invariants
     939           1 :                 // hold. We could (and previously did) choose to only validate these
     940           1 :                 // bounds in invariants builds, but the most likely avenue for these
     941           1 :                 // tombstones' existence is through a bug in a migration and old data
     942           1 :                 // sitting around in an old store from long ago.
     943           1 :                 //
     944           1 :                 // The table stats collector will read all files range deletions
     945           1 :                 // asynchronously after Open, and provides a perfect opportunity to
     946           1 :                 // validate our invariants without harming user latency. We also
     947           1 :                 // previously performed truncation here which similarly required key
     948           1 :                 // comparisons, so replacing those key comparisons with assertions
     949           1 :                 // should be roughly similar in performance.
     950           1 :                 //
     951           1 :                 // TODO(jackson): Only use AssertBounds in invariants builds in the
     952           1 :                 // following release.
     953           1 :                 iter = keyspan.AssertBounds(
     954           1 :                         iter, m.SmallestPointKey, m.LargestPointKey.UserKey, comparer.Compare,
     955           1 :                 )
     956           1 :                 dIter := &keyspan.DefragmentingIter{}
     957           1 :                 dIter.Init(comparer, iter, equal, reducer, new(keyspan.DefragmentingBuffers))
     958           1 :                 iter = dIter
     959           1 :                 mIter.AddLevel(iter)
     960           1 :         }
     961             : 
     962           1 :         iter, err = cr.NewRawRangeKeyIter(context.TODO(), m.FragmentIterTransforms())
     963           1 :         if err != nil {
     964           0 :                 return nil, err
     965           0 :         }
     966           1 :         if iter != nil {
     967           1 :                 // Assert expected bounds in tests.
     968           1 :                 if invariants.Sometimes(50) {
     969           1 :                         iter = keyspan.AssertBounds(
     970           1 :                                 iter, m.SmallestRangeKey, m.LargestRangeKey.UserKey, comparer.Compare,
     971           1 :                         )
     972           1 :                 }
     973             :                 // Wrap the range key iterator in a filter that elides keys other than range
     974             :                 // key deletions.
     975           1 :                 iter = keyspan.Filter(iter, func(in *keyspan.Span, buf []keyspan.Key) []keyspan.Key {
     976           1 :                         keys := buf[:0]
     977           1 :                         for _, k := range in.Keys {
     978           1 :                                 if k.Kind() != base.InternalKeyKindRangeKeyDelete {
     979           1 :                                         continue
     980             :                                 }
     981           1 :                                 keys = append(keys, k)
     982             :                         }
     983           1 :                         return keys
     984             :                 }, comparer.Compare)
     985           1 :                 dIter := &keyspan.DefragmentingIter{}
     986           1 :                 dIter.Init(comparer, iter, equal, reducer, new(keyspan.DefragmentingBuffers))
     987           1 :                 iter = dIter
     988           1 :                 mIter.AddLevel(iter)
     989             :         }
     990             : 
     991           1 :         return mIter, nil
     992             : }
     993             : 
     994             : // rangeKeySetsAnnotator is a manifest.Annotator that annotates B-Tree nodes
     995             : // with the sum of the files' counts of range key fragments. The count of range
     996             : // key sets may change once a table's stats are loaded asynchronously, so its
     997             : // values are marked as cacheable only if a file's stats have been loaded.
     998           1 : var rangeKeySetsAnnotator = manifest.SumAnnotator(func(f *manifest.FileMetadata) (uint64, bool) {
     999           1 :         return f.Stats.NumRangeKeySets, f.StatsValid()
    1000           1 : })
    1001             : 
    1002             : // tombstonesAnnotator is a manifest.Annotator that annotates B-Tree nodes
    1003             : // with the sum of the files' counts of tombstones (DEL, SINGLEDEL and RANGEDEL
    1004             : // keys). The count of tombstones may change once a table's stats are loaded
    1005             : // asynchronously, so its values are marked as cacheable only if a file's stats
    1006             : // have been loaded.
    1007           1 : var tombstonesAnnotator = manifest.SumAnnotator(func(f *manifest.FileMetadata) (uint64, bool) {
    1008           1 :         return f.Stats.NumDeletions, f.StatsValid()
    1009           1 : })
    1010             : 
    1011             : // valueBlocksSizeAnnotator is a manifest.Annotator that annotates B-Tree
    1012             : // nodes with the sum of the files' Properties.ValueBlocksSize. The value block
    1013             : // size may change once a table's stats are loaded asynchronously, so its
    1014             : // values are marked as cacheable only if a file's stats have been loaded.
    1015           1 : var valueBlockSizeAnnotator = manifest.SumAnnotator(func(f *fileMetadata) (uint64, bool) {
    1016           1 :         return f.Stats.ValueBlocksSize, f.StatsValid()
    1017           1 : })
    1018             : 
    1019             : // compressionTypeAnnotator is a manifest.Annotator that annotates B-tree
    1020             : // nodes with the compression type of the file. Its annotation type is
    1021             : // compressionTypes. The compression type may change once a table's stats are
    1022             : // loaded asynchronously, so its values are marked as cacheable only if a file's
    1023             : // stats have been loaded.
    1024             : var compressionTypeAnnotator = manifest.Annotator[compressionTypes]{
    1025             :         Aggregator: compressionTypeAggregator{},
    1026             : }
    1027             : 
    1028             : type compressionTypeAggregator struct{}
    1029             : 
    1030             : type compressionTypes struct {
    1031             :         snappy, zstd, none, unknown uint64
    1032             : }
    1033             : 
    1034           1 : func (a compressionTypeAggregator) Zero(dst *compressionTypes) *compressionTypes {
    1035           1 :         if dst == nil {
    1036           1 :                 return new(compressionTypes)
    1037           1 :         }
    1038           1 :         *dst = compressionTypes{}
    1039           1 :         return dst
    1040             : }
    1041             : 
    1042             : func (a compressionTypeAggregator) Accumulate(
    1043             :         f *fileMetadata, dst *compressionTypes,
    1044           1 : ) (v *compressionTypes, cacheOK bool) {
    1045           1 :         switch f.Stats.CompressionType {
    1046           1 :         case SnappyCompression:
    1047           1 :                 dst.snappy++
    1048           1 :         case ZstdCompression:
    1049           1 :                 dst.zstd++
    1050           1 :         case NoCompression:
    1051           1 :                 dst.none++
    1052           1 :         default:
    1053           1 :                 dst.unknown++
    1054             :         }
    1055           1 :         return dst, f.StatsValid()
    1056             : }
    1057             : 
    1058             : func (a compressionTypeAggregator) Merge(
    1059             :         src *compressionTypes, dst *compressionTypes,
    1060           1 : ) *compressionTypes {
    1061           1 :         dst.snappy += src.snappy
    1062           1 :         dst.zstd += src.zstd
    1063           1 :         dst.none += src.none
    1064           1 :         dst.unknown += src.unknown
    1065           1 :         return dst
    1066           1 : }

Generated by: LCOV version 1.14