LCOV - code coverage report
Current view: top level - pebble - level_checker.go (source / functions) Coverage Total Hit
Test: 2025-03-13 08:17Z a48d4fcc - tests + meta.lcov Lines: 84.0 % 489 411
Test Date: 2025-03-13 08:18:34 Functions: - 0 0

            Line data    Source code
       1              : // Copyright 2019 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              :         "io"
      11              :         "sort"
      12              : 
      13              :         "github.com/cockroachdb/errors"
      14              :         "github.com/cockroachdb/pebble/internal/base"
      15              :         "github.com/cockroachdb/pebble/internal/keyspan"
      16              :         "github.com/cockroachdb/pebble/internal/manifest"
      17              : )
      18              : 
      19              : // This file implements DB.CheckLevels() which checks that every entry in the
      20              : // DB is consistent with respect to the level invariant: any point (or the
      21              : // infinite number of points in a range tombstone) has a seqnum such that a
      22              : // point with the same UserKey at a lower level has a lower seqnum. This is an
      23              : // expensive check since it involves iterating over all the entries in the DB,
      24              : // hence only intended for tests or tools.
      25              : //
      26              : // If we ignore range tombstones, the consistency checking of points can be
      27              : // done with a simplified version of mergingIter. simpleMergingIter is that
      28              : // simplified version of mergingIter that only needs to step through points
      29              : // (analogous to only doing Next()). It can also easily accommodate
      30              : // consistency checking of points relative to range tombstones.
      31              : // simpleMergingIter does not do any seek optimizations present in mergingIter
      32              : // (it minimally needs to seek the range delete iterators to position them at
      33              : // or past the current point) since it does not want to miss points for
      34              : // purposes of consistency checking.
      35              : //
      36              : // Mutual consistency of range tombstones is non-trivial to check. One needs
      37              : // to detect inversions of the form [a, c)#8 at higher level and [b, c)#10 at
      38              : // a lower level. The start key of the former is not contained in the latter
      39              : // and we can't use the exclusive end key, c, for a containment check since it
      40              : // is the sentinel key. We observe that if these tombstones were fragmented
      41              : // wrt each other we would have [a, b)#8 and [b, c)#8 at the higher level and
      42              : // [b, c)#10 at the lower level and then it is is trivial to compare the two
      43              : // [b, c) tombstones. Note that this fragmentation needs to take into account
      44              : // that tombstones in a file may be untruncated and need to act within the
      45              : // bounds of the file. This checking is performed by checkRangeTombstones()
      46              : // and its helper functions.
      47              : 
      48              : // The per-level structure used by simpleMergingIter.
      49              : type simpleMergingIterLevel struct {
      50              :         iter         internalIterator
      51              :         rangeDelIter keyspan.FragmentIterator
      52              : 
      53              :         iterKV    *base.InternalKV
      54              :         tombstone *keyspan.Span
      55              : }
      56              : 
      57            2 : func (ml *simpleMergingIterLevel) setRangeDelIter(iter keyspan.FragmentIterator) {
      58            2 :         ml.tombstone = nil
      59            2 :         if ml.rangeDelIter != nil {
      60            2 :                 ml.rangeDelIter.Close()
      61            2 :         }
      62            2 :         ml.rangeDelIter = iter
      63              : }
      64              : 
      65              : type simpleMergingIter struct {
      66              :         levels   []simpleMergingIterLevel
      67              :         snapshot base.SeqNum
      68              :         heap     simpleMergingIterHeap
      69              :         // The last point's key and level. For validation.
      70              :         lastKey     InternalKey
      71              :         lastLevel   int
      72              :         lastIterMsg string
      73              :         // A non-nil valueMerger means MERGE record processing is ongoing.
      74              :         valueMerger base.ValueMerger
      75              :         // The first error will cause step() to return false.
      76              :         err       error
      77              :         numPoints int64
      78              :         merge     Merge
      79              :         formatKey base.FormatKey
      80              : }
      81              : 
      82              : func (m *simpleMergingIter) init(
      83              :         merge Merge,
      84              :         cmp Compare,
      85              :         snapshot base.SeqNum,
      86              :         formatKey base.FormatKey,
      87              :         levels ...simpleMergingIterLevel,
      88            2 : ) {
      89            2 :         m.levels = levels
      90            2 :         m.formatKey = formatKey
      91            2 :         m.merge = merge
      92            2 :         m.snapshot = snapshot
      93            2 :         m.lastLevel = -1
      94            2 :         m.heap.cmp = cmp
      95            2 :         m.heap.items = make([]simpleMergingIterItem, 0, len(levels))
      96            2 :         for i := range m.levels {
      97            2 :                 l := &m.levels[i]
      98            2 :                 l.iterKV = l.iter.First()
      99            2 :                 if l.iterKV != nil {
     100            2 :                         item := simpleMergingIterItem{
     101            2 :                                 index: i,
     102            2 :                                 kv:    *l.iterKV,
     103            2 :                         }
     104            2 :                         item.kv.K = l.iterKV.K.Clone()
     105            2 :                         m.heap.items = append(m.heap.items, item)
     106            2 :                 }
     107              :         }
     108            2 :         m.heap.init()
     109            2 : 
     110            2 :         if m.heap.len() == 0 {
     111            2 :                 return
     112            2 :         }
     113            2 :         m.positionRangeDels()
     114              : }
     115              : 
     116              : // Positions all the rangedel iterators at or past the current top of the
     117              : // heap, using SeekGE().
     118            2 : func (m *simpleMergingIter) positionRangeDels() {
     119            2 :         item := &m.heap.items[0]
     120            2 :         for i := range m.levels {
     121            2 :                 l := &m.levels[i]
     122            2 :                 if l.rangeDelIter == nil {
     123            2 :                         continue
     124              :                 }
     125            2 :                 t, err := l.rangeDelIter.SeekGE(item.kv.K.UserKey)
     126            2 :                 m.err = firstError(m.err, err)
     127            2 :                 l.tombstone = t
     128              :         }
     129              : }
     130              : 
     131              : // Returns true if not yet done.
     132            2 : func (m *simpleMergingIter) step() bool {
     133            2 :         if m.heap.len() == 0 || m.err != nil {
     134            2 :                 return false
     135            2 :         }
     136            2 :         item := &m.heap.items[0]
     137            2 :         l := &m.levels[item.index]
     138            2 :         // Sentinels are not relevant for this point checking.
     139            2 :         if !item.kv.K.IsExclusiveSentinel() && item.kv.K.Visible(m.snapshot, base.SeqNumMax) {
     140            2 :                 // This is a visible point key.
     141            2 :                 if !m.handleVisiblePoint(item, l) {
     142            0 :                         return false
     143            0 :                 }
     144              :         }
     145              : 
     146              :         // The iterator for the current level may be closed in the following call to
     147              :         // Next(). We save its debug string for potential use after it is closed -
     148              :         // either in this current step() invocation or on the next invocation.
     149            2 :         m.lastIterMsg = l.iter.String()
     150            2 : 
     151            2 :         // Step to the next point.
     152            2 :         l.iterKV = l.iter.Next()
     153            2 :         if l.iterKV == nil {
     154            2 :                 m.err = errors.CombineErrors(l.iter.Error(), l.iter.Close())
     155            2 :                 l.iter = nil
     156            2 :                 m.heap.pop()
     157            2 :         } else {
     158            2 :                 // Check point keys in an sstable are ordered. Although not required, we check
     159            2 :                 // for memtables as well. A subtle check here is that successive sstables of
     160            2 :                 // L1 and higher levels are ordered. This happens when levelIter moves to the
     161            2 :                 // next sstable in the level, in which case item.key is previous sstable's
     162            2 :                 // last point key.
     163            2 :                 if !l.iterKV.K.IsExclusiveSentinel() && base.InternalCompare(m.heap.cmp, item.kv.K, l.iterKV.K) >= 0 {
     164            0 :                         m.err = errors.Errorf("out of order keys %s >= %s in %s",
     165            0 :                                 item.kv.K.Pretty(m.formatKey), l.iterKV.K.Pretty(m.formatKey), l.iter)
     166            0 :                         return false
     167            0 :                 }
     168            2 :                 userKeyBuf := item.kv.K.UserKey[:0]
     169            2 :                 item.kv = *l.iterKV
     170            2 :                 item.kv.K.UserKey = append(userKeyBuf, l.iterKV.K.UserKey...)
     171            2 :                 if m.heap.len() > 1 {
     172            2 :                         m.heap.fix(0)
     173            2 :                 }
     174              :         }
     175            2 :         if m.err != nil {
     176            0 :                 return false
     177            0 :         }
     178            2 :         if m.heap.len() == 0 {
     179            2 :                 // If m.valueMerger != nil, the last record was a MERGE record.
     180            2 :                 if m.valueMerger != nil {
     181            2 :                         var closer io.Closer
     182            2 :                         var err error
     183            2 :                         _, closer, err = m.valueMerger.Finish(true /* includesBase */)
     184            2 :                         if closer != nil {
     185            0 :                                 err = errors.CombineErrors(err, closer.Close())
     186            0 :                         }
     187            2 :                         if err != nil {
     188            0 :                                 m.err = errors.CombineErrors(m.err,
     189            0 :                                         errors.Wrapf(err, "merge processing error on key %s in %s",
     190            0 :                                                 item.kv.K.Pretty(m.formatKey), m.lastIterMsg))
     191            0 :                         }
     192            2 :                         m.valueMerger = nil
     193              :                 }
     194            2 :                 return false
     195              :         }
     196            2 :         m.positionRangeDels()
     197            2 :         return true
     198              : }
     199              : 
     200              : // handleVisiblePoint returns true if validation succeeded and level checking
     201              : // can continue.
     202              : func (m *simpleMergingIter) handleVisiblePoint(
     203              :         item *simpleMergingIterItem, l *simpleMergingIterLevel,
     204            2 : ) (ok bool) {
     205            2 :         m.numPoints++
     206            2 :         keyChanged := m.heap.cmp(item.kv.K.UserKey, m.lastKey.UserKey) != 0
     207            2 :         if !keyChanged {
     208            2 :                 // At the same user key. We will see them in decreasing seqnum
     209            2 :                 // order so the lastLevel must not be lower.
     210            2 :                 if m.lastLevel > item.index {
     211            0 :                         m.err = errors.Errorf("found InternalKey %s in %s and InternalKey %s in %s",
     212            0 :                                 item.kv.K.Pretty(m.formatKey), l.iter, m.lastKey.Pretty(m.formatKey),
     213            0 :                                 m.lastIterMsg)
     214            0 :                         return false
     215            0 :                 }
     216            2 :                 m.lastLevel = item.index
     217            2 :         } else {
     218            2 :                 // The user key has changed.
     219            2 :                 m.lastKey.Trailer = item.kv.K.Trailer
     220            2 :                 m.lastKey.UserKey = append(m.lastKey.UserKey[:0], item.kv.K.UserKey...)
     221            2 :                 m.lastLevel = item.index
     222            2 :         }
     223              :         // Ongoing series of MERGE records ends with a MERGE record.
     224            2 :         if keyChanged && m.valueMerger != nil {
     225            2 :                 var closer io.Closer
     226            2 :                 _, closer, m.err = m.valueMerger.Finish(true /* includesBase */)
     227            2 :                 if m.err == nil && closer != nil {
     228            0 :                         m.err = closer.Close()
     229            0 :                 }
     230            2 :                 m.valueMerger = nil
     231              :         }
     232            2 :         itemValue, _, err := item.kv.Value(nil)
     233            2 :         if err != nil {
     234            0 :                 m.err = err
     235            0 :                 return false
     236            0 :         }
     237            2 :         if m.valueMerger != nil {
     238            2 :                 // Ongoing series of MERGE records.
     239            2 :                 switch item.kv.K.Kind() {
     240            2 :                 case InternalKeyKindSingleDelete, InternalKeyKindDelete, InternalKeyKindDeleteSized:
     241            2 :                         var closer io.Closer
     242            2 :                         _, closer, m.err = m.valueMerger.Finish(true /* includesBase */)
     243            2 :                         if m.err == nil && closer != nil {
     244            0 :                                 m.err = closer.Close()
     245            0 :                         }
     246            2 :                         m.valueMerger = nil
     247            2 :                 case InternalKeyKindSet, InternalKeyKindSetWithDelete:
     248            2 :                         m.err = m.valueMerger.MergeOlder(itemValue)
     249            2 :                         if m.err == nil {
     250            2 :                                 var closer io.Closer
     251            2 :                                 _, closer, m.err = m.valueMerger.Finish(true /* includesBase */)
     252            2 :                                 if m.err == nil && closer != nil {
     253            0 :                                         m.err = closer.Close()
     254            0 :                                 }
     255              :                         }
     256            2 :                         m.valueMerger = nil
     257            2 :                 case InternalKeyKindMerge:
     258            2 :                         m.err = m.valueMerger.MergeOlder(itemValue)
     259            0 :                 default:
     260            0 :                         m.err = errors.Errorf("pebble: invalid internal key kind %s in %s",
     261            0 :                                 item.kv.K.Pretty(m.formatKey),
     262            0 :                                 l.iter)
     263            0 :                         return false
     264              :                 }
     265            2 :         } else if item.kv.K.Kind() == InternalKeyKindMerge && m.err == nil {
     266            2 :                 // New series of MERGE records.
     267            2 :                 m.valueMerger, m.err = m.merge(item.kv.K.UserKey, itemValue)
     268            2 :         }
     269            2 :         if m.err != nil {
     270            0 :                 m.err = errors.Wrapf(m.err, "merge processing error on key %s in %s",
     271            0 :                         item.kv.K.Pretty(m.formatKey), l.iter)
     272            0 :                 return false
     273            0 :         }
     274              :         // Is this point covered by a tombstone at a lower level? Note that all these
     275              :         // iterators must be positioned at a key > item.key.
     276            2 :         for level := item.index + 1; level < len(m.levels); level++ {
     277            2 :                 lvl := &m.levels[level]
     278            2 :                 if lvl.rangeDelIter == nil || lvl.tombstone.Empty() {
     279            2 :                         continue
     280              :                 }
     281            2 :                 if lvl.tombstone.Contains(m.heap.cmp, item.kv.K.UserKey) && lvl.tombstone.CoversAt(m.snapshot, item.kv.K.SeqNum()) {
     282            0 :                         m.err = errors.Errorf("tombstone %s in %s deletes key %s in %s",
     283            0 :                                 lvl.tombstone.Pretty(m.formatKey), lvl.iter, item.kv.K.Pretty(m.formatKey),
     284            0 :                                 l.iter)
     285            0 :                         return false
     286            0 :                 }
     287              :         }
     288            2 :         return true
     289              : }
     290              : 
     291              : // Checking that range tombstones are mutually consistent is performed by
     292              : // checkRangeTombstones(). See the overview comment at the top of the file.
     293              : //
     294              : // We do this check as follows:
     295              : // - Collect the tombstones for each level, put them into one pool of tombstones
     296              : //   along with their level information (addTombstonesFromIter()).
     297              : // - Collect the start and end user keys from all these tombstones
     298              : //   (collectAllUserKey()) and use them to fragment all the tombstones
     299              : //   (fragmentUsingUserKey()).
     300              : // - Sort tombstones by start key and decreasing seqnum
     301              : //   (tombstonesByStartKeyAndSeqnum) - all tombstones that have the same start
     302              : //   key will have the same end key because they have been fragmented.
     303              : // - Iterate and check (iterateAndCheckTombstones()).
     304              : //
     305              : // Note that this simple approach requires holding all the tombstones across all
     306              : // levels in-memory. A more sophisticated incremental approach could be devised,
     307              : // if necessary.
     308              : 
     309              : // A tombstone and the corresponding level it was found in.
     310              : type tombstoneWithLevel struct {
     311              :         keyspan.Span
     312              :         level int
     313              :         // The level in LSM. A -1 means it's a memtable.
     314              :         lsmLevel int
     315              :         fileNum  base.FileNum
     316              : }
     317              : 
     318              : // For sorting tombstoneWithLevels in increasing order of start UserKey and
     319              : // for the same start UserKey in decreasing order of seqnum.
     320              : type tombstonesByStartKeyAndSeqnum struct {
     321              :         cmp Compare
     322              :         buf []tombstoneWithLevel
     323              : }
     324              : 
     325            2 : func (v *tombstonesByStartKeyAndSeqnum) Len() int { return len(v.buf) }
     326            2 : func (v *tombstonesByStartKeyAndSeqnum) Less(i, j int) bool {
     327            2 :         less := v.cmp(v.buf[i].Start, v.buf[j].Start)
     328            2 :         if less == 0 {
     329            2 :                 return v.buf[i].LargestSeqNum() > v.buf[j].LargestSeqNum()
     330            2 :         }
     331            2 :         return less < 0
     332              : }
     333            2 : func (v *tombstonesByStartKeyAndSeqnum) Swap(i, j int) {
     334            2 :         v.buf[i], v.buf[j] = v.buf[j], v.buf[i]
     335            2 : }
     336              : 
     337              : func iterateAndCheckTombstones(
     338              :         cmp Compare, formatKey base.FormatKey, tombstones []tombstoneWithLevel,
     339            2 : ) error {
     340            2 :         sortBuf := tombstonesByStartKeyAndSeqnum{
     341            2 :                 cmp: cmp,
     342            2 :                 buf: tombstones,
     343            2 :         }
     344            2 :         sort.Sort(&sortBuf)
     345            2 : 
     346            2 :         // For a sequence of tombstones that share the same start UserKey, we will
     347            2 :         // encounter them in non-increasing seqnum order and so should encounter them
     348            2 :         // in non-decreasing level order.
     349            2 :         lastTombstone := tombstoneWithLevel{}
     350            2 :         for _, t := range tombstones {
     351            2 :                 if cmp(lastTombstone.Start, t.Start) == 0 && lastTombstone.level > t.level {
     352            0 :                         return errors.Errorf("encountered tombstone %s in %s"+
     353            0 :                                 " that has a lower seqnum than the same tombstone in %s",
     354            0 :                                 t.Span.Pretty(formatKey), levelOrMemtable(t.lsmLevel, t.fileNum),
     355            0 :                                 levelOrMemtable(lastTombstone.lsmLevel, lastTombstone.fileNum))
     356            0 :                 }
     357            2 :                 lastTombstone = t
     358              :         }
     359            2 :         return nil
     360              : }
     361              : 
     362              : type checkConfig struct {
     363              :         logger    Logger
     364              :         comparer  *Comparer
     365              :         readState *readState
     366              :         newIters  tableNewIters
     367              :         seqNum    base.SeqNum
     368              :         stats     *CheckLevelsStats
     369              :         merge     Merge
     370              :         formatKey base.FormatKey
     371              : }
     372              : 
     373              : // cmp is shorthand for comparer.Compare.
     374            2 : func (c *checkConfig) cmp(a, b []byte) int { return c.comparer.Compare(a, b) }
     375              : 
     376            2 : func checkRangeTombstones(c *checkConfig) error {
     377            2 :         var level int
     378            2 :         var tombstones []tombstoneWithLevel
     379            2 :         var err error
     380            2 : 
     381            2 :         memtables := c.readState.memtables
     382            2 :         for i := len(memtables) - 1; i >= 0; i-- {
     383            2 :                 iter := memtables[i].newRangeDelIter(nil)
     384            2 :                 if iter == nil {
     385            2 :                         continue
     386              :                 }
     387            2 :                 tombstones, err = addTombstonesFromIter(
     388            2 :                         iter, level, -1, 0, tombstones, c.seqNum, c.cmp, c.formatKey,
     389            2 :                 )
     390            2 :                 iter.Close()
     391            2 :                 if err != nil {
     392            0 :                         return err
     393            0 :                 }
     394            2 :                 level++
     395              :         }
     396              : 
     397            2 :         current := c.readState.current
     398            2 :         addTombstonesFromLevel := func(files manifest.LevelIterator, lsmLevel int) error {
     399            2 :                 for f := files.First(); f != nil; f = files.Next() {
     400            2 :                         lf := files.Take()
     401            2 :                         iters, err := c.newIters(
     402            2 :                                 context.Background(), lf.TableMetadata, &IterOptions{layer: manifest.Level(lsmLevel)},
     403            2 :                                 internalIterOpts{}, iterRangeDeletions)
     404            2 :                         if err != nil {
     405            0 :                                 return err
     406            0 :                         }
     407            2 :                         tombstones, err = addTombstonesFromIter(iters.RangeDeletion(), level, lsmLevel, f.FileNum,
     408            2 :                                 tombstones, c.seqNum, c.cmp, c.formatKey)
     409            2 :                         iters.CloseAll()
     410            2 : 
     411            2 :                         if err != nil {
     412            0 :                                 return err
     413            0 :                         }
     414              :                 }
     415            2 :                 return nil
     416              :         }
     417              :         // Now the levels with untruncated tombsones.
     418            2 :         for i := len(current.L0SublevelFiles) - 1; i >= 0; i-- {
     419            2 :                 if current.L0SublevelFiles[i].Empty() {
     420            0 :                         continue
     421              :                 }
     422            2 :                 err := addTombstonesFromLevel(current.L0SublevelFiles[i].Iter(), 0)
     423            2 :                 if err != nil {
     424            0 :                         return err
     425            0 :                 }
     426            2 :                 level++
     427              :         }
     428            2 :         for i := 1; i < len(current.Levels); i++ {
     429            2 :                 if err := addTombstonesFromLevel(current.Levels[i].Iter(), i); err != nil {
     430            0 :                         return err
     431            0 :                 }
     432            2 :                 level++
     433              :         }
     434            2 :         if c.stats != nil {
     435            1 :                 c.stats.NumTombstones = len(tombstones)
     436            1 :         }
     437              :         // We now have truncated tombstones.
     438              :         // Fragment them all.
     439            2 :         userKeys := collectAllUserKeys(c.cmp, tombstones)
     440            2 :         tombstones = fragmentUsingUserKeys(c.cmp, tombstones, userKeys)
     441            2 :         return iterateAndCheckTombstones(c.cmp, c.formatKey, tombstones)
     442              : }
     443              : 
     444            0 : func levelOrMemtable(lsmLevel int, fileNum base.FileNum) string {
     445            0 :         if lsmLevel == -1 {
     446            0 :                 return "memtable"
     447            0 :         }
     448            0 :         return fmt.Sprintf("L%d: fileNum=%s", lsmLevel, fileNum)
     449              : }
     450              : 
     451              : func addTombstonesFromIter(
     452              :         iter keyspan.FragmentIterator,
     453              :         level int,
     454              :         lsmLevel int,
     455              :         fileNum base.FileNum,
     456              :         tombstones []tombstoneWithLevel,
     457              :         seqNum base.SeqNum,
     458              :         cmp Compare,
     459              :         formatKey base.FormatKey,
     460            2 : ) (_ []tombstoneWithLevel, err error) {
     461            2 :         var prevTombstone keyspan.Span
     462            2 :         tomb, err := iter.First()
     463            2 :         for ; tomb != nil; tomb, err = iter.Next() {
     464            2 :                 t := tomb.Visible(seqNum)
     465            2 :                 if t.Empty() {
     466            2 :                         continue
     467              :                 }
     468            2 :                 t = t.Clone()
     469            2 :                 // This is mainly a test for rangeDelV2 formatted blocks which are expected to
     470            2 :                 // be ordered and fragmented on disk. But we anyways check for memtables,
     471            2 :                 // rangeDelV1 as well.
     472            2 :                 if cmp(prevTombstone.End, t.Start) > 0 {
     473            0 :                         return nil, errors.Errorf("unordered or unfragmented range delete tombstones %s, %s in %s",
     474            0 :                                 prevTombstone.Pretty(formatKey), t.Pretty(formatKey), levelOrMemtable(lsmLevel, fileNum))
     475            0 :                 }
     476            2 :                 prevTombstone = t
     477            2 : 
     478            2 :                 if !t.Empty() {
     479            2 :                         tombstones = append(tombstones, tombstoneWithLevel{
     480            2 :                                 Span:     t,
     481            2 :                                 level:    level,
     482            2 :                                 lsmLevel: lsmLevel,
     483            2 :                                 fileNum:  fileNum,
     484            2 :                         })
     485            2 :                 }
     486              :         }
     487            2 :         if err != nil {
     488            0 :                 return nil, err
     489            0 :         }
     490            2 :         return tombstones, nil
     491              : }
     492              : 
     493              : type userKeysSort struct {
     494              :         cmp Compare
     495              :         buf [][]byte
     496              : }
     497              : 
     498            2 : func (v *userKeysSort) Len() int { return len(v.buf) }
     499            2 : func (v *userKeysSort) Less(i, j int) bool {
     500            2 :         return v.cmp(v.buf[i], v.buf[j]) < 0
     501            2 : }
     502            2 : func (v *userKeysSort) Swap(i, j int) {
     503            2 :         v.buf[i], v.buf[j] = v.buf[j], v.buf[i]
     504            2 : }
     505            2 : func collectAllUserKeys(cmp Compare, tombstones []tombstoneWithLevel) [][]byte {
     506            2 :         keys := make([][]byte, 0, len(tombstones)*2)
     507            2 :         for _, t := range tombstones {
     508            2 :                 keys = append(keys, t.Start)
     509            2 :                 keys = append(keys, t.End)
     510            2 :         }
     511            2 :         sorter := userKeysSort{
     512            2 :                 cmp: cmp,
     513            2 :                 buf: keys,
     514            2 :         }
     515            2 :         sort.Sort(&sorter)
     516            2 :         var last, curr int
     517            2 :         for last, curr = -1, 0; curr < len(keys); curr++ {
     518            2 :                 if last < 0 || cmp(keys[last], keys[curr]) != 0 {
     519            2 :                         last++
     520            2 :                         keys[last] = keys[curr]
     521            2 :                 }
     522              :         }
     523            2 :         keys = keys[:last+1]
     524            2 :         return keys
     525              : }
     526              : 
     527              : func fragmentUsingUserKeys(
     528              :         cmp Compare, tombstones []tombstoneWithLevel, userKeys [][]byte,
     529            2 : ) []tombstoneWithLevel {
     530            2 :         var buf []tombstoneWithLevel
     531            2 :         for _, t := range tombstones {
     532            2 :                 // Find the first position with tombstone start < user key
     533            2 :                 i := sort.Search(len(userKeys), func(i int) bool {
     534            2 :                         return cmp(t.Start, userKeys[i]) < 0
     535            2 :                 })
     536            2 :                 for ; i < len(userKeys); i++ {
     537            2 :                         if cmp(userKeys[i], t.End) >= 0 {
     538            2 :                                 break
     539              :                         }
     540            2 :                         tPartial := t
     541            2 :                         tPartial.End = userKeys[i]
     542            2 :                         buf = append(buf, tPartial)
     543            2 :                         t.Start = userKeys[i]
     544              :                 }
     545            2 :                 buf = append(buf, t)
     546              :         }
     547            2 :         return buf
     548              : }
     549              : 
     550              : // CheckLevelsStats provides basic stats on points and tombstones encountered.
     551              : type CheckLevelsStats struct {
     552              :         NumPoints     int64
     553              :         NumTombstones int
     554              : }
     555              : 
     556              : // CheckLevels checks:
     557              : //   - Every entry in the DB is consistent with the level invariant. See the
     558              : //     comment at the top of the file.
     559              : //   - Point keys in sstables are ordered.
     560              : //   - Range delete tombstones in sstables are ordered and fragmented.
     561              : //   - Successful processing of all MERGE records.
     562            2 : func (d *DB) CheckLevels(stats *CheckLevelsStats) error {
     563            2 :         // Grab and reference the current readState.
     564            2 :         readState := d.loadReadState()
     565            2 :         defer readState.unref()
     566            2 : 
     567            2 :         // Determine the seqnum to read at after grabbing the read state (current and
     568            2 :         // memtables) above.
     569            2 :         seqNum := d.mu.versions.visibleSeqNum.Load()
     570            2 : 
     571            2 :         checkConfig := &checkConfig{
     572            2 :                 logger:    d.opts.Logger,
     573            2 :                 comparer:  d.opts.Comparer,
     574            2 :                 readState: readState,
     575            2 :                 newIters:  d.newIters,
     576            2 :                 seqNum:    seqNum,
     577            2 :                 stats:     stats,
     578            2 :                 merge:     d.merge,
     579            2 :                 formatKey: d.opts.Comparer.FormatKey,
     580            2 :         }
     581            2 :         return checkLevelsInternal(checkConfig)
     582            2 : }
     583              : 
     584            2 : func checkLevelsInternal(c *checkConfig) (err error) {
     585            2 :         // Phase 1: Use a simpleMergingIter to step through all the points and ensure
     586            2 :         // that points with the same user key at different levels are not inverted
     587            2 :         // wrt sequence numbers and the same holds for tombstones that cover points.
     588            2 :         // To do this, one needs to construct a simpleMergingIter which is similar to
     589            2 :         // how one constructs a mergingIter.
     590            2 : 
     591            2 :         // Add mem tables from newest to oldest.
     592            2 :         var mlevels []simpleMergingIterLevel
     593            2 :         defer func() {
     594            2 :                 for i := range mlevels {
     595            2 :                         l := &mlevels[i]
     596            2 :                         if l.iter != nil {
     597            2 :                                 err = firstError(err, l.iter.Close())
     598            2 :                                 l.iter = nil
     599            2 :                         }
     600            2 :                         if l.rangeDelIter != nil {
     601            2 :                                 l.rangeDelIter.Close()
     602            2 :                                 l.rangeDelIter = nil
     603            2 :                         }
     604              :                 }
     605              :         }()
     606              : 
     607            2 :         memtables := c.readState.memtables
     608            2 :         for i := len(memtables) - 1; i >= 0; i-- {
     609            2 :                 mem := memtables[i]
     610            2 :                 mlevels = append(mlevels, simpleMergingIterLevel{
     611            2 :                         iter:         mem.newIter(nil),
     612            2 :                         rangeDelIter: mem.newRangeDelIter(nil),
     613            2 :                 })
     614            2 :         }
     615              : 
     616            2 :         current := c.readState.current
     617            2 :         // Determine the final size for mlevels so that there are no more
     618            2 :         // reallocations. levelIter will hold a pointer to elements in mlevels.
     619            2 :         start := len(mlevels)
     620            2 :         for sublevel := len(current.L0SublevelFiles) - 1; sublevel >= 0; sublevel-- {
     621            2 :                 if current.L0SublevelFiles[sublevel].Empty() {
     622            0 :                         continue
     623              :                 }
     624            2 :                 mlevels = append(mlevels, simpleMergingIterLevel{})
     625              :         }
     626            2 :         for level := 1; level < len(current.Levels); level++ {
     627            2 :                 if current.Levels[level].Empty() {
     628            2 :                         continue
     629              :                 }
     630            2 :                 mlevels = append(mlevels, simpleMergingIterLevel{})
     631              :         }
     632            2 :         mlevelAlloc := mlevels[start:]
     633            2 :         // Add L0 files by sublevel.
     634            2 :         for sublevel := len(current.L0SublevelFiles) - 1; sublevel >= 0; sublevel-- {
     635            2 :                 if current.L0SublevelFiles[sublevel].Empty() {
     636            0 :                         continue
     637              :                 }
     638            2 :                 manifestIter := current.L0SublevelFiles[sublevel].Iter()
     639            2 :                 iterOpts := IterOptions{logger: c.logger}
     640            2 :                 li := &levelIter{}
     641            2 :                 li.init(context.Background(), iterOpts, c.comparer, c.newIters, manifestIter,
     642            2 :                         manifest.L0Sublevel(sublevel), internalIterOpts{})
     643            2 :                 li.initRangeDel(&mlevelAlloc[0])
     644            2 :                 mlevelAlloc[0].iter = li
     645            2 :                 mlevelAlloc = mlevelAlloc[1:]
     646              :         }
     647            2 :         for level := 1; level < len(current.Levels); level++ {
     648            2 :                 if current.Levels[level].Empty() {
     649            2 :                         continue
     650              :                 }
     651              : 
     652            2 :                 iterOpts := IterOptions{logger: c.logger}
     653            2 :                 li := &levelIter{}
     654            2 :                 li.init(context.Background(), iterOpts, c.comparer, c.newIters,
     655            2 :                         current.Levels[level].Iter(), manifest.Level(level), internalIterOpts{})
     656            2 :                 li.initRangeDel(&mlevelAlloc[0])
     657            2 :                 mlevelAlloc[0].iter = li
     658            2 :                 mlevelAlloc = mlevelAlloc[1:]
     659              :         }
     660              : 
     661            2 :         mergingIter := &simpleMergingIter{}
     662            2 :         mergingIter.init(c.merge, c.cmp, c.seqNum, c.formatKey, mlevels...)
     663            2 :         for cont := mergingIter.step(); cont; cont = mergingIter.step() {
     664            2 :         }
     665            2 :         if err := mergingIter.err; err != nil {
     666            0 :                 return err
     667            0 :         }
     668            2 :         if c.stats != nil {
     669            1 :                 c.stats.NumPoints = mergingIter.numPoints
     670            1 :         }
     671              : 
     672              :         // Phase 2: Check that the tombstones are mutually consistent.
     673            2 :         return checkRangeTombstones(c)
     674              : }
     675              : 
     676              : type simpleMergingIterItem struct {
     677              :         index int
     678              :         kv    base.InternalKV
     679              : }
     680              : 
     681              : type simpleMergingIterHeap struct {
     682              :         cmp     Compare
     683              :         reverse bool
     684              :         items   []simpleMergingIterItem
     685              : }
     686              : 
     687            2 : func (h *simpleMergingIterHeap) len() int {
     688            2 :         return len(h.items)
     689            2 : }
     690              : 
     691            2 : func (h *simpleMergingIterHeap) less(i, j int) bool {
     692            2 :         ikey, jkey := h.items[i].kv.K, h.items[j].kv.K
     693            2 :         if c := h.cmp(ikey.UserKey, jkey.UserKey); c != 0 {
     694            2 :                 if h.reverse {
     695            0 :                         return c > 0
     696            0 :                 }
     697            2 :                 return c < 0
     698              :         }
     699            2 :         if h.reverse {
     700            0 :                 return ikey.Trailer < jkey.Trailer
     701            0 :         }
     702            2 :         return ikey.Trailer > jkey.Trailer
     703              : }
     704              : 
     705            2 : func (h *simpleMergingIterHeap) swap(i, j int) {
     706            2 :         h.items[i], h.items[j] = h.items[j], h.items[i]
     707            2 : }
     708              : 
     709              : // init, fix, up and down are copied from the go stdlib.
     710            2 : func (h *simpleMergingIterHeap) init() {
     711            2 :         // heapify
     712            2 :         n := h.len()
     713            2 :         for i := n/2 - 1; i >= 0; i-- {
     714            2 :                 h.down(i, n)
     715            2 :         }
     716              : }
     717              : 
     718            2 : func (h *simpleMergingIterHeap) fix(i int) {
     719            2 :         if !h.down(i, h.len()) {
     720            2 :                 h.up(i)
     721            2 :         }
     722              : }
     723              : 
     724            2 : func (h *simpleMergingIterHeap) pop() *simpleMergingIterItem {
     725            2 :         n := h.len() - 1
     726            2 :         h.swap(0, n)
     727            2 :         h.down(0, n)
     728            2 :         item := &h.items[n]
     729            2 :         h.items = h.items[:n]
     730            2 :         return item
     731            2 : }
     732              : 
     733            2 : func (h *simpleMergingIterHeap) up(j int) {
     734            2 :         for {
     735            2 :                 i := (j - 1) / 2 // parent
     736            2 :                 if i == j || !h.less(j, i) {
     737            2 :                         break
     738              :                 }
     739            0 :                 h.swap(i, j)
     740            0 :                 j = i
     741              :         }
     742              : }
     743              : 
     744            2 : func (h *simpleMergingIterHeap) down(i0, n int) bool {
     745            2 :         i := i0
     746            2 :         for {
     747            2 :                 j1 := 2*i + 1
     748            2 :                 if j1 >= n || j1 < 0 { // j1 < 0 after int overflow
     749            2 :                         break
     750              :                 }
     751            2 :                 j := j1 // left child
     752            2 :                 if j2 := j1 + 1; j2 < n && h.less(j2, j1) {
     753            2 :                         j = j2 // = 2*i + 2  // right child
     754            2 :                 }
     755            2 :                 if !h.less(j, i) {
     756            2 :                         break
     757              :                 }
     758            2 :                 h.swap(i, j)
     759            2 :                 i = j
     760              :         }
     761            2 :         return i > i0
     762              : }
        

Generated by: LCOV version 2.0-1