LCOV - code coverage report
Current view: top level - pebble - merging_iter.go (source / functions) Hit Total Coverage
Test: 2024-05-17 08:16Z 2ac449bb - tests only.lcov Lines: 709 779 91.0 %
Date: 2024-05-17 08:16:56 Functions: 0 0 -

          Line data    Source code
       1             : // Copyright 2018 The LevelDB-Go and Pebble Authors. All rights reserved. Use
       2             : // of this source code is governed by a BSD-style license that can be found in
       3             : // the LICENSE file.
       4             : 
       5             : package pebble
       6             : 
       7             : import (
       8             :         "bytes"
       9             :         "context"
      10             :         "fmt"
      11             :         "runtime/debug"
      12             :         "unsafe"
      13             : 
      14             :         "github.com/cockroachdb/errors"
      15             :         "github.com/cockroachdb/pebble/internal/base"
      16             :         "github.com/cockroachdb/pebble/internal/invariants"
      17             :         "github.com/cockroachdb/pebble/internal/keyspan"
      18             : )
      19             : 
      20             : type mergingIterLevel struct {
      21             :         index int
      22             :         iter  internalIterator
      23             :         // rangeDelIter is set to the range-deletion iterator for the level. When
      24             :         // configured with a levelIter, this pointer changes as sstable boundaries
      25             :         // are crossed. See levelIter.initRangeDel and the Range Deletions comment
      26             :         // below.
      27             :         rangeDelIter keyspan.FragmentIterator
      28             :         // iterKV caches the current key-value pair iter points to.
      29             :         iterKV *base.InternalKV
      30             :         // levelIter is non-nil if this level's iter is ultimately backed by a
      31             :         // *levelIter. The handle in iter may have wrapped the levelIter with
      32             :         // intermediary internalIterator implementations.
      33             :         levelIter *levelIter
      34             : 
      35             :         // tombstone caches the tombstone rangeDelIter is currently pointed at. If
      36             :         // tombstone is nil, there are no further tombstones within the
      37             :         // current sstable in the current iterator direction. The cached tombstone is
      38             :         // only valid for the levels in the range [0,heap[0].index]. This avoids
      39             :         // positioning tombstones at lower levels which cannot possibly shadow the
      40             :         // current key.
      41             :         tombstone *keyspan.Span
      42             : }
      43             : 
      44             : // mergingIter provides a merged view of multiple iterators from different
      45             : // levels of the LSM.
      46             : //
      47             : // The core of a mergingIter is a heap of internalIterators (see
      48             : // mergingIterHeap). The heap can operate as either a min-heap, used during
      49             : // forward iteration (First, SeekGE, Next) or a max-heap, used during reverse
      50             : // iteration (Last, SeekLT, Prev). The heap is initialized in calls to First,
      51             : // Last, SeekGE, and SeekLT. A call to Next or Prev takes the current top
      52             : // element on the heap, advances its iterator, and then "fixes" the heap
      53             : // property. When one of the child iterators is exhausted during Next/Prev
      54             : // iteration, it is removed from the heap.
      55             : //
      56             : // # Range Deletions
      57             : //
      58             : // A mergingIter can optionally be configured with a slice of range deletion
      59             : // iterators. The range deletion iterator slice must exactly parallel the point
      60             : // iterators and the range deletion iterator must correspond to the same level
      61             : // in the LSM as the point iterator. Note that each memtable and each table in
      62             : // L0 is a different "level" from the mergingIter perspective. So level 0 below
      63             : // does not correspond to L0 in the LSM.
      64             : //
      65             : // A range deletion iterator iterates over fragmented range tombstones. Range
      66             : // tombstones are fragmented by splitting them at any overlapping points. This
      67             : // fragmentation guarantees that within an sstable tombstones will either be
      68             : // distinct or will have identical start and end user keys. While range
      69             : // tombstones are fragmented within an sstable, the start and end keys are not truncated
      70             : // to sstable boundaries. This is necessary because the tombstone end key is
      71             : // exclusive and does not have a sequence number. Consider an sstable
      72             : // containing the range tombstone [a,c)#9 and the key "b#8". The tombstone must
      73             : // delete "b#8", yet older versions of "b" might spill over to the next
      74             : // sstable. So the boundary key for this sstable must be "b#8". Adjusting the
      75             : // end key of tombstones to be optionally inclusive or contain a sequence
      76             : // number would be possible solutions (such solutions have potentially serious
      77             : // issues: tombstones have exclusive end keys since an inclusive deletion end can
      78             : // be converted to an exclusive one while the reverse transformation is not possible;
      79             : // the semantics of a sequence number for the end key of a range tombstone are murky).
      80             : //
      81             : // The approach taken here performs an
      82             : // implicit truncation of the tombstone to the sstable boundaries.
      83             : //
      84             : // During initialization of a mergingIter, the range deletion iterators for
      85             : // batches, memtables, and L0 tables are populated up front. Note that Batches
      86             : // and memtables index unfragmented tombstones.  Batch.newRangeDelIter() and
      87             : // memTable.newRangeDelIter() fragment and cache the tombstones on demand. The
      88             : // L1-L6 range deletion iterators are populated by levelIter. When configured
      89             : // to load range deletion iterators, whenever a levelIter loads a table it
      90             : // loads both the point iterator and the range deletion
      91             : // iterator. levelIter.rangeDelIter is configured to point to the right entry
      92             : // in mergingIter.levels. The effect of this setup is that
      93             : // mergingIter.levels[i].rangeDelIter always contains the fragmented range
      94             : // tombstone for the current table in level i that the levelIter has open.
      95             : //
      96             : // Another crucial mechanism of levelIter is that it materializes fake point
      97             : // entries for the table boundaries if the boundary is range deletion
      98             : // key. Consider a table that contains only a range tombstone [a-e)#10. The
      99             : // sstable boundaries for this table will be a#10,15 and
     100             : // e#72057594037927935,15. During forward iteration levelIter will return
     101             : // e#72057594037927935,15 as a key. During reverse iteration levelIter will
     102             : // return a#10,15 as a key. These sentinel keys act as bookends to point
     103             : // iteration and allow mergingIter to keep a table and its associated range
     104             : // tombstones loaded as long as there are keys at lower levels that are within
     105             : // the bounds of the table.
     106             : //
     107             : // The final piece to the range deletion puzzle is the LSM invariant that for a
     108             : // given key K newer versions of K can only exist earlier in the level, or at
     109             : // higher levels of the tree. For example, if K#4 exists in L3, k#5 can only
     110             : // exist earlier in the L3 or in L0, L1, L2 or a memtable. Get very explicitly
     111             : // uses this invariant to find the value for a key by walking the LSM level by
     112             : // level. For range deletions, this invariant means that a range deletion at
     113             : // level N will necessarily shadow any keys within its bounds in level Y where
     114             : // Y > N. One wrinkle to this statement is that it only applies to keys that
     115             : // lie within the sstable bounds as well, but we get that guarantee due to the
     116             : // way the range deletion iterator and point iterator are bound together by a
     117             : // levelIter.
     118             : //
     119             : // Tying the above all together, we get a picture where each level (index in
     120             : // mergingIter.levels) is composed of both point operations (pX) and range
     121             : // deletions (rX). The range deletions for level X shadow both the point
     122             : // operations and range deletions for level Y where Y > X allowing mergingIter
     123             : // to skip processing entries in that shadow. For example, consider the
     124             : // scenario:
     125             : //
     126             : //      r0: a---e
     127             : //      r1:    d---h
     128             : //      r2:       g---k
     129             : //      r3:          j---n
     130             : //      r4:             m---q
     131             : //
     132             : // This is showing 5 levels of range deletions. Consider what happens upon
     133             : // SeekGE("b"). We first seek the point iterator for level 0 (the point values
     134             : // are not shown above) and we then seek the range deletion iterator. That
     135             : // returns the tombstone [a,e). This tombstone tells us that all keys in the
     136             : // range [a,e) in lower levels are deleted so we can skip them. So we can
     137             : // adjust the seek key to "e", the tombstone end key. For level 1 we seek to
     138             : // "e" and find the range tombstone [d,h) and similar logic holds. By the time
     139             : // we get to level 4 we're seeking to "n".
     140             : //
     141             : // One consequence of not truncating tombstone end keys to sstable boundaries
     142             : // is the seeking process described above cannot always seek to the tombstone
     143             : // end key in the older level. For example, imagine in the above example r3 is
     144             : // a partitioned level (i.e., L1+ in our LSM), and the sstable containing [j,
     145             : // n) has "k" as its upper boundary. In this situation, compactions involving
     146             : // keys at or after "k" can output those keys to r4+, even if they're newer
     147             : // than our tombstone [j, n). So instead of seeking to "n" in r4 we can only
     148             : // seek to "k".  To achieve this, the instance variable `largestUserKey.`
     149             : // maintains the upper bounds of the current sstables in the partitioned
     150             : // levels. In this example, `levels[3].largestUserKey` holds "k", telling us to
     151             : // limit the seek triggered by a tombstone in r3 to "k".
     152             : //
     153             : // During actual iteration levels can contain both point operations and range
     154             : // deletions. Within a level, when a range deletion contains a point operation
     155             : // the sequence numbers must be checked to determine if the point operation is
     156             : // newer or older than the range deletion tombstone. The mergingIter maintains
     157             : // the invariant that the range deletion iterators for all levels newer that
     158             : // the current iteration key (L < m.heap.items[0].index) are positioned at the
     159             : // next (or previous during reverse iteration) range deletion tombstone. We
     160             : // know those levels don't contain a range deletion tombstone that covers the
     161             : // current key because if they did the current key would be deleted. The range
     162             : // deletion iterator for the current key's level is positioned at a range
     163             : // tombstone covering or past the current key. The position of all of other
     164             : // range deletion iterators is unspecified. Whenever a key from those levels
     165             : // becomes the current key, their range deletion iterators need to be
     166             : // positioned. This lazy positioning avoids seeking the range deletion
     167             : // iterators for keys that are never considered. (A similar bit of lazy
     168             : // evaluation can be done for the point iterators, but is still TBD).
     169             : //
     170             : // For a full example, consider the following setup:
     171             : //
     172             : //      p0:               o
     173             : //      r0:             m---q
     174             : //
     175             : //      p1:              n p
     176             : //      r1:       g---k
     177             : //
     178             : //      p2:  b d    i
     179             : //      r2: a---e           q----v
     180             : //
     181             : //      p3:     e
     182             : //      r3:
     183             : //
     184             : // If we start iterating from the beginning, the first key we encounter is "b"
     185             : // in p2. When the mergingIter is pointing at a valid entry, the range deletion
     186             : // iterators for all of the levels < m.heap.items[0].index are positioned at
     187             : // the next range tombstone past the current key. So r0 will point at [m,q) and
     188             : // r1 at [g,k). When the key "b" is encountered, we check to see if the current
     189             : // tombstone for r0 or r1 contains it, and whether the tombstone for r2, [a,e),
     190             : // contains and is newer than "b".
     191             : //
     192             : // Advancing the iterator finds the next key at "d". This is in the same level
     193             : // as the previous key "b" so we don't have to reposition any of the range
     194             : // deletion iterators, but merely check whether "d" is now contained by any of
     195             : // the range tombstones at higher levels or has stepped past the range
     196             : // tombstone in its own level or higher levels. In this case, there is nothing to be done.
     197             : //
     198             : // Advancing the iterator again finds "e". Since "e" comes from p3, we have to
     199             : // position the r3 range deletion iterator, which is empty. "e" is past the r2
     200             : // tombstone of [a,e) so we need to advance the r2 range deletion iterator to
     201             : // [q,v).
     202             : //
     203             : // The next key is "i". Because this key is in p2, a level above "e", we don't
     204             : // have to reposition any range deletion iterators and instead see that "i" is
     205             : // covered by the range tombstone [g,k). The iterator is immediately advanced
     206             : // to "n" which is covered by the range tombstone [m,q) causing the iterator to
     207             : // advance to "o" which is visible.
     208             : //
     209             : // # Error handling
     210             : //
     211             : // Any iterator operation may fail. The InternalIterator contract dictates that
     212             : // an iterator must return a nil internal key when an error occurs, and a
     213             : // subsequent call to Error() should return the error value. The exported
     214             : // merging iterator positioning methods must adhere to this contract by setting
     215             : // m.err to hold any error encountered by the individual level iterators and
     216             : // returning a nil internal key. Some internal helpers (eg,
     217             : // find[Next|Prev]Entry) also adhere to this contract, setting m.err directly).
     218             : // Other internal functions return an explicit error return value and DO NOT set
     219             : // m.err, relying on the caller to set m.err appropriately.
     220             : //
     221             : // TODO(jackson): Update the InternalIterator interface to return explicit error
     222             : // return values (and an *InternalKV pointer).
     223             : //
     224             : // TODO(peter,rangedel): For testing, advance the iterator through various
     225             : // scenarios and have each step display the current state (i.e. the current
     226             : // heap and range-del iterator positioning).
     227             : type mergingIter struct {
     228             :         logger        Logger
     229             :         split         Split
     230             :         dir           int
     231             :         snapshot      uint64
     232             :         batchSnapshot uint64
     233             :         levels        []mergingIterLevel
     234             :         heap          mergingIterHeap
     235             :         err           error
     236             :         prefix        []byte
     237             :         lower         []byte
     238             :         upper         []byte
     239             :         stats         *InternalIteratorStats
     240             : 
     241             :         // levelsPositioned, if non-nil, is a slice of the same length as levels.
     242             :         // It's used by NextPrefix to record which levels have already been
     243             :         // repositioned. It's created lazily by the first call to NextPrefix.
     244             :         levelsPositioned []bool
     245             : 
     246             :         combinedIterState *combinedIterState
     247             : 
     248             :         // Used in some tests to disable the random disabling of seek optimizations.
     249             :         forceEnableSeekOpt bool
     250             : }
     251             : 
     252             : // mergingIter implements the base.InternalIterator interface.
     253             : var _ base.InternalIterator = (*mergingIter)(nil)
     254             : 
     255             : // newMergingIter returns an iterator that merges its input. Walking the
     256             : // resultant iterator will return all key/value pairs of all input iterators
     257             : // in strictly increasing key order, as defined by cmp. It is permissible to
     258             : // pass a nil split parameter if the caller is never going to call
     259             : // SeekPrefixGE.
     260             : //
     261             : // The input's key ranges may overlap, but there are assumed to be no duplicate
     262             : // keys: if iters[i] contains a key k then iters[j] will not contain that key k.
     263             : //
     264             : // None of the iters may be nil.
     265             : func newMergingIter(
     266             :         logger Logger,
     267             :         stats *base.InternalIteratorStats,
     268             :         cmp Compare,
     269             :         split Split,
     270             :         iters ...internalIterator,
     271           1 : ) *mergingIter {
     272           1 :         m := &mergingIter{}
     273           1 :         levels := make([]mergingIterLevel, len(iters))
     274           1 :         for i := range levels {
     275           1 :                 levels[i].iter = iters[i]
     276           1 :         }
     277           1 :         m.init(&IterOptions{logger: logger}, stats, cmp, split, levels...)
     278           1 :         return m
     279             : }
     280             : 
     281             : func (m *mergingIter) init(
     282             :         opts *IterOptions,
     283             :         stats *base.InternalIteratorStats,
     284             :         cmp Compare,
     285             :         split Split,
     286             :         levels ...mergingIterLevel,
     287           1 : ) {
     288           1 :         m.err = nil // clear cached iteration error
     289           1 :         m.logger = opts.getLogger()
     290           1 :         if opts != nil {
     291           1 :                 m.lower = opts.LowerBound
     292           1 :                 m.upper = opts.UpperBound
     293           1 :         }
     294           1 :         m.snapshot = InternalKeySeqNumMax
     295           1 :         m.batchSnapshot = InternalKeySeqNumMax
     296           1 :         m.levels = levels
     297           1 :         m.heap.cmp = cmp
     298           1 :         m.split = split
     299           1 :         m.stats = stats
     300           1 :         if cap(m.heap.items) < len(levels) {
     301           1 :                 m.heap.items = make([]*mergingIterLevel, 0, len(levels))
     302           1 :         } else {
     303           1 :                 m.heap.items = m.heap.items[:0]
     304           1 :         }
     305           1 :         for l := range m.levels {
     306           1 :                 m.levels[l].index = l
     307           1 :         }
     308             : }
     309             : 
     310           1 : func (m *mergingIter) initHeap() {
     311           1 :         m.heap.items = m.heap.items[:0]
     312           1 :         for i := range m.levels {
     313           1 :                 if l := &m.levels[i]; l.iterKV != nil {
     314           1 :                         m.heap.items = append(m.heap.items, l)
     315           1 :                 }
     316             :         }
     317           1 :         m.heap.init()
     318             : }
     319             : 
     320           1 : func (m *mergingIter) initMinHeap() error {
     321           1 :         m.dir = 1
     322           1 :         m.heap.reverse = false
     323           1 :         m.initHeap()
     324           1 :         return m.initMinRangeDelIters(-1)
     325           1 : }
     326             : 
     327             : // The level of the previous top element was oldTopLevel. Note that all range delete
     328             : // iterators < oldTopLevel are positioned past the key of the previous top element and
     329             : // the range delete iterator == oldTopLevel is positioned at or past the key of the
     330             : // previous top element. We need to position the range delete iterators from oldTopLevel + 1
     331             : // to the level of the current top element.
     332           1 : func (m *mergingIter) initMinRangeDelIters(oldTopLevel int) error {
     333           1 :         if m.heap.len() == 0 {
     334           1 :                 return nil
     335           1 :         }
     336             : 
     337             :         // Position the range-del iterators at levels <= m.heap.items[0].index.
     338           1 :         item := m.heap.items[0]
     339           1 :         for level := oldTopLevel + 1; level <= item.index; level++ {
     340           1 :                 l := &m.levels[level]
     341           1 :                 if l.rangeDelIter == nil {
     342           1 :                         continue
     343             :                 }
     344           1 :                 var err error
     345           1 :                 l.tombstone, err = l.rangeDelIter.SeekGE(item.iterKV.K.UserKey)
     346           1 :                 if err != nil {
     347           0 :                         return err
     348           0 :                 }
     349             :         }
     350           1 :         return nil
     351             : }
     352             : 
     353           1 : func (m *mergingIter) initMaxHeap() error {
     354           1 :         m.dir = -1
     355           1 :         m.heap.reverse = true
     356           1 :         m.initHeap()
     357           1 :         return m.initMaxRangeDelIters(-1)
     358           1 : }
     359             : 
     360             : // The level of the previous top element was oldTopLevel. Note that all range delete
     361             : // iterators < oldTopLevel are positioned before the key of the previous top element and
     362             : // the range delete iterator == oldTopLevel is positioned at or before the key of the
     363             : // previous top element. We need to position the range delete iterators from oldTopLevel + 1
     364             : // to the level of the current top element.
     365           1 : func (m *mergingIter) initMaxRangeDelIters(oldTopLevel int) error {
     366           1 :         if m.heap.len() == 0 {
     367           1 :                 return nil
     368           1 :         }
     369             :         // Position the range-del iterators at levels <= m.heap.items[0].index.
     370           1 :         item := m.heap.items[0]
     371           1 :         for level := oldTopLevel + 1; level <= item.index; level++ {
     372           1 :                 l := &m.levels[level]
     373           1 :                 if l.rangeDelIter == nil {
     374           1 :                         continue
     375             :                 }
     376           1 :                 tomb, err := keyspan.SeekLE(m.heap.cmp, l.rangeDelIter, item.iterKV.K.UserKey)
     377           1 :                 if err != nil {
     378           0 :                         return err
     379           0 :                 }
     380           1 :                 l.tombstone = tomb
     381             :         }
     382           1 :         return nil
     383             : }
     384             : 
     385           1 : func (m *mergingIter) switchToMinHeap() error {
     386           1 :         if m.heap.len() == 0 {
     387           1 :                 if m.lower != nil {
     388           1 :                         m.SeekGE(m.lower, base.SeekGEFlagsNone)
     389           1 :                 } else {
     390           1 :                         m.First()
     391           1 :                 }
     392           1 :                 return m.err
     393             :         }
     394             : 
     395             :         // We're switching from using a max heap to a min heap. We need to advance
     396             :         // any iterator that is less than or equal to the current key. Consider the
     397             :         // scenario where we have 2 iterators being merged (user-key:seq-num):
     398             :         //
     399             :         // i1:     *a:2     b:2
     400             :         // i2: a:1      b:1
     401             :         //
     402             :         // The current key is a:2 and i2 is pointed at a:1. When we switch to forward
     403             :         // iteration, we want to return a key that is greater than a:2.
     404             : 
     405           1 :         key := m.heap.items[0].iterKV.K
     406           1 :         cur := m.heap.items[0]
     407           1 : 
     408           1 :         for i := range m.levels {
     409           1 :                 l := &m.levels[i]
     410           1 :                 if l == cur {
     411           1 :                         continue
     412             :                 }
     413           1 :                 for l.iterKV = l.iter.Next(); l.iterKV != nil; l.iterKV = l.iter.Next() {
     414           1 :                         if base.InternalCompare(m.heap.cmp, key, l.iterKV.K) < 0 {
     415           1 :                                 // key < iter-key
     416           1 :                                 break
     417             :                         }
     418             :                         // key >= iter-key
     419             :                 }
     420           1 :                 if l.iterKV == nil {
     421           1 :                         if err := l.iter.Error(); err != nil {
     422           1 :                                 return err
     423           1 :                         }
     424             :                 }
     425             :         }
     426             : 
     427             :         // Special handling for the current iterator because we were using its key
     428             :         // above.
     429           1 :         cur.iterKV = cur.iter.Next()
     430           1 :         if cur.iterKV == nil {
     431           1 :                 if err := cur.iter.Error(); err != nil {
     432           1 :                         return err
     433           1 :                 }
     434             :         }
     435           1 :         return m.initMinHeap()
     436             : }
     437             : 
     438           1 : func (m *mergingIter) switchToMaxHeap() error {
     439           1 :         if m.heap.len() == 0 {
     440           1 :                 if m.upper != nil {
     441           1 :                         m.SeekLT(m.upper, base.SeekLTFlagsNone)
     442           1 :                 } else {
     443           1 :                         m.Last()
     444           1 :                 }
     445           1 :                 return m.err
     446             :         }
     447             : 
     448             :         // We're switching from using a min heap to a max heap. We need to backup any
     449             :         // iterator that is greater than or equal to the current key. Consider the
     450             :         // scenario where we have 2 iterators being merged (user-key:seq-num):
     451             :         //
     452             :         // i1: a:2     *b:2
     453             :         // i2:     a:1      b:1
     454             :         //
     455             :         // The current key is b:2 and i2 is pointing at b:1. When we switch to
     456             :         // reverse iteration, we want to return a key that is less than b:2.
     457           1 :         key := m.heap.items[0].iterKV.K
     458           1 :         cur := m.heap.items[0]
     459           1 : 
     460           1 :         for i := range m.levels {
     461           1 :                 l := &m.levels[i]
     462           1 :                 if l == cur {
     463           1 :                         continue
     464             :                 }
     465             : 
     466           1 :                 for l.iterKV = l.iter.Prev(); l.iterKV != nil; l.iterKV = l.iter.Prev() {
     467           1 :                         if base.InternalCompare(m.heap.cmp, key, l.iterKV.K) > 0 {
     468           1 :                                 // key > iter-key
     469           1 :                                 break
     470             :                         }
     471             :                         // key <= iter-key
     472             :                 }
     473           1 :                 if l.iterKV == nil {
     474           1 :                         if err := l.iter.Error(); err != nil {
     475           1 :                                 return err
     476           1 :                         }
     477             :                 }
     478             :         }
     479             : 
     480             :         // Special handling for the current iterator because we were using its key
     481             :         // above.
     482           1 :         cur.iterKV = cur.iter.Prev()
     483           1 :         if cur.iterKV == nil {
     484           1 :                 if err := cur.iter.Error(); err != nil {
     485           1 :                         return err
     486           1 :                 }
     487             :         }
     488           1 :         return m.initMaxHeap()
     489             : }
     490             : 
     491             : // nextEntry unconditionally steps to the next entry. item is the current top
     492             : // item in the heap.
     493           1 : func (m *mergingIter) nextEntry(l *mergingIterLevel, succKey []byte) error {
     494           1 :         // INVARIANT: If in prefix iteration mode, item.iterKey must have a prefix equal
     495           1 :         // to m.prefix. This invariant is important for ensuring TrySeekUsingNext
     496           1 :         // optimizations behave correctly.
     497           1 :         //
     498           1 :         // During prefix iteration, the iterator does not have a full view of the
     499           1 :         // LSM. Some level iterators may omit keys that are known to fall outside
     500           1 :         // the seek prefix (eg, due to sstable bloom filter exclusion). It's
     501           1 :         // important that in such cases we don't position any iterators beyond
     502           1 :         // m.prefix, because doing so may interfere with future seeks.
     503           1 :         //
     504           1 :         // Let prefixes P1 < P2 < P3. Imagine a SeekPrefixGE to prefix P1, followed
     505           1 :         // by a SeekPrefixGE to prefix P2. Imagine there exist live keys at prefix
     506           1 :         // P2, but they're not visible to the SeekPrefixGE(P1) (because of
     507           1 :         // bloom-filter exclusion or a range tombstone that deletes prefix P1 but
     508           1 :         // not P2). If the SeekPrefixGE(P1) is allowed to move any level iterators
     509           1 :         // to P3, the SeekPrefixGE(P2, TrySeekUsingNext=true) may mistakenly think
     510           1 :         // the level contains no point keys or range tombstones within the prefix
     511           1 :         // P2. Care is taken to avoid ever advancing the iterator beyond the current
     512           1 :         // prefix. If nextEntry is ever invoked while we're already beyond the
     513           1 :         // current prefix, we're violating the invariant.
     514           1 :         if invariants.Enabled && m.prefix != nil {
     515           1 :                 if p := m.split.Prefix(l.iterKV.K.UserKey); !bytes.Equal(m.prefix, p) {
     516           0 :                         m.logger.Fatalf("mergingIter: prefix violation: nexting beyond prefix %q; existing heap root %q\n%s",
     517           0 :                                 m.prefix, l.iterKV, debug.Stack())
     518           0 :                 }
     519             :         }
     520             : 
     521           1 :         oldTopLevel := l.index
     522           1 :         oldRangeDelIter := l.rangeDelIter
     523           1 : 
     524           1 :         if succKey == nil {
     525           1 :                 l.iterKV = l.iter.Next()
     526           1 :         } else {
     527           1 :                 l.iterKV = l.iter.NextPrefix(succKey)
     528           1 :         }
     529             : 
     530           1 :         if l.iterKV == nil {
     531           1 :                 if err := l.iter.Error(); err != nil {
     532           1 :                         return err
     533           1 :                 }
     534           1 :                 m.heap.pop()
     535           1 :         } else {
     536           1 :                 if m.prefix != nil && !bytes.Equal(m.prefix, m.split.Prefix(l.iterKV.K.UserKey)) {
     537           1 :                         // Set keys without a matching prefix to their zero values when in prefix
     538           1 :                         // iteration mode and remove iterated level from heap.
     539           1 :                         l.iterKV = nil
     540           1 :                         m.heap.pop()
     541           1 :                 } else if m.heap.len() > 1 {
     542           1 :                         m.heap.fix(0)
     543           1 :                 }
     544           1 :                 if l.rangeDelIter != oldRangeDelIter {
     545           1 :                         // The rangeDelIter changed which indicates that the l.iter moved to the
     546           1 :                         // next sstable. We have to update the tombstone for oldTopLevel as well.
     547           1 :                         oldTopLevel--
     548           1 :                 }
     549             :         }
     550             : 
     551             :         // The cached tombstones are only valid for the levels
     552             :         // [0,oldTopLevel]. Updated the cached tombstones for any levels in the range
     553             :         // [oldTopLevel+1,heap[0].index].
     554           1 :         return m.initMinRangeDelIters(oldTopLevel)
     555             : }
     556             : 
     557             : // isNextEntryDeleted starts from the current entry (as the next entry) and if
     558             : // it is deleted, moves the iterators forward as needed and returns true, else
     559             : // it returns false. item is the top item in the heap. If any of the required
     560             : // iterator operations error, the error is returned without updating m.err.
     561             : //
     562             : // During prefix iteration mode, isNextEntryDeleted will exhaust the iterator by
     563             : // clearing the heap if the deleted key(s) extend beyond the iteration prefix
     564             : // during prefix-iteration mode.
     565           1 : func (m *mergingIter) isNextEntryDeleted(item *mergingIterLevel) (bool, error) {
     566           1 :         // Look for a range deletion tombstone containing item.iterKV at higher
     567           1 :         // levels (level < item.index). If we find such a range tombstone we know
     568           1 :         // it deletes the key in the current level. Also look for a range
     569           1 :         // deletion at the current level (level == item.index). If we find such a
     570           1 :         // range deletion we need to check whether it is newer than the current
     571           1 :         // entry.
     572           1 :         for level := 0; level <= item.index; level++ {
     573           1 :                 l := &m.levels[level]
     574           1 :                 if l.rangeDelIter == nil || l.tombstone == nil {
     575           1 :                         // If l.tombstone is nil, there are no further tombstones
     576           1 :                         // in the current sstable in the current (forward) iteration
     577           1 :                         // direction.
     578           1 :                         continue
     579             :                 }
     580           1 :                 if m.heap.cmp(l.tombstone.End, item.iterKV.K.UserKey) <= 0 {
     581           1 :                         // The current key is at or past the tombstone end key.
     582           1 :                         //
     583           1 :                         // NB: for the case that this l.rangeDelIter is provided by a levelIter we know that
     584           1 :                         // the levelIter must be positioned at a key >= item.iterKV. So it is sufficient to seek the
     585           1 :                         // current l.rangeDelIter (since any range del iterators that will be provided by the
     586           1 :                         // levelIter in the future cannot contain item.iterKV). Also, it is possible that we
     587           1 :                         // will encounter parts of the range delete that should be ignored -- we handle that
     588           1 :                         // below.
     589           1 :                         var err error
     590           1 :                         l.tombstone, err = l.rangeDelIter.SeekGE(item.iterKV.K.UserKey)
     591           1 :                         if err != nil {
     592           1 :                                 return false, err
     593           1 :                         }
     594             :                 }
     595           1 :                 if l.tombstone == nil {
     596           1 :                         continue
     597             :                 }
     598             : 
     599           1 :                 if l.tombstone.VisibleAt(m.snapshot) && m.heap.cmp(l.tombstone.Start, item.iterKV.K.UserKey) <= 0 {
     600           1 :                         if level < item.index {
     601           1 :                                 // We could also do m.seekGE(..., level + 1). The levels from
     602           1 :                                 // [level + 1, item.index) are already after item.iterKV so seeking them may be
     603           1 :                                 // wasteful.
     604           1 : 
     605           1 :                                 // We can seek up to tombstone.End.
     606           1 :                                 //
     607           1 :                                 // Progress argument: Since this file is at a higher level than item.iterKV we know
     608           1 :                                 // that the iterator in this file must be positioned within its bounds and at a key
     609           1 :                                 // X > item.iterKV (otherwise it would be the min of the heap). It is not
     610           1 :                                 // possible for X.UserKey == item.iterKV.UserKey, since it is incompatible with
     611           1 :                                 // X > item.iterKV (a lower version cannot be in a higher sstable), so it must be that
     612           1 :                                 // X.UserKey > item.iterKV.UserKey. Which means l.largestUserKey > item.key.UserKey.
     613           1 :                                 // We also know that l.tombstone.End > item.iterKV.UserKey. So the min of these,
     614           1 :                                 // seekKey, computed below, is > item.iterKV.UserKey, so the call to seekGE() will
     615           1 :                                 // make forward progress.
     616           1 :                                 seekKey := l.tombstone.End
     617           1 :                                 // This seek is not directly due to a SeekGE call, so we don't know
     618           1 :                                 // enough about the underlying iterator positions, and so we keep the
     619           1 :                                 // try-seek-using-next optimization disabled. Additionally, if we're in
     620           1 :                                 // prefix-seek mode and a re-seek would have moved us past the original
     621           1 :                                 // prefix, we can remove all merging iter levels below the rangedel
     622           1 :                                 // tombstone's level and return immediately instead of re-seeking. This
     623           1 :                                 // is correct since those levels cannot provide a key that matches the
     624           1 :                                 // prefix, and is also visible. Additionally, this is important to make
     625           1 :                                 // subsequent `TrySeekUsingNext` work correctly, as a re-seek on a
     626           1 :                                 // different prefix could have resulted in this iterator skipping visible
     627           1 :                                 // keys at prefixes in between m.prefix and seekKey, that are currently
     628           1 :                                 // not in the heap due to a bloom filter mismatch.
     629           1 :                                 //
     630           1 :                                 // Additionally, we set the relative-seek flag. This is
     631           1 :                                 // important when iterating with lazy combined iteration. If
     632           1 :                                 // there's a range key between this level's current file and the
     633           1 :                                 // file the seek will land on, we need to detect it in order to
     634           1 :                                 // trigger construction of the combined iterator.
     635           1 :                                 if m.prefix != nil {
     636           1 :                                         if !bytes.Equal(m.prefix, m.split.Prefix(seekKey)) {
     637           1 :                                                 for i := item.index; i < len(m.levels); i++ {
     638           1 :                                                         // Remove this level from the heap. Setting iterKV
     639           1 :                                                         // to nil should be sufficient for initMinHeap to
     640           1 :                                                         // not re-initialize the heap with them in it. Other
     641           1 :                                                         // fields in mergingIterLevel can remain as-is; the
     642           1 :                                                         // iter/rangeDelIter needs to stay intact for future
     643           1 :                                                         // trySeekUsingNexts to work, the level iter
     644           1 :                                                         // boundary context is owned by the levelIter which
     645           1 :                                                         // is not being repositioned, and any tombstones in
     646           1 :                                                         // these levels will be irrelevant for us anyway.
     647           1 :                                                         m.levels[i].iterKV = nil
     648           1 :                                                 }
     649             :                                                 // TODO(bilal): Consider a more efficient way of removing levels from
     650             :                                                 // the heap without reinitializing all of it. This would likely
     651             :                                                 // necessitate tracking the heap positions of each mergingIterHeap
     652             :                                                 // item in the mergingIterLevel, and then swapping that item in the
     653             :                                                 // heap with the last-positioned heap item, and shrinking the heap by
     654             :                                                 // one.
     655           1 :                                                 if err := m.initMinHeap(); err != nil {
     656           0 :                                                         return false, err
     657           0 :                                                 }
     658           1 :                                                 return true, nil
     659             :                                         }
     660             :                                 }
     661           1 :                                 if err := m.seekGE(seekKey, item.index, base.SeekGEFlagsNone.EnableRelativeSeek()); err != nil {
     662           1 :                                         return false, err
     663           1 :                                 }
     664           1 :                                 return true, nil
     665             :                         }
     666           1 :                         if l.tombstone.CoversAt(m.snapshot, item.iterKV.SeqNum()) {
     667           1 :                                 if err := m.nextEntry(item, nil /* succKey */); err != nil {
     668           0 :                                         return false, err
     669           0 :                                 }
     670           1 :                                 return true, nil
     671             :                         }
     672             :                 }
     673             :         }
     674           1 :         return false, nil
     675             : }
     676             : 
     677             : // Starting from the current entry, finds the first (next) entry that can be returned.
     678             : //
     679             : // If an error occurs, m.err is updated to hold the error and findNextentry
     680             : // returns a nil internal key.
     681           1 : func (m *mergingIter) findNextEntry() *base.InternalKV {
     682           1 :         for m.heap.len() > 0 && m.err == nil {
     683           1 :                 item := m.heap.items[0]
     684           1 : 
     685           1 :                 // The levelIter internal iterator will interleave exclusive sentinel
     686           1 :                 // keys to keep files open until their range deletions are no longer
     687           1 :                 // necessary. Sometimes these are interleaved with the user key of a
     688           1 :                 // file's largest key, in which case they may simply be stepped over to
     689           1 :                 // move to the next file in the forward direction. Other times they're
     690           1 :                 // interleaved at the user key of the user-iteration boundary, if that
     691           1 :                 // falls within the bounds of a file. In the latter case, there are no
     692           1 :                 // more keys < m.upper, and we can stop iterating.
     693           1 :                 //
     694           1 :                 // We perform a key comparison to differentiate between these two cases.
     695           1 :                 // This key comparison is considered okay because it only happens for
     696           1 :                 // sentinel keys. It may be eliminated after #2863.
     697           1 :                 if m.levels[item.index].iterKV.K.IsExclusiveSentinel() {
     698           1 :                         if m.upper != nil && m.heap.cmp(m.levels[item.index].iterKV.K.UserKey, m.upper) >= 0 {
     699           1 :                                 break
     700             :                         }
     701             :                         // This key is the largest boundary of a file and can be skipped now
     702             :                         // that the file's range deletions are no longer relevant.
     703           1 :                         m.err = m.nextEntry(item, nil /* succKey */)
     704           1 :                         if m.err != nil {
     705           1 :                                 return nil
     706           1 :                         }
     707           1 :                         continue
     708             :                 }
     709             : 
     710           1 :                 m.addItemStats(item)
     711           1 : 
     712           1 :                 // Check if the heap root key is deleted by a range tombstone in a
     713           1 :                 // higher level. If it is, isNextEntryDeleted will advance the iterator
     714           1 :                 // to a later key (through seeking or nexting).
     715           1 :                 isDeleted, err := m.isNextEntryDeleted(item)
     716           1 :                 if err != nil {
     717           1 :                         m.err = err
     718           1 :                         return nil
     719           1 :                 } else if isDeleted {
     720           1 :                         m.stats.PointsCoveredByRangeTombstones++
     721           1 :                         continue
     722             :                 }
     723             : 
     724             :                 // Check if the key is visible at the iterator sequence numbers.
     725           1 :                 if !item.iterKV.Visible(m.snapshot, m.batchSnapshot) {
     726           1 :                         m.err = m.nextEntry(item, nil /* succKey */)
     727           1 :                         if m.err != nil {
     728           0 :                                 return nil
     729           0 :                         }
     730           1 :                         continue
     731             :                 }
     732             : 
     733             :                 // The heap root is visible and not deleted by any range tombstones.
     734             :                 // Return it.
     735           1 :                 return item.iterKV
     736             :         }
     737           1 :         return nil
     738             : }
     739             : 
     740             : // Steps to the prev entry. item is the current top item in the heap.
     741           1 : func (m *mergingIter) prevEntry(l *mergingIterLevel) error {
     742           1 :         oldTopLevel := l.index
     743           1 :         oldRangeDelIter := l.rangeDelIter
     744           1 :         if l.iterKV = l.iter.Prev(); l.iterKV != nil {
     745           1 :                 if m.heap.len() > 1 {
     746           1 :                         m.heap.fix(0)
     747           1 :                 }
     748           1 :                 if l.rangeDelIter != oldRangeDelIter && l.rangeDelIter != nil {
     749           1 :                         // The rangeDelIter changed which indicates that the l.iter moved to the
     750           1 :                         // previous sstable. We have to update the tombstone for oldTopLevel as
     751           1 :                         // well.
     752           1 :                         oldTopLevel--
     753           1 :                 }
     754           1 :         } else {
     755           1 :                 if err := l.iter.Error(); err != nil {
     756           1 :                         return err
     757           1 :                 }
     758           1 :                 m.heap.pop()
     759             :         }
     760             : 
     761             :         // The cached tombstones are only valid for the levels
     762             :         // [0,oldTopLevel]. Updated the cached tombstones for any levels in the range
     763             :         // [oldTopLevel+1,heap[0].index].
     764           1 :         return m.initMaxRangeDelIters(oldTopLevel)
     765             : }
     766             : 
     767             : // isPrevEntryDeleted() starts from the current entry (as the prev entry) and if it is deleted,
     768             : // moves the iterators backward as needed and returns true, else it returns false. item is the top
     769             : // item in the heap.
     770           1 : func (m *mergingIter) isPrevEntryDeleted(item *mergingIterLevel) (bool, error) {
     771           1 :         // Look for a range deletion tombstone containing item.iterKV at higher
     772           1 :         // levels (level < item.index). If we find such a range tombstone we know
     773           1 :         // it deletes the key in the current level. Also look for a range
     774           1 :         // deletion at the current level (level == item.index). If we find such a
     775           1 :         // range deletion we need to check whether it is newer than the current
     776           1 :         // entry.
     777           1 :         for level := 0; level <= item.index; level++ {
     778           1 :                 l := &m.levels[level]
     779           1 :                 if l.rangeDelIter == nil || l.tombstone == nil {
     780           1 :                         // If l.tombstone is nil, there are no further tombstones
     781           1 :                         // in the current sstable in the current (reverse) iteration
     782           1 :                         // direction.
     783           1 :                         continue
     784             :                 }
     785           1 :                 if m.heap.cmp(item.iterKV.K.UserKey, l.tombstone.Start) < 0 {
     786           1 :                         // The current key is before the tombstone start key.
     787           1 :                         //
     788           1 :                         // NB: for the case that this l.rangeDelIter is provided by a levelIter we know that
     789           1 :                         // the levelIter must be positioned at a key < item.iterKV. So it is sufficient to seek the
     790           1 :                         // current l.rangeDelIter (since any range del iterators that will be provided by the
     791           1 :                         // levelIter in the future cannot contain item.iterKV). Also, it is it is possible that we
     792           1 :                         // will encounter parts of the range delete that should be ignored -- we handle that
     793           1 :                         // below.
     794           1 : 
     795           1 :                         tomb, err := keyspan.SeekLE(m.heap.cmp, l.rangeDelIter, item.iterKV.K.UserKey)
     796           1 :                         if err != nil {
     797           0 :                                 return false, err
     798           0 :                         }
     799           1 :                         l.tombstone = tomb
     800             :                 }
     801           1 :                 if l.tombstone == nil {
     802           1 :                         continue
     803             :                 }
     804           1 :                 if l.tombstone.VisibleAt(m.snapshot) && m.heap.cmp(l.tombstone.End, item.iterKV.K.UserKey) > 0 {
     805           1 :                         if level < item.index {
     806           1 :                                 // We could also do m.seekLT(..., level + 1). The levels from
     807           1 :                                 // [level + 1, item.index) are already before item.iterKV so seeking them may be
     808           1 :                                 // wasteful.
     809           1 : 
     810           1 :                                 // We can seek up to tombstone.Start.UserKey.
     811           1 :                                 //
     812           1 :                                 // Progress argument: We know that the iterator in this file is positioned within
     813           1 :                                 // its bounds and at a key X < item.iterKV (otherwise it would be the max of the heap).
     814           1 :                                 // So smallestUserKey <= item.iterKV.UserKey and we already know that
     815           1 :                                 // l.tombstone.Start.UserKey <= item.iterKV.UserKey. So the seekKey computed below
     816           1 :                                 // is <= item.iterKV.UserKey, and since we do a seekLT() we will make backwards
     817           1 :                                 // progress.
     818           1 :                                 seekKey := l.tombstone.Start
     819           1 :                                 // We set the relative-seek flag. This is important when
     820           1 :                                 // iterating with lazy combined iteration. If there's a range
     821           1 :                                 // key between this level's current file and the file the seek
     822           1 :                                 // will land on, we need to detect it in order to trigger
     823           1 :                                 // construction of the combined iterator.
     824           1 :                                 if err := m.seekLT(seekKey, item.index, base.SeekLTFlagsNone.EnableRelativeSeek()); err != nil {
     825           1 :                                         return false, err
     826           1 :                                 }
     827           1 :                                 return true, nil
     828             :                         }
     829           1 :                         if l.tombstone.CoversAt(m.snapshot, item.iterKV.SeqNum()) {
     830           1 :                                 if err := m.prevEntry(item); err != nil {
     831           0 :                                         return false, err
     832           0 :                                 }
     833           1 :                                 return true, nil
     834             :                         }
     835             :                 }
     836             :         }
     837           1 :         return false, nil
     838             : }
     839             : 
     840             : // Starting from the current entry, finds the first (prev) entry that can be returned.
     841             : //
     842             : // If an error occurs, m.err is updated to hold the error and findNextentry
     843             : // returns a nil internal key.
     844           1 : func (m *mergingIter) findPrevEntry() *base.InternalKV {
     845           1 :         for m.heap.len() > 0 && m.err == nil {
     846           1 :                 item := m.heap.items[0]
     847           1 : 
     848           1 :                 // The levelIter internal iterator will interleave exclusive sentinel
     849           1 :                 // keys to keep files open until their range deletions are no longer
     850           1 :                 // necessary. Sometimes these are interleaved with the user key of a
     851           1 :                 // file's smallest key, in which case they may simply be stepped over to
     852           1 :                 // move to the next file in the backward direction. Other times they're
     853           1 :                 // interleaved at the user key of the user-iteration boundary, if that
     854           1 :                 // falls within the bounds of a file. In the latter case, there are no
     855           1 :                 // more keys ≥ m.lower, and we can stop iterating.
     856           1 :                 //
     857           1 :                 // We perform a key comparison to differentiate between these two cases.
     858           1 :                 // This key comparison is considered okay because it only happens for
     859           1 :                 // sentinel keys. It may be eliminated after #2863.
     860           1 :                 if m.levels[item.index].iterKV.K.IsExclusiveSentinel() {
     861           1 :                         if m.lower != nil && m.heap.cmp(m.levels[item.index].iterKV.K.UserKey, m.lower) <= 0 {
     862           1 :                                 break
     863             :                         }
     864             :                         // This key is the smallest boundary of a file and can be skipped
     865             :                         // now that the file's range deletions are no longer relevant.
     866           1 :                         m.err = m.prevEntry(item)
     867           1 :                         if m.err != nil {
     868           1 :                                 return nil
     869           1 :                         }
     870           1 :                         continue
     871             :                 }
     872             : 
     873           1 :                 m.addItemStats(item)
     874           1 :                 if isDeleted, err := m.isPrevEntryDeleted(item); err != nil {
     875           1 :                         m.err = err
     876           1 :                         return nil
     877           1 :                 } else if isDeleted {
     878           1 :                         m.stats.PointsCoveredByRangeTombstones++
     879           1 :                         continue
     880             :                 }
     881           1 :                 if item.iterKV.Visible(m.snapshot, m.batchSnapshot) {
     882           1 :                         return item.iterKV
     883           1 :                 }
     884           1 :                 m.err = m.prevEntry(item)
     885             :         }
     886           1 :         return nil
     887             : }
     888             : 
     889             : // Seeks levels >= level to >= key. Additionally uses range tombstones to extend the seeks.
     890             : //
     891             : // If an error occurs, seekGE returns the error without setting m.err.
     892           1 : func (m *mergingIter) seekGE(key []byte, level int, flags base.SeekGEFlags) error {
     893           1 :         // When seeking, we can use tombstones to adjust the key we seek to on each
     894           1 :         // level. Consider the series of range tombstones:
     895           1 :         //
     896           1 :         //   1: a---e
     897           1 :         //   2:    d---h
     898           1 :         //   3:       g---k
     899           1 :         //   4:          j---n
     900           1 :         //   5:             m---q
     901           1 :         //
     902           1 :         // If we SeekGE("b") we also find the tombstone "b" resides within in the
     903           1 :         // first level which is [a,e). Regardless of whether this tombstone deletes
     904           1 :         // "b" in that level, we know it deletes "b" in all lower levels, so we
     905           1 :         // adjust the search key in the next level to the tombstone end key "e". We
     906           1 :         // then SeekGE("e") in the second level and find the corresponding tombstone
     907           1 :         // [d,h). This process continues and we end up seeking for "h" in the 3rd
     908           1 :         // level, "k" in the 4th level and "n" in the last level.
     909           1 :         //
     910           1 :         // TODO(peter,rangedel): In addition to the above we can delay seeking a
     911           1 :         // level (and any lower levels) when the current iterator position is
     912           1 :         // contained within a range tombstone at a higher level.
     913           1 : 
     914           1 :         // Deterministically disable the TrySeekUsingNext optimizations sometimes in
     915           1 :         // invariant builds to encourage the metamorphic tests to surface bugs. Note
     916           1 :         // that we cannot disable the optimization within individual levels. It must
     917           1 :         // be disabled for all levels or none. If one lower-level iterator performs
     918           1 :         // a fresh seek whereas another takes advantage of its current iterator
     919           1 :         // position, the heap can become inconsistent. Consider the following
     920           1 :         // example:
     921           1 :         //
     922           1 :         //     L5:  [ [b-c) ]  [ d ]*
     923           1 :         //     L6:  [  b ]           [e]*
     924           1 :         //
     925           1 :         // Imagine a SeekGE(a). The [b-c) range tombstone deletes the L6 point key
     926           1 :         // 'b', resulting in the iterator positioned at d with the heap:
     927           1 :         //
     928           1 :         //     {L5: d, L6: e}
     929           1 :         //
     930           1 :         // A subsequent SeekGE(b) is seeking to a larger key, so the caller may set
     931           1 :         // TrySeekUsingNext()=true. If the L5 iterator used the TrySeekUsingNext
     932           1 :         // optimization but the L6 iterator did not, the iterator would have the
     933           1 :         // heap:
     934           1 :         //
     935           1 :         //     {L6: b, L5: d}
     936           1 :         //
     937           1 :         // Because the L5 iterator has already advanced to the next sstable, the
     938           1 :         // merging iterator cannot observe the [b-c) range tombstone and will
     939           1 :         // mistakenly return L6's deleted point key 'b'.
     940           1 :         if invariants.Enabled && flags.TrySeekUsingNext() && !m.forceEnableSeekOpt &&
     941           1 :                 disableSeekOpt(key, uintptr(unsafe.Pointer(m))) {
     942           1 :                 flags = flags.DisableTrySeekUsingNext()
     943           1 :         }
     944             : 
     945           1 :         for ; level < len(m.levels); level++ {
     946           1 :                 if invariants.Enabled && m.lower != nil && m.heap.cmp(key, m.lower) < 0 {
     947           0 :                         m.logger.Fatalf("mergingIter: lower bound violation: %s < %s\n%s", key, m.lower, debug.Stack())
     948           0 :                 }
     949             : 
     950           1 :                 l := &m.levels[level]
     951           1 :                 if m.prefix != nil {
     952           1 :                         l.iterKV = l.iter.SeekPrefixGE(m.prefix, key, flags)
     953           1 :                         if l.iterKV != nil {
     954           1 :                                 if !bytes.Equal(m.prefix, m.split.Prefix(l.iterKV.K.UserKey)) {
     955           1 :                                         // Prevent keys without a matching prefix from being added to the heap by setting
     956           1 :                                         // iterKey and iterValue to their zero values before calling initMinHeap.
     957           1 :                                         l.iterKV = nil
     958           1 :                                 }
     959             :                         }
     960           1 :                 } else {
     961           1 :                         l.iterKV = l.iter.SeekGE(key, flags)
     962           1 :                 }
     963           1 :                 if l.iterKV == nil {
     964           1 :                         if err := l.iter.Error(); err != nil {
     965           1 :                                 return err
     966           1 :                         }
     967             :                 }
     968             : 
     969             :                 // If this level contains overlapping range tombstones, alter the seek
     970             :                 // key accordingly. Caveat: If we're performing lazy-combined iteration,
     971             :                 // we cannot alter the seek key: Range tombstones don't delete range
     972             :                 // keys, and there might exist live range keys within the range
     973             :                 // tombstone's span that need to be observed to trigger a switch to
     974             :                 // combined iteration.
     975           1 :                 if rangeDelIter := l.rangeDelIter; rangeDelIter != nil &&
     976           1 :                         (m.combinedIterState == nil || m.combinedIterState.initialized) {
     977           1 :                         // The level has a range-del iterator. Find the tombstone containing
     978           1 :                         // the search key.
     979           1 :                         var err error
     980           1 :                         l.tombstone, err = rangeDelIter.SeekGE(key)
     981           1 :                         if err != nil {
     982           0 :                                 return err
     983           0 :                         }
     984           1 :                         if l.tombstone != nil && l.tombstone.VisibleAt(m.snapshot) && m.heap.cmp(l.tombstone.Start, key) <= 0 {
     985           1 :                                 // Based on the containment condition tombstone.End > key, so
     986           1 :                                 // the assignment to key results in a monotonically
     987           1 :                                 // non-decreasing key across iterations of this loop.
     988           1 :                                 //
     989           1 :                                 // The adjustment of key here can only move it to a larger key.
     990           1 :                                 // Since the caller of seekGE guaranteed that the original key
     991           1 :                                 // was greater than or equal to m.lower, the new key will
     992           1 :                                 // continue to be greater than or equal to m.lower.
     993           1 :                                 key = l.tombstone.End
     994           1 :                         }
     995             :                 }
     996             :         }
     997           1 :         return m.initMinHeap()
     998             : }
     999             : 
    1000           0 : func (m *mergingIter) String() string {
    1001           0 :         return "merging"
    1002           0 : }
    1003             : 
    1004             : // SeekGE implements base.InternalIterator.SeekGE. Note that SeekGE only checks
    1005             : // the upper bound. It is up to the caller to ensure that key is greater than
    1006             : // or equal to the lower bound.
    1007           1 : func (m *mergingIter) SeekGE(key []byte, flags base.SeekGEFlags) *base.InternalKV {
    1008           1 :         m.prefix = nil
    1009           1 :         m.err = m.seekGE(key, 0 /* start level */, flags)
    1010           1 :         if m.err != nil {
    1011           1 :                 return nil
    1012           1 :         }
    1013           1 :         return m.findNextEntry()
    1014             : }
    1015             : 
    1016             : // SeekPrefixGE implements base.InternalIterator.SeekPrefixGE.
    1017           1 : func (m *mergingIter) SeekPrefixGE(prefix, key []byte, flags base.SeekGEFlags) *base.InternalKV {
    1018           1 :         return m.SeekPrefixGEStrict(prefix, key, flags)
    1019           1 : }
    1020             : 
    1021             : // SeekPrefixGEStrict implements topLevelIterator.SeekPrefixGEStrict. Note that
    1022             : // SeekPrefixGEStrict explicitly checks that the key has a matching prefix.
    1023             : func (m *mergingIter) SeekPrefixGEStrict(
    1024             :         prefix, key []byte, flags base.SeekGEFlags,
    1025           1 : ) *base.InternalKV {
    1026           1 :         m.prefix = prefix
    1027           1 :         m.err = m.seekGE(key, 0 /* start level */, flags)
    1028           1 :         if m.err != nil {
    1029           1 :                 return nil
    1030           1 :         }
    1031             : 
    1032           1 :         iterKV := m.findNextEntry()
    1033           1 :         if invariants.Enabled && iterKV != nil {
    1034           1 :                 if !bytes.Equal(m.prefix, m.split.Prefix(iterKV.K.UserKey)) {
    1035           0 :                         m.logger.Fatalf("mergingIter: prefix violation: returning key %q without prefix %q\n", iterKV, m.prefix)
    1036           0 :                 }
    1037             :         }
    1038           1 :         return iterKV
    1039             : }
    1040             : 
    1041             : // Seeks levels >= level to < key. Additionally uses range tombstones to extend the seeks.
    1042           1 : func (m *mergingIter) seekLT(key []byte, level int, flags base.SeekLTFlags) error {
    1043           1 :         // See the comment in seekGE regarding using tombstones to adjust the seek
    1044           1 :         // target per level.
    1045           1 :         m.prefix = nil
    1046           1 :         for ; level < len(m.levels); level++ {
    1047           1 :                 if invariants.Enabled && m.upper != nil && m.heap.cmp(key, m.upper) > 0 {
    1048           0 :                         m.logger.Fatalf("mergingIter: upper bound violation: %s > %s\n%s", key, m.upper, debug.Stack())
    1049           0 :                 }
    1050             : 
    1051           1 :                 l := &m.levels[level]
    1052           1 :                 l.iterKV = l.iter.SeekLT(key, flags)
    1053           1 :                 if l.iterKV == nil {
    1054           1 :                         if err := l.iter.Error(); err != nil {
    1055           1 :                                 return err
    1056           1 :                         }
    1057             :                 }
    1058             : 
    1059             :                 // If this level contains overlapping range tombstones, alter the seek
    1060             :                 // key accordingly. Caveat: If we're performing lazy-combined iteration,
    1061             :                 // we cannot alter the seek key: Range tombstones don't delete range
    1062             :                 // keys, and there might exist live range keys within the range
    1063             :                 // tombstone's span that need to be observed to trigger a switch to
    1064             :                 // combined iteration.
    1065           1 :                 if rangeDelIter := l.rangeDelIter; rangeDelIter != nil &&
    1066           1 :                         (m.combinedIterState == nil || m.combinedIterState.initialized) {
    1067           1 :                         // The level has a range-del iterator. Find the tombstone containing
    1068           1 :                         // the search key.
    1069           1 :                         tomb, err := keyspan.SeekLE(m.heap.cmp, rangeDelIter, key)
    1070           1 :                         if err != nil {
    1071           0 :                                 return err
    1072           0 :                         }
    1073           1 :                         l.tombstone = tomb
    1074           1 :                         // Since SeekLT is exclusive on `key` and a tombstone's end key is
    1075           1 :                         // also exclusive, a seek key equal to a tombstone's end key still
    1076           1 :                         // enables the seek optimization (Note this is different than the
    1077           1 :                         // check performed by (*keyspan.Span).Contains).
    1078           1 :                         if l.tombstone != nil && l.tombstone.VisibleAt(m.snapshot) &&
    1079           1 :                                 m.heap.cmp(key, l.tombstone.End) <= 0 {
    1080           1 :                                 // NB: Based on the containment condition
    1081           1 :                                 // tombstone.Start.UserKey <= key, so the assignment to key
    1082           1 :                                 // results in a monotonically non-increasing key across
    1083           1 :                                 // iterations of this loop.
    1084           1 :                                 //
    1085           1 :                                 // The adjustment of key here can only move it to a smaller key.
    1086           1 :                                 // Since the caller of seekLT guaranteed that the original key
    1087           1 :                                 // was less than or equal to m.upper, the new key will continue
    1088           1 :                                 // to be less than or equal to m.upper.
    1089           1 :                                 key = l.tombstone.Start
    1090           1 :                         }
    1091             :                 }
    1092             :         }
    1093             : 
    1094           1 :         return m.initMaxHeap()
    1095             : }
    1096             : 
    1097             : // SeekLT implements base.InternalIterator.SeekLT. Note that SeekLT only checks
    1098             : // the lower bound. It is up to the caller to ensure that key is less than the
    1099             : // upper bound.
    1100           1 : func (m *mergingIter) SeekLT(key []byte, flags base.SeekLTFlags) *base.InternalKV {
    1101           1 :         m.prefix = nil
    1102           1 :         m.err = m.seekLT(key, 0 /* start level */, flags)
    1103           1 :         if m.err != nil {
    1104           1 :                 return nil
    1105           1 :         }
    1106           1 :         return m.findPrevEntry()
    1107             : }
    1108             : 
    1109             : // First implements base.InternalIterator.First. Note that First only checks
    1110             : // the upper bound. It is up to the caller to ensure that key is greater than
    1111             : // or equal to the lower bound (e.g. via a call to SeekGE(lower)).
    1112           1 : func (m *mergingIter) First() *base.InternalKV {
    1113           1 :         m.err = nil // clear cached iteration error
    1114           1 :         m.prefix = nil
    1115           1 :         m.heap.items = m.heap.items[:0]
    1116           1 :         for i := range m.levels {
    1117           1 :                 l := &m.levels[i]
    1118           1 :                 l.iterKV = l.iter.First()
    1119           1 :                 if l.iterKV == nil {
    1120           1 :                         if m.err = l.iter.Error(); m.err != nil {
    1121           1 :                                 return nil
    1122           1 :                         }
    1123             :                 }
    1124             :         }
    1125           1 :         if m.err = m.initMinHeap(); m.err != nil {
    1126           0 :                 return nil
    1127           0 :         }
    1128           1 :         return m.findNextEntry()
    1129             : }
    1130             : 
    1131             : // Last implements base.InternalIterator.Last. Note that Last only checks the
    1132             : // lower bound. It is up to the caller to ensure that key is less than the
    1133             : // upper bound (e.g. via a call to SeekLT(upper))
    1134           1 : func (m *mergingIter) Last() *base.InternalKV {
    1135           1 :         m.err = nil // clear cached iteration error
    1136           1 :         m.prefix = nil
    1137           1 :         for i := range m.levels {
    1138           1 :                 l := &m.levels[i]
    1139           1 :                 l.iterKV = l.iter.Last()
    1140           1 :                 if l.iterKV == nil {
    1141           1 :                         if m.err = l.iter.Error(); m.err != nil {
    1142           1 :                                 return nil
    1143           1 :                         }
    1144             :                 }
    1145             :         }
    1146           1 :         if m.err = m.initMaxHeap(); m.err != nil {
    1147           0 :                 return nil
    1148           0 :         }
    1149           1 :         return m.findPrevEntry()
    1150             : }
    1151             : 
    1152           1 : func (m *mergingIter) Next() *base.InternalKV {
    1153           1 :         if m.err != nil {
    1154           1 :                 return nil
    1155           1 :         }
    1156             : 
    1157           1 :         if m.dir != 1 {
    1158           1 :                 if m.err = m.switchToMinHeap(); m.err != nil {
    1159           1 :                         return nil
    1160           1 :                 }
    1161           1 :                 return m.findNextEntry()
    1162             :         }
    1163             : 
    1164           1 :         if m.heap.len() == 0 {
    1165           1 :                 return nil
    1166           1 :         }
    1167             : 
    1168             :         // NB: It's okay to call nextEntry directly even during prefix iteration
    1169             :         // mode. During prefix iteration mode, we rely on the caller to not call
    1170             :         // Next if the iterator has already advanced beyond the iteration prefix.
    1171             :         // See the comment above the base.InternalIterator interface.
    1172           1 :         if m.err = m.nextEntry(m.heap.items[0], nil /* succKey */); m.err != nil {
    1173           1 :                 return nil
    1174           1 :         }
    1175             : 
    1176           1 :         iterKV := m.findNextEntry()
    1177           1 :         if invariants.Enabled && m.prefix != nil && iterKV != nil {
    1178           1 :                 if !bytes.Equal(m.prefix, m.split.Prefix(iterKV.K.UserKey)) {
    1179           0 :                         m.logger.Fatalf("mergingIter: prefix violation: returning key %q without prefix %q\n", iterKV, m.prefix)
    1180           0 :                 }
    1181             :         }
    1182           1 :         return iterKV
    1183             : }
    1184             : 
    1185           1 : func (m *mergingIter) NextPrefix(succKey []byte) *base.InternalKV {
    1186           1 :         if m.dir != 1 {
    1187           0 :                 panic("pebble: cannot switch directions with NextPrefix")
    1188             :         }
    1189           1 :         if m.err != nil || m.heap.len() == 0 {
    1190           0 :                 return nil
    1191           0 :         }
    1192           1 :         if m.levelsPositioned == nil {
    1193           1 :                 m.levelsPositioned = make([]bool, len(m.levels))
    1194           1 :         } else {
    1195           1 :                 for i := range m.levelsPositioned {
    1196           1 :                         m.levelsPositioned[i] = false
    1197           1 :                 }
    1198             :         }
    1199             : 
    1200             :         // The heap root necessarily must be positioned at a key < succKey, because
    1201             :         // NextPrefix was invoked.
    1202           1 :         root := m.heap.items[0]
    1203           1 :         if invariants.Enabled && m.heap.cmp((*root).iterKV.K.UserKey, succKey) >= 0 {
    1204           0 :                 m.logger.Fatalf("pebble: invariant violation: NextPrefix(%q) called on merging iterator already positioned at %q",
    1205           0 :                         succKey, (*root).iterKV)
    1206           0 :         }
    1207             :         // NB: root is the heap root before we call nextEntry; nextEntry may change
    1208             :         // the heap root, so we must not `root` to still be the root of the heap, or
    1209             :         // even to be in the heap if the level's iterator becomes exhausted.
    1210           1 :         if m.err = m.nextEntry(root, succKey); m.err != nil {
    1211           1 :                 return nil
    1212           1 :         }
    1213             :         // We only consider the level to be conclusively positioned at the next
    1214             :         // prefix if our call to nextEntry did not advance the level onto a range
    1215             :         // deletion's boundary. Range deletions may have bounds within the prefix
    1216             :         // that are still surfaced by NextPrefix.
    1217           1 :         m.levelsPositioned[root.index] = root.iterKV == nil || !root.iterKV.K.IsExclusiveSentinel()
    1218           1 : 
    1219           1 :         for m.heap.len() > 0 {
    1220           1 :                 root := m.heap.items[0]
    1221           1 :                 if m.levelsPositioned[root.index] {
    1222           1 :                         // A level we've previously positioned is at the top of the heap, so
    1223           1 :                         // there are no other levels positioned at keys < succKey. We've
    1224           1 :                         // advanced as far as we need to.
    1225           1 :                         break
    1226             :                 }
    1227             :                 // If the current heap root is a sentinel key, we need to skip it.
    1228             :                 // Calling NextPrefix while positioned at a sentinel key is not
    1229             :                 // supported.
    1230           1 :                 if root.iterKV.K.IsExclusiveSentinel() {
    1231           1 :                         if m.err = m.nextEntry(root, nil); m.err != nil {
    1232           0 :                                 return nil
    1233           0 :                         }
    1234           1 :                         continue
    1235             :                 }
    1236             : 
    1237             :                 // Since this level was not the original heap root when NextPrefix was
    1238             :                 // called, we don't know whether this level's current key has the
    1239             :                 // previous prefix or a new one.
    1240           1 :                 if m.heap.cmp(root.iterKV.K.UserKey, succKey) >= 0 {
    1241           1 :                         break
    1242             :                 }
    1243           1 :                 if m.err = m.nextEntry(root, succKey); m.err != nil {
    1244           0 :                         return nil
    1245           0 :                 }
    1246             :                 // We only consider the level to be conclusively positioned at the next
    1247             :                 // prefix if our call to nextEntry did not land onto a range deletion's
    1248             :                 // boundary. Range deletions may have bounds within the prefix that are
    1249             :                 // still surfaced by NextPrefix.
    1250           1 :                 m.levelsPositioned[root.index] = root.iterKV == nil || !root.iterKV.K.IsExclusiveSentinel()
    1251             :         }
    1252           1 :         return m.findNextEntry()
    1253             : }
    1254             : 
    1255           1 : func (m *mergingIter) Prev() *base.InternalKV {
    1256           1 :         if m.err != nil {
    1257           0 :                 return nil
    1258           0 :         }
    1259             : 
    1260           1 :         if m.dir != -1 {
    1261           1 :                 if m.prefix != nil {
    1262           1 :                         m.err = errors.New("pebble: unsupported reverse prefix iteration")
    1263           1 :                         return nil
    1264           1 :                 }
    1265           1 :                 if m.err = m.switchToMaxHeap(); m.err != nil {
    1266           1 :                         return nil
    1267           1 :                 }
    1268           1 :                 return m.findPrevEntry()
    1269             :         }
    1270             : 
    1271           1 :         if m.heap.len() == 0 {
    1272           1 :                 return nil
    1273           1 :         }
    1274           1 :         if m.err = m.prevEntry(m.heap.items[0]); m.err != nil {
    1275           1 :                 return nil
    1276           1 :         }
    1277           1 :         return m.findPrevEntry()
    1278             : }
    1279             : 
    1280           1 : func (m *mergingIter) Error() error {
    1281           1 :         if m.heap.len() == 0 || m.err != nil {
    1282           1 :                 return m.err
    1283           1 :         }
    1284           1 :         return m.levels[m.heap.items[0].index].iter.Error()
    1285             : }
    1286             : 
    1287           1 : func (m *mergingIter) Close() error {
    1288           1 :         for i := range m.levels {
    1289           1 :                 iter := m.levels[i].iter
    1290           1 :                 if err := iter.Close(); err != nil && m.err == nil {
    1291           0 :                         m.err = err
    1292           0 :                 }
    1293           1 :                 if rangeDelIter := m.levels[i].rangeDelIter; rangeDelIter != nil {
    1294           1 :                         if err := rangeDelIter.Close(); err != nil && m.err == nil {
    1295           0 :                                 m.err = err
    1296           0 :                         }
    1297             :                 }
    1298             :         }
    1299           1 :         m.levels = nil
    1300           1 :         m.heap.items = m.heap.items[:0]
    1301           1 :         return m.err
    1302             : }
    1303             : 
    1304           1 : func (m *mergingIter) SetBounds(lower, upper []byte) {
    1305           1 :         m.prefix = nil
    1306           1 :         m.lower = lower
    1307           1 :         m.upper = upper
    1308           1 :         for i := range m.levels {
    1309           1 :                 m.levels[i].iter.SetBounds(lower, upper)
    1310           1 :         }
    1311           1 :         m.heap.clear()
    1312             : }
    1313             : 
    1314           1 : func (m *mergingIter) SetContext(ctx context.Context) {
    1315           1 :         for i := range m.levels {
    1316           1 :                 m.levels[i].iter.SetContext(ctx)
    1317           1 :         }
    1318             : }
    1319             : 
    1320           0 : func (m *mergingIter) DebugString() string {
    1321           0 :         var buf bytes.Buffer
    1322           0 :         sep := ""
    1323           0 :         for m.heap.len() > 0 {
    1324           0 :                 item := m.heap.pop()
    1325           0 :                 fmt.Fprintf(&buf, "%s%s", sep, item.iterKV.K)
    1326           0 :                 sep = " "
    1327           0 :         }
    1328           0 :         var err error
    1329           0 :         if m.dir == 1 {
    1330           0 :                 err = m.initMinHeap()
    1331           0 :         } else {
    1332           0 :                 err = m.initMaxHeap()
    1333           0 :         }
    1334           0 :         if err != nil {
    1335           0 :                 fmt.Fprintf(&buf, "err=<%s>", err)
    1336           0 :         }
    1337           0 :         return buf.String()
    1338             : }
    1339             : 
    1340           1 : func (m *mergingIter) ForEachLevelIter(fn func(li *levelIter) bool) {
    1341           1 :         for _, ml := range m.levels {
    1342           1 :                 if ml.levelIter != nil {
    1343           1 :                         if done := fn(ml.levelIter); done {
    1344           1 :                                 break
    1345             :                         }
    1346             :                 }
    1347             :         }
    1348             : }
    1349             : 
    1350           1 : func (m *mergingIter) addItemStats(l *mergingIterLevel) {
    1351           1 :         m.stats.PointCount++
    1352           1 :         m.stats.KeyBytes += uint64(len(l.iterKV.K.UserKey))
    1353           1 :         m.stats.ValueBytes += uint64(len(l.iterKV.V.ValueOrHandle))
    1354           1 : }
    1355             : 
    1356             : var _ internalIterator = &mergingIter{}

Generated by: LCOV version 1.14