LCOV - code coverage report
Current view: top level - pebble - scan_internal.go (source / functions) Hit Total Coverage
Test: 2024-04-23 08:15Z 01000f24 - tests only.lcov Lines: 611 726 84.2 %
Date: 2024-04-23 08:16:17 Functions: 0 0 -

          Line data    Source code
       1             : // Copyright 2023 The LevelDB-Go and Pebble Authors. All rights reserved. Use
       2             : // of this source code is governed by a BSD-style license that can be found in
       3             : // the LICENSE file.
       4             : 
       5             : package pebble
       6             : 
       7             : import (
       8             :         "context"
       9             :         "fmt"
      10             :         "slices"
      11             : 
      12             :         "github.com/cockroachdb/errors"
      13             :         "github.com/cockroachdb/pebble/internal/base"
      14             :         "github.com/cockroachdb/pebble/internal/invariants"
      15             :         "github.com/cockroachdb/pebble/internal/keyspan"
      16             :         "github.com/cockroachdb/pebble/internal/keyspan/keyspanimpl"
      17             :         "github.com/cockroachdb/pebble/internal/manifest"
      18             :         "github.com/cockroachdb/pebble/objstorage"
      19             :         "github.com/cockroachdb/pebble/objstorage/remote"
      20             :         "github.com/cockroachdb/pebble/sstable"
      21             : )
      22             : 
      23             : const (
      24             :         // In skip-shared iteration mode, keys in levels greater than
      25             :         // sharedLevelsStart (i.e. lower in the LSM) are skipped. Keys
      26             :         // in sharedLevelsStart are returned iff they are not in a
      27             :         // shared file.
      28             :         sharedLevelsStart = remote.SharedLevelsStart
      29             : 
      30             :         // In skip-external iteration mode, keys in levels greater
      31             :         // than externalSkipStart are skipped. Keys in
      32             :         // externalSkipStart are returned iff they are not in an
      33             :         // external file.
      34             :         externalSkipStart = 6
      35             : )
      36             : 
      37             : // ErrInvalidSkipSharedIteration is returned by ScanInternal if it was called
      38             : // with a shared file visitor function, and a file in a shareable level (i.e.
      39             : // level >= sharedLevelsStart) was found to not be in shared storage according
      40             : // to objstorage.Provider, or not shareable for another reason such as for
      41             : // containing keys newer than the snapshot sequence number.
      42             : var ErrInvalidSkipSharedIteration = errors.New("pebble: cannot use skip-shared iteration due to non-shareable files in lower levels")
      43             : 
      44             : // SharedSSTMeta represents an sstable on shared storage that can be ingested
      45             : // by another pebble instance. This struct must contain all fields that are
      46             : // required for a Pebble instance to ingest a foreign sstable on shared storage,
      47             : // including constructing any relevant objstorage.Provider / remoteobjcat.Catalog
      48             : // data structures, as well as creating virtual FileMetadatas.
      49             : //
      50             : // Note that the Pebble instance creating and returning a SharedSSTMeta might
      51             : // not be the one that created the underlying sstable on shared storage to begin
      52             : // with; it's possible for a Pebble instance to reshare an sstable that was
      53             : // shared to it.
      54             : type SharedSSTMeta struct {
      55             :         // Backing is the shared object underlying this SST. Can be attached to an
      56             :         // objstorage.Provider.
      57             :         Backing objstorage.RemoteObjectBackingHandle
      58             : 
      59             :         // Smallest and Largest internal keys for the overall bounds. The kind and
      60             :         // SeqNum of these will reflect what is physically present on the source Pebble
      61             :         // instance's view of the sstable; it's up to the ingesting instance to set the
      62             :         // sequence number in the trailer to match the read-time sequence numbers
      63             :         // reserved for the level this SST is being ingested into. The Kind is expected
      64             :         // to remain unchanged by the ingesting instance.
      65             :         //
      66             :         // Note that these bounds could be narrower than the bounds of the underlying
      67             :         // sstable; ScanInternal is expected to truncate sstable bounds to the user key
      68             :         // bounds passed into that method.
      69             :         Smallest, Largest InternalKey
      70             : 
      71             :         // SmallestRangeKey and LargestRangeKey are internal keys that denote the
      72             :         // range key bounds of this sstable. Must lie within [Smallest, Largest].
      73             :         SmallestRangeKey, LargestRangeKey InternalKey
      74             : 
      75             :         // SmallestPointKey and LargestPointKey are internal keys that denote the
      76             :         // point key bounds of this sstable. Must lie within [Smallest, Largest].
      77             :         SmallestPointKey, LargestPointKey InternalKey
      78             : 
      79             :         // Level denotes the level at which this file was present at read time.
      80             :         // For files visited by ScanInternal, this value will only be 5 or 6.
      81             :         Level uint8
      82             : 
      83             :         // Size contains an estimate of the size of this sstable.
      84             :         Size uint64
      85             : 
      86             :         // fileNum at time of creation in the creator instance. Only used for
      87             :         // debugging/tests.
      88             :         fileNum base.FileNum
      89             : }
      90             : 
      91           1 : func (s *SharedSSTMeta) cloneFromFileMeta(f *fileMetadata) {
      92           1 :         *s = SharedSSTMeta{
      93           1 :                 Smallest:         f.Smallest.Clone(),
      94           1 :                 Largest:          f.Largest.Clone(),
      95           1 :                 SmallestRangeKey: f.SmallestRangeKey.Clone(),
      96           1 :                 LargestRangeKey:  f.LargestRangeKey.Clone(),
      97           1 :                 SmallestPointKey: f.SmallestPointKey.Clone(),
      98           1 :                 LargestPointKey:  f.LargestPointKey.Clone(),
      99           1 :                 Size:             f.Size,
     100           1 :                 fileNum:          f.FileNum,
     101           1 :         }
     102           1 : }
     103             : 
     104             : type sharedByLevel []SharedSSTMeta
     105             : 
     106           1 : func (s sharedByLevel) Len() int           { return len(s) }
     107           0 : func (s sharedByLevel) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
     108           1 : func (s sharedByLevel) Less(i, j int) bool { return s[i].Level < s[j].Level }
     109             : 
     110             : type pcIterPos int
     111             : 
     112             : const (
     113             :         pcIterPosCur pcIterPos = iota
     114             :         pcIterPosNext
     115             : )
     116             : 
     117             : // pointCollapsingIterator is an internalIterator that collapses point keys and
     118             : // returns at most one point internal key for each user key. Merges and
     119             : // SingleDels are not supported and result in a panic if encountered. Point keys
     120             : // deleted by rangedels are considered shadowed and not exposed.
     121             : //
     122             : // Only used in ScanInternal to return at most one internal key per user key.
     123             : type pointCollapsingIterator struct {
     124             :         iter     keyspan.InterleavingIter
     125             :         pos      pcIterPos
     126             :         comparer *base.Comparer
     127             :         merge    base.Merge
     128             :         err      error
     129             :         seqNum   uint64
     130             :         // The current position of `iter`. Always owned by the underlying iter.
     131             :         iterKV *base.InternalKV
     132             :         // The last saved key. findNextEntry and similar methods are expected to save
     133             :         // the current value of iterKey to savedKey if they're iterating away from the
     134             :         // current key but still need to retain it. See comments in findNextEntry on
     135             :         // how this field is used.
     136             :         //
     137             :         // At the end of a positioning call:
     138             :         //  - if pos == pcIterPosNext, iterKey is pointing to the next user key owned
     139             :         //    by `iter` while savedKey is holding a copy to our current key.
     140             :         //  - If pos == pcIterPosCur, iterKey is pointing to an `iter`-owned current
     141             :         //    key, and savedKey is either undefined or pointing to a version of the
     142             :         //    current key owned by this iterator (i.e. backed by savedKeyBuf).
     143             :         savedKey    InternalKey
     144             :         savedKeyBuf []byte
     145             :         // If fixedSeqNum is non-zero, all emitted points are verified to have this
     146             :         // fixed sequence number.
     147             :         fixedSeqNum uint64
     148             : }
     149             : 
     150           1 : func (p *pointCollapsingIterator) Span() *keyspan.Span {
     151           1 :         return p.iter.Span()
     152           1 : }
     153             : 
     154             : // SeekPrefixGE implements the InternalIterator interface.
     155             : func (p *pointCollapsingIterator) SeekPrefixGE(
     156             :         prefix, key []byte, flags base.SeekGEFlags,
     157           0 : ) *base.InternalKV {
     158           0 :         p.resetKey()
     159           0 :         p.iterKV = p.iter.SeekPrefixGE(prefix, key, flags)
     160           0 :         p.pos = pcIterPosCur
     161           0 :         if p.iterKV == nil {
     162           0 :                 return nil
     163           0 :         }
     164           0 :         return p.findNextEntry()
     165             : }
     166             : 
     167             : // SeekGE implements the InternalIterator interface.
     168           1 : func (p *pointCollapsingIterator) SeekGE(key []byte, flags base.SeekGEFlags) *base.InternalKV {
     169           1 :         p.resetKey()
     170           1 :         p.iterKV = p.iter.SeekGE(key, flags)
     171           1 :         p.pos = pcIterPosCur
     172           1 :         if p.iterKV == nil {
     173           1 :                 return nil
     174           1 :         }
     175           1 :         return p.findNextEntry()
     176             : }
     177             : 
     178             : // SeekLT implements the InternalIterator interface.
     179           0 : func (p *pointCollapsingIterator) SeekLT(key []byte, flags base.SeekLTFlags) *base.InternalKV {
     180           0 :         panic("unimplemented")
     181             : }
     182             : 
     183           1 : func (p *pointCollapsingIterator) resetKey() {
     184           1 :         p.savedKey.UserKey = p.savedKeyBuf[:0]
     185           1 :         p.savedKey.Trailer = 0
     186           1 :         p.iterKV = nil
     187           1 :         p.pos = pcIterPosCur
     188           1 : }
     189             : 
     190           1 : func (p *pointCollapsingIterator) verifySeqNum(kv *base.InternalKV) *base.InternalKV {
     191           1 :         if !invariants.Enabled {
     192           0 :                 return kv
     193           0 :         }
     194           1 :         if p.fixedSeqNum == 0 || kv == nil || kv.Kind() == InternalKeyKindRangeDelete {
     195           1 :                 return kv
     196           1 :         }
     197           0 :         if kv.SeqNum() != p.fixedSeqNum {
     198           0 :                 panic(fmt.Sprintf("expected foreign point key to have seqnum %d, got %d", p.fixedSeqNum, kv.SeqNum()))
     199             :         }
     200           0 :         return kv
     201             : }
     202             : 
     203             : // findNextEntry is called to return the next key. p.iter must be positioned at the
     204             : // start of the first user key we are interested in.
     205           1 : func (p *pointCollapsingIterator) findNextEntry() *base.InternalKV {
     206           1 :         p.saveKey()
     207           1 :         // Saves a comparison in the fast path
     208           1 :         firstIteration := true
     209           1 :         for p.iterKV != nil {
     210           1 :                 // NB: p.savedKey is either the current key (iff p.iterKV == firstKey),
     211           1 :                 // or the previous key.
     212           1 :                 if !firstIteration && !p.comparer.Equal(p.iterKV.K.UserKey, p.savedKey.UserKey) {
     213           1 :                         p.saveKey()
     214           1 :                         continue
     215             :                 }
     216           1 :                 firstIteration = false
     217           1 :                 if s := p.iter.Span(); s != nil && s.CoversAt(p.seqNum, p.iterKV.SeqNum()) {
     218           1 :                         // All future keys for this user key must be deleted.
     219           1 :                         if p.savedKey.Kind() == InternalKeyKindSingleDelete {
     220           0 :                                 panic("cannot process singledel key in point collapsing iterator")
     221             :                         }
     222             :                         // Fast forward to the next user key.
     223           1 :                         p.saveKey()
     224           1 :                         p.iterKV = p.iter.Next()
     225           1 :                         for p.iterKV != nil && p.savedKey.SeqNum() >= p.iterKV.SeqNum() && p.comparer.Equal(p.iterKV.K.UserKey, p.savedKey.UserKey) {
     226           1 :                                 p.iterKV = p.iter.Next()
     227           1 :                         }
     228           1 :                         continue
     229             :                 }
     230           1 :                 switch p.savedKey.Kind() {
     231           1 :                 case InternalKeyKindSet, InternalKeyKindDelete, InternalKeyKindSetWithDelete, InternalKeyKindDeleteSized:
     232           1 :                         // Note that we return SETs directly, even if they would otherwise get
     233           1 :                         // compacted into a Del to turn into a SetWithDelete. This is a fast
     234           1 :                         // path optimization that can break SINGLEDEL determinism. To lead to
     235           1 :                         // consistent SINGLEDEL behaviour, this iterator should *not* be used for
     236           1 :                         // a keyspace where SINGLEDELs could be in use. If this iterator observes
     237           1 :                         // a SINGLEDEL as the first internal key for a user key, it will panic.
     238           1 :                         //
     239           1 :                         // As p.value is a lazy value owned by the child iterator, we can thread
     240           1 :                         // it through without loading it into p.valueBuf.
     241           1 :                         //
     242           1 :                         // TODO(bilal): We can even avoid saving the key in this fast path if
     243           1 :                         // we are in a block where setHasSamePrefix = false in a v3 sstable,
     244           1 :                         // guaranteeing that there's only one internal key for each user key.
     245           1 :                         // Thread this logic through the sstable iterators and/or consider
     246           1 :                         // collapsing (ha) this logic into the sstable iterators that are aware
     247           1 :                         // of blocks and can determine user key changes without doing key saves
     248           1 :                         // or comparisons.
     249           1 :                         p.pos = pcIterPosCur
     250           1 :                         return p.verifySeqNum(p.iterKV)
     251           0 :                 case InternalKeyKindSingleDelete:
     252           0 :                         // Panic, as this iterator is not expected to observe single deletes.
     253           0 :                         panic("cannot process singledel key in point collapsing iterator")
     254           0 :                 case InternalKeyKindMerge:
     255           0 :                         // Panic, as this iterator is not expected to observe merges.
     256           0 :                         panic("cannot process merge key in point collapsing iterator")
     257           1 :                 case InternalKeyKindRangeDelete:
     258           1 :                         // These are interleaved by the interleaving iterator ahead of all points.
     259           1 :                         // We should pass them as-is, but also account for any points ahead of
     260           1 :                         // them.
     261           1 :                         p.pos = pcIterPosCur
     262           1 :                         return p.verifySeqNum(p.iterKV)
     263           0 :                 default:
     264           0 :                         panic(fmt.Sprintf("unexpected kind: %d", p.iterKV.Kind()))
     265             :                 }
     266             :         }
     267           0 :         p.resetKey()
     268           0 :         return nil
     269             : }
     270             : 
     271             : // First implements the InternalIterator interface.
     272           1 : func (p *pointCollapsingIterator) First() *base.InternalKV {
     273           1 :         p.resetKey()
     274           1 :         p.iterKV = p.iter.First()
     275           1 :         p.pos = pcIterPosCur
     276           1 :         if p.iterKV == nil {
     277           0 :                 return nil
     278           0 :         }
     279           1 :         return p.findNextEntry()
     280             : }
     281             : 
     282             : // Last implements the InternalIterator interface.
     283           0 : func (p *pointCollapsingIterator) Last() *base.InternalKV {
     284           0 :         panic("unimplemented")
     285             : }
     286             : 
     287           1 : func (p *pointCollapsingIterator) saveKey() {
     288           1 :         if p.iterKV == nil {
     289           1 :                 p.savedKey = InternalKey{UserKey: p.savedKeyBuf[:0]}
     290           1 :                 return
     291           1 :         }
     292           1 :         p.savedKeyBuf = append(p.savedKeyBuf[:0], p.iterKV.K.UserKey...)
     293           1 :         p.savedKey = InternalKey{UserKey: p.savedKeyBuf, Trailer: p.iterKV.K.Trailer}
     294             : }
     295             : 
     296             : // Next implements the InternalIterator interface.
     297           1 : func (p *pointCollapsingIterator) Next() *base.InternalKV {
     298           1 :         switch p.pos {
     299           1 :         case pcIterPosCur:
     300           1 :                 p.saveKey()
     301           1 :                 if p.iterKV != nil && p.iterKV.Kind() == InternalKeyKindRangeDelete {
     302           1 :                         // Step over the interleaved range delete and process the very next
     303           1 :                         // internal key, even if it's at the same user key. This is because a
     304           1 :                         // point for that user key has not been returned yet.
     305           1 :                         p.iterKV = p.iter.Next()
     306           1 :                         break
     307             :                 }
     308             :                 // Fast forward to the next user key.
     309           1 :                 kv := p.iter.Next()
     310           1 :                 // p.iterKV.SeqNum() >= key.SeqNum() is an optimization that allows us to
     311           1 :                 // use p.iterKV.SeqNum() < key.SeqNum() as a sign that the user key has
     312           1 :                 // changed, without needing to do the full key comparison.
     313           1 :                 for kv != nil && p.savedKey.SeqNum() >= kv.SeqNum() &&
     314           1 :                         p.comparer.Equal(p.savedKey.UserKey, kv.K.UserKey) {
     315           1 :                         kv = p.iter.Next()
     316           1 :                 }
     317           1 :                 if kv == nil {
     318           1 :                         // There are no keys to return.
     319           1 :                         p.resetKey()
     320           1 :                         return nil
     321           1 :                 }
     322           1 :                 p.iterKV = kv
     323           0 :         case pcIterPosNext:
     324           0 :                 p.pos = pcIterPosCur
     325             :         }
     326           1 :         if p.iterKV == nil {
     327           1 :                 p.resetKey()
     328           1 :                 return nil
     329           1 :         }
     330           1 :         return p.findNextEntry()
     331             : }
     332             : 
     333             : // NextPrefix implements the InternalIterator interface.
     334           0 : func (p *pointCollapsingIterator) NextPrefix(succKey []byte) *base.InternalKV {
     335           0 :         panic("unimplemented")
     336             : }
     337             : 
     338             : // Prev implements the InternalIterator interface.
     339           0 : func (p *pointCollapsingIterator) Prev() *base.InternalKV {
     340           0 :         panic("unimplemented")
     341             : }
     342             : 
     343             : // Error implements the InternalIterator interface.
     344           1 : func (p *pointCollapsingIterator) Error() error {
     345           1 :         if p.err != nil {
     346           0 :                 return p.err
     347           0 :         }
     348           1 :         return p.iter.Error()
     349             : }
     350             : 
     351             : // Close implements the InternalIterator interface.
     352           1 : func (p *pointCollapsingIterator) Close() error {
     353           1 :         return p.iter.Close()
     354           1 : }
     355             : 
     356             : // SetBounds implements the InternalIterator interface.
     357           0 : func (p *pointCollapsingIterator) SetBounds(lower, upper []byte) {
     358           0 :         p.resetKey()
     359           0 :         p.iter.SetBounds(lower, upper)
     360           0 : }
     361             : 
     362           0 : func (p *pointCollapsingIterator) SetContext(ctx context.Context) {
     363           0 :         p.iter.SetContext(ctx)
     364           0 : }
     365             : 
     366             : // String implements the InternalIterator interface.
     367           0 : func (p *pointCollapsingIterator) String() string {
     368           0 :         return p.iter.String()
     369           0 : }
     370             : 
     371             : var _ internalIterator = &pointCollapsingIterator{}
     372             : 
     373             : // IteratorLevelKind is used to denote whether the current ScanInternal iterator
     374             : // is unknown, belongs to a flushable, or belongs to an LSM level type.
     375             : type IteratorLevelKind int8
     376             : 
     377             : const (
     378             :         // IteratorLevelUnknown indicates an unknown LSM level.
     379             :         IteratorLevelUnknown IteratorLevelKind = iota
     380             :         // IteratorLevelLSM indicates an LSM level.
     381             :         IteratorLevelLSM
     382             :         // IteratorLevelFlushable indicates a flushable (i.e. memtable).
     383             :         IteratorLevelFlushable
     384             : )
     385             : 
     386             : // IteratorLevel is used with scanInternalIterator to surface additional iterator-specific info where possible.
     387             : // Note: this is struct is only provided for point keys.
     388             : type IteratorLevel struct {
     389             :         Kind IteratorLevelKind
     390             :         // FlushableIndex indicates the position within the flushable queue of this level.
     391             :         // Only valid if kind == IteratorLevelFlushable.
     392             :         FlushableIndex int
     393             :         // The level within the LSM. Only valid if Kind == IteratorLevelLSM.
     394             :         Level int
     395             :         // Sublevel is only valid if Kind == IteratorLevelLSM and Level == 0.
     396             :         Sublevel int
     397             : }
     398             : 
     399             : // scanInternalIterator is an iterator that returns all internal keys, including
     400             : // tombstones. For instance, an InternalKeyKindDelete would be returned as an
     401             : // InternalKeyKindDelete instead of the iterator skipping over to the next key.
     402             : // Internal keys within a user key are collapsed, eg. if there are two SETs, the
     403             : // one with the higher sequence is returned. Useful if an external user of Pebble
     404             : // needs to observe and rebuild Pebble's history of internal keys, such as in
     405             : // node-to-node replication. For use with {db,snapshot}.ScanInternal().
     406             : //
     407             : // scanInternalIterator is expected to ignore point keys deleted by range
     408             : // deletions, and range keys shadowed by a range key unset or delete, however it
     409             : // *must* return the range delete as well as the range key unset/delete that did
     410             : // the shadowing.
     411             : type scanInternalIterator struct {
     412             :         ctx             context.Context
     413             :         db              *DB
     414             :         opts            scanInternalOptions
     415             :         comparer        *base.Comparer
     416             :         merge           Merge
     417             :         iter            internalIterator
     418             :         readState       *readState
     419             :         version         *version
     420             :         rangeKey        *iteratorRangeKeyState
     421             :         pointKeyIter    internalIterator
     422             :         iterKV          *base.InternalKV
     423             :         alloc           *iterAlloc
     424             :         newIters        tableNewIters
     425             :         newIterRangeKey keyspanimpl.TableNewSpanIter
     426             :         seqNum          uint64
     427             :         iterLevels      []IteratorLevel
     428             :         mergingIter     *mergingIter
     429             : 
     430             :         // boundsBuf holds two buffers used to store the lower and upper bounds.
     431             :         // Whenever the InternalIterator's bounds change, the new bounds are copied
     432             :         // into boundsBuf[boundsBufIdx]. The two bounds share a slice to reduce
     433             :         // allocations. opts.LowerBound and opts.UpperBound point into this slice.
     434             :         boundsBuf    [2][]byte
     435             :         boundsBufIdx int
     436             : }
     437             : 
     438             : // truncateExternalFile truncates an External file's [SmallestUserKey,
     439             : // LargestUserKey] fields to [lower, upper). A ExternalFile is
     440             : // produced that is suitable for external consumption by other Pebble
     441             : // instances.
     442             : //
     443             : // truncateSharedFile reads the file to try to create the smallest
     444             : // possible bounds.  Here, we blindly truncate them. This may mean we
     445             : // include this SST in iterations it isn't really needed in. Since we
     446             : // don't expect External files to be long-lived in the pebble
     447             : // instance, We think this is OK.
     448             : //
     449             : // TODO(ssd) 2024-01-26: Potentially de-duplicate with
     450             : // truncateSharedFile.
     451             : func (d *DB) truncateExternalFile(
     452             :         ctx context.Context,
     453             :         lower, upper []byte,
     454             :         level int,
     455             :         file *fileMetadata,
     456             :         objMeta objstorage.ObjectMetadata,
     457           1 : ) (*ExternalFile, error) {
     458           1 :         cmp := d.cmp
     459           1 :         sst := &ExternalFile{
     460           1 :                 Level:           uint8(level),
     461           1 :                 ObjName:         objMeta.Remote.CustomObjectName,
     462           1 :                 Locator:         objMeta.Remote.Locator,
     463           1 :                 HasPointKey:     file.HasPointKeys,
     464           1 :                 HasRangeKey:     file.HasRangeKeys,
     465           1 :                 Size:            file.Size,
     466           1 :                 SyntheticSuffix: slices.Clone(file.SyntheticSuffix),
     467           1 :         }
     468           1 :         if file.SyntheticPrefix.IsSet() {
     469           0 :                 sst.SyntheticPrefix = slices.Clone(sst.SyntheticPrefix)
     470           0 :         }
     471             : 
     472           1 :         needsLowerTruncate := cmp(lower, file.Smallest.UserKey) > 0
     473           1 :         if needsLowerTruncate {
     474           1 :                 sst.StartKey = slices.Clone(lower)
     475           1 :         } else {
     476           1 :                 sst.StartKey = slices.Clone(file.Smallest.UserKey)
     477           1 :         }
     478             : 
     479           1 :         cmpUpper := cmp(upper, file.Largest.UserKey)
     480           1 :         needsUpperTruncate := cmpUpper < 0
     481           1 :         if needsUpperTruncate {
     482           0 :                 sst.EndKey = slices.Clone(upper)
     483           0 :                 sst.EndKeyIsInclusive = false
     484           1 :         } else {
     485           1 :                 sst.EndKey = slices.Clone(file.Largest.UserKey)
     486           1 :                 sst.EndKeyIsInclusive = !file.Largest.IsExclusiveSentinel()
     487           1 :         }
     488             : 
     489           1 :         if cmp(sst.StartKey, sst.EndKey) > 0 {
     490           0 :                 return nil, base.AssertionFailedf("pebble: invalid external file bounds after truncation [%q, %q)", sst.StartKey, sst.EndKey)
     491           0 :         }
     492             : 
     493           1 :         if cmp(sst.StartKey, sst.EndKey) == 0 && !sst.EndKeyIsInclusive {
     494           0 :                 return nil, base.AssertionFailedf("pebble: invalid external file bounds after truncation [%q, %q)", sst.StartKey, sst.EndKey)
     495           0 :         }
     496             : 
     497           1 :         return sst, nil
     498             : }
     499             : 
     500             : // truncateSharedFile truncates a shared file's [Smallest, Largest] fields to
     501             : // [lower, upper), potentially opening iterators on the file to find keys within
     502             : // the requested bounds. A SharedSSTMeta is produced that is suitable for
     503             : // external consumption by other Pebble instances. If shouldSkip is true, this
     504             : // file does not contain any keys in [lower, upper) and can be skipped.
     505             : //
     506             : // TODO(bilal): If opening iterators and doing reads in this method is too
     507             : // inefficient, consider producing non-tight file bounds instead.
     508             : func (d *DB) truncateSharedFile(
     509             :         ctx context.Context,
     510             :         lower, upper []byte,
     511             :         level int,
     512             :         file *fileMetadata,
     513             :         objMeta objstorage.ObjectMetadata,
     514           1 : ) (sst *SharedSSTMeta, shouldSkip bool, err error) {
     515           1 :         cmp := d.cmp
     516           1 :         sst = &SharedSSTMeta{}
     517           1 :         sst.cloneFromFileMeta(file)
     518           1 :         sst.Level = uint8(level)
     519           1 :         sst.Backing, err = d.objProvider.RemoteObjectBacking(&objMeta)
     520           1 :         if err != nil {
     521           0 :                 return nil, false, err
     522           0 :         }
     523           1 :         needsLowerTruncate := cmp(lower, file.Smallest.UserKey) > 0
     524           1 :         needsUpperTruncate := cmp(upper, file.Largest.UserKey) < 0 || (cmp(upper, file.Largest.UserKey) == 0 && !file.Largest.IsExclusiveSentinel())
     525           1 :         // Fast path: file is entirely within [lower, upper).
     526           1 :         if !needsLowerTruncate && !needsUpperTruncate {
     527           1 :                 return sst, false, nil
     528           1 :         }
     529             : 
     530             :         // We will need to truncate file bounds in at least one direction. Open all
     531             :         // relevant iterators.
     532           1 :         iters, err := d.newIters(ctx, file, &IterOptions{
     533           1 :                 LowerBound: lower,
     534           1 :                 UpperBound: upper,
     535           1 :                 level:      manifest.Level(level),
     536           1 :         }, internalIterOpts{}, iterPointKeys|iterRangeDeletions|iterRangeKeys)
     537           1 :         if err != nil {
     538           0 :                 return nil, false, err
     539           0 :         }
     540           1 :         defer iters.CloseAll()
     541           1 :         iter := iters.point
     542           1 :         rangeDelIter := iters.rangeDeletion
     543           1 :         rangeKeyIter := iters.rangeKey
     544           1 :         if rangeDelIter != nil {
     545           1 :                 rangeDelIter = keyspan.Truncate(cmp, rangeDelIter, base.UserKeyBoundsEndExclusive(lower, upper))
     546           1 :         }
     547           1 :         if rangeKeyIter != nil {
     548           1 :                 rangeKeyIter = keyspan.Truncate(cmp, rangeKeyIter, base.UserKeyBoundsEndExclusive(lower, upper))
     549           1 :         }
     550             :         // Check if we need to truncate on the left side. This means finding a new
     551             :         // LargestPointKey and LargestRangeKey that is >= lower.
     552           1 :         if needsLowerTruncate {
     553           1 :                 sst.SmallestPointKey.UserKey = sst.SmallestPointKey.UserKey[:0]
     554           1 :                 sst.SmallestPointKey.Trailer = 0
     555           1 :                 kv := iter.SeekGE(lower, base.SeekGEFlagsNone)
     556           1 :                 foundPointKey := kv != nil
     557           1 :                 if kv != nil {
     558           1 :                         sst.SmallestPointKey.CopyFrom(kv.K)
     559           1 :                 }
     560           1 :                 if rangeDelIter != nil {
     561           1 :                         if span, err := rangeDelIter.SeekGE(lower); err != nil {
     562           0 :                                 return nil, false, err
     563           1 :                         } else if span != nil && (len(sst.SmallestPointKey.UserKey) == 0 || base.InternalCompare(cmp, span.SmallestKey(), sst.SmallestPointKey) < 0) {
     564           1 :                                 sst.SmallestPointKey.CopyFrom(span.SmallestKey())
     565           1 :                                 foundPointKey = true
     566           1 :                         }
     567             :                 }
     568           1 :                 if !foundPointKey {
     569           1 :                         // There are no point keys in the span we're interested in.
     570           1 :                         sst.SmallestPointKey = InternalKey{}
     571           1 :                         sst.LargestPointKey = InternalKey{}
     572           1 :                 }
     573           1 :                 sst.SmallestRangeKey.UserKey = sst.SmallestRangeKey.UserKey[:0]
     574           1 :                 sst.SmallestRangeKey.Trailer = 0
     575           1 :                 if rangeKeyIter != nil {
     576           1 :                         span, err := rangeKeyIter.SeekGE(lower)
     577           1 :                         switch {
     578           0 :                         case err != nil:
     579           0 :                                 return nil, false, err
     580           1 :                         case span != nil:
     581           1 :                                 sst.SmallestRangeKey.CopyFrom(span.SmallestKey())
     582           1 :                         default:
     583           1 :                                 // There are no range keys in the span we're interested in.
     584           1 :                                 sst.SmallestRangeKey = InternalKey{}
     585           1 :                                 sst.LargestRangeKey = InternalKey{}
     586             :                         }
     587             :                 }
     588             :         }
     589             :         // Check if we need to truncate on the right side. This means finding a new
     590             :         // LargestPointKey and LargestRangeKey that is < upper.
     591           1 :         if needsUpperTruncate {
     592           1 :                 sst.LargestPointKey.UserKey = sst.LargestPointKey.UserKey[:0]
     593           1 :                 sst.LargestPointKey.Trailer = 0
     594           1 :                 kv := iter.SeekLT(upper, base.SeekLTFlagsNone)
     595           1 :                 foundPointKey := kv != nil
     596           1 :                 if kv != nil {
     597           1 :                         sst.LargestPointKey.CopyFrom(kv.K)
     598           1 :                 }
     599           1 :                 if rangeDelIter != nil {
     600           1 :                         if span, err := rangeDelIter.SeekLT(upper); err != nil {
     601           0 :                                 return nil, false, err
     602           1 :                         } else if span != nil && (len(sst.LargestPointKey.UserKey) == 0 || base.InternalCompare(cmp, span.LargestKey(), sst.LargestPointKey) > 0) {
     603           1 :                                 sst.LargestPointKey.CopyFrom(span.LargestKey())
     604           1 :                                 foundPointKey = true
     605           1 :                         }
     606             :                 }
     607           1 :                 if !foundPointKey {
     608           1 :                         // There are no point keys in the span we're interested in.
     609           1 :                         sst.SmallestPointKey = InternalKey{}
     610           1 :                         sst.LargestPointKey = InternalKey{}
     611           1 :                 }
     612           1 :                 sst.LargestRangeKey.UserKey = sst.LargestRangeKey.UserKey[:0]
     613           1 :                 sst.LargestRangeKey.Trailer = 0
     614           1 :                 if rangeKeyIter != nil {
     615           1 :                         span, err := rangeKeyIter.SeekLT(upper)
     616           1 :                         switch {
     617           0 :                         case err != nil:
     618           0 :                                 return nil, false, err
     619           1 :                         case span != nil:
     620           1 :                                 sst.LargestRangeKey.CopyFrom(span.LargestKey())
     621           1 :                         default:
     622           1 :                                 // There are no range keys in the span we're interested in.
     623           1 :                                 sst.SmallestRangeKey = InternalKey{}
     624           1 :                                 sst.LargestRangeKey = InternalKey{}
     625             :                         }
     626             :                 }
     627             :         }
     628             :         // Set overall bounds based on {Smallest,Largest}{Point,Range}Key.
     629           1 :         switch {
     630           1 :         case len(sst.SmallestRangeKey.UserKey) == 0:
     631           1 :                 sst.Smallest = sst.SmallestPointKey
     632           1 :         case len(sst.SmallestPointKey.UserKey) == 0:
     633           1 :                 sst.Smallest = sst.SmallestRangeKey
     634           1 :         default:
     635           1 :                 sst.Smallest = sst.SmallestPointKey
     636           1 :                 if base.InternalCompare(cmp, sst.SmallestRangeKey, sst.SmallestPointKey) < 0 {
     637           1 :                         sst.Smallest = sst.SmallestRangeKey
     638           1 :                 }
     639             :         }
     640           1 :         switch {
     641           1 :         case len(sst.LargestRangeKey.UserKey) == 0:
     642           1 :                 sst.Largest = sst.LargestPointKey
     643           1 :         case len(sst.LargestPointKey.UserKey) == 0:
     644           1 :                 sst.Largest = sst.LargestRangeKey
     645           1 :         default:
     646           1 :                 sst.Largest = sst.LargestPointKey
     647           1 :                 if base.InternalCompare(cmp, sst.LargestRangeKey, sst.LargestPointKey) > 0 {
     648           1 :                         sst.Largest = sst.LargestRangeKey
     649           1 :                 }
     650             :         }
     651             :         // On rare occasion, a file might overlap with [lower, upper) but not actually
     652             :         // have any keys within those bounds. Skip such files.
     653           1 :         if len(sst.Smallest.UserKey) == 0 {
     654           1 :                 return nil, true, nil
     655           1 :         }
     656           1 :         sst.Size, err = d.tableCache.estimateSize(file, sst.Smallest.UserKey, sst.Largest.UserKey)
     657           1 :         if err != nil {
     658           0 :                 return nil, false, err
     659           0 :         }
     660             :         // On occasion, estimateSize gives us a low estimate, i.e. a 0 file size. This
     661             :         // can cause panics in places where we divide by file sizes. Correct for it
     662             :         // here.
     663           1 :         if sst.Size == 0 {
     664           1 :                 sst.Size = 1
     665           1 :         }
     666           1 :         return sst, false, nil
     667             : }
     668             : 
     669             : func scanInternalImpl(
     670             :         ctx context.Context, lower, upper []byte, iter *scanInternalIterator, opts *scanInternalOptions,
     671           1 : ) error {
     672           1 :         if opts.visitSharedFile != nil && (lower == nil || upper == nil) {
     673           0 :                 panic("lower and upper bounds must be specified in skip-shared iteration mode")
     674             :         }
     675           1 :         if opts.visitSharedFile != nil && opts.visitExternalFile != nil {
     676           0 :                 return base.AssertionFailedf("cannot provide both a shared-file and external-file visitor")
     677           0 :         }
     678             : 
     679             :         // Before starting iteration, check if any files in levels sharedLevelsStart
     680             :         // and below are *not* shared. Error out if that is the case, as skip-shared
     681             :         // iteration will not produce a consistent point-in-time view of this range
     682             :         // of keys. For files that are shared, call visitSharedFile with a truncated
     683             :         // version of that file.
     684           1 :         cmp := iter.comparer.Compare
     685           1 :         provider := iter.db.ObjProvider()
     686           1 :         seqNum := iter.seqNum
     687           1 :         current := iter.version
     688           1 :         if current == nil {
     689           1 :                 current = iter.readState.current
     690           1 :         }
     691             : 
     692           1 :         if opts.visitSharedFile != nil || opts.visitExternalFile != nil {
     693           1 :                 if provider == nil {
     694           0 :                         panic("expected non-nil Provider in skip-shared iteration mode")
     695             :                 }
     696             : 
     697           1 :                 firstLevelWithRemote := opts.skipLevelForOpts()
     698           1 :                 for level := firstLevelWithRemote; level < numLevels; level++ {
     699           1 :                         files := current.Levels[level].Iter()
     700           1 :                         for f := files.SeekGE(cmp, lower); f != nil && cmp(f.Smallest.UserKey, upper) < 0; f = files.Next() {
     701           1 :                                 if cmp(lower, f.Largest.UserKey) == 0 && f.Largest.IsExclusiveSentinel() {
     702           0 :                                         continue
     703             :                                 }
     704             : 
     705           1 :                                 var objMeta objstorage.ObjectMetadata
     706           1 :                                 var err error
     707           1 :                                 objMeta, err = provider.Lookup(fileTypeTable, f.FileBacking.DiskFileNum)
     708           1 :                                 if err != nil {
     709           0 :                                         return err
     710           0 :                                 }
     711             : 
     712             :                                 // We allow a mix of files at the first level.
     713           1 :                                 if level != firstLevelWithRemote {
     714           1 :                                         if !objMeta.IsShared() && !objMeta.IsExternal() {
     715           0 :                                                 return errors.Wrapf(ErrInvalidSkipSharedIteration, "file %s is not shared or external", objMeta.DiskFileNum)
     716           0 :                                         }
     717             :                                 }
     718             : 
     719           1 :                                 if objMeta.IsShared() && opts.visitSharedFile == nil {
     720           0 :                                         return errors.Wrapf(ErrInvalidSkipSharedIteration, "shared file is present but no shared file visitor is defined")
     721           0 :                                 }
     722             : 
     723           1 :                                 if objMeta.IsExternal() && opts.visitExternalFile == nil {
     724           1 :                                         return errors.Wrapf(ErrInvalidSkipSharedIteration, "external file is present but no external file visitor is defined")
     725           1 :                                 }
     726             : 
     727           1 :                                 if !base.Visible(f.LargestSeqNum, seqNum, base.InternalKeySeqNumMax) {
     728           1 :                                         return errors.Wrapf(ErrInvalidSkipSharedIteration, "file %s contains keys newer than snapshot", objMeta.DiskFileNum)
     729           1 :                                 }
     730             : 
     731           1 :                                 if level != firstLevelWithRemote && (!objMeta.IsShared() && !objMeta.IsExternal()) {
     732           0 :                                         return errors.Wrapf(ErrInvalidSkipSharedIteration, "file %s is not shared or external", objMeta.DiskFileNum)
     733           0 :                                 }
     734             : 
     735           1 :                                 if objMeta.IsShared() {
     736           1 :                                         var sst *SharedSSTMeta
     737           1 :                                         var skip bool
     738           1 :                                         sst, skip, err = iter.db.truncateSharedFile(ctx, lower, upper, level, f, objMeta)
     739           1 :                                         if err != nil {
     740           0 :                                                 return err
     741           0 :                                         }
     742           1 :                                         if skip {
     743           1 :                                                 continue
     744             :                                         }
     745           1 :                                         if err = opts.visitSharedFile(sst); err != nil {
     746           0 :                                                 return err
     747           0 :                                         }
     748           1 :                                 } else if objMeta.IsExternal() {
     749           1 :                                         sst, err := iter.db.truncateExternalFile(ctx, lower, upper, level, f, objMeta)
     750           1 :                                         if err != nil {
     751           0 :                                                 return err
     752           0 :                                         }
     753           1 :                                         if err := opts.visitExternalFile(sst); err != nil {
     754           0 :                                                 return err
     755           0 :                                         }
     756             :                                 }
     757             : 
     758             :                         }
     759             :                 }
     760             :         }
     761             : 
     762           1 :         for valid := iter.seekGE(lower); valid && iter.error() == nil; valid = iter.next() {
     763           1 :                 key := iter.unsafeKey()
     764           1 : 
     765           1 :                 if opts.rateLimitFunc != nil {
     766           0 :                         if err := opts.rateLimitFunc(key, iter.lazyValue()); err != nil {
     767           0 :                                 return err
     768           0 :                         }
     769             :                 }
     770             : 
     771           1 :                 switch key.Kind() {
     772           1 :                 case InternalKeyKindRangeKeyDelete, InternalKeyKindRangeKeyUnset, InternalKeyKindRangeKeySet:
     773           1 :                         if opts.visitRangeKey != nil {
     774           1 :                                 span := iter.unsafeSpan()
     775           1 :                                 // NB: The caller isn't interested in the sequence numbers of these
     776           1 :                                 // range keys. Rather, the caller wants them to be in trailer order
     777           1 :                                 // _after_ zeroing of sequence numbers. Copy span.Keys, sort it, and then
     778           1 :                                 // call visitRangeKey.
     779           1 :                                 keysCopy := make([]keyspan.Key, len(span.Keys))
     780           1 :                                 for i := range span.Keys {
     781           1 :                                         keysCopy[i] = span.Keys[i]
     782           1 :                                         keysCopy[i].Trailer = base.MakeTrailer(0, span.Keys[i].Kind())
     783           1 :                                 }
     784           1 :                                 keyspan.SortKeysByTrailer(&keysCopy)
     785           1 :                                 if err := opts.visitRangeKey(span.Start, span.End, keysCopy); err != nil {
     786           0 :                                         return err
     787           0 :                                 }
     788             :                         }
     789           1 :                 case InternalKeyKindRangeDelete:
     790           1 :                         if opts.visitRangeDel != nil {
     791           1 :                                 rangeDel := iter.unsafeRangeDel()
     792           1 :                                 if err := opts.visitRangeDel(rangeDel.Start, rangeDel.End, rangeDel.LargestSeqNum()); err != nil {
     793           0 :                                         return err
     794           0 :                                 }
     795             :                         }
     796           1 :                 default:
     797           1 :                         if opts.visitPointKey != nil {
     798           1 :                                 var info IteratorLevel
     799           1 :                                 if len(iter.mergingIter.heap.items) > 0 {
     800           1 :                                         mergingIterIdx := iter.mergingIter.heap.items[0].index
     801           1 :                                         info = iter.iterLevels[mergingIterIdx]
     802           1 :                                 } else {
     803           0 :                                         info = IteratorLevel{Kind: IteratorLevelUnknown}
     804           0 :                                 }
     805           1 :                                 val := iter.lazyValue()
     806           1 :                                 if err := opts.visitPointKey(key, val, info); err != nil {
     807           0 :                                         return err
     808           0 :                                 }
     809             :                         }
     810             :                 }
     811             :         }
     812             : 
     813           1 :         return nil
     814             : }
     815             : 
     816           1 : func (opts *scanInternalOptions) skipLevelForOpts() int {
     817           1 :         if opts.visitSharedFile != nil {
     818           1 :                 return sharedLevelsStart
     819           1 :         }
     820           1 :         if opts.visitExternalFile != nil {
     821           1 :                 return externalSkipStart
     822           1 :         }
     823           1 :         return numLevels
     824             : }
     825             : 
     826             : // constructPointIter constructs a merging iterator and sets i.iter to it.
     827             : func (i *scanInternalIterator) constructPointIter(
     828             :         categoryAndQoS sstable.CategoryAndQoS, memtables flushableList, buf *iterAlloc,
     829           1 : ) error {
     830           1 :         // Merging levels and levels from iterAlloc.
     831           1 :         mlevels := buf.mlevels[:0]
     832           1 :         levels := buf.levels[:0]
     833           1 : 
     834           1 :         // We compute the number of levels needed ahead of time and reallocate a slice if
     835           1 :         // the array from the iterAlloc isn't large enough. Doing this allocation once
     836           1 :         // should improve the performance.
     837           1 :         numMergingLevels := len(memtables)
     838           1 :         numLevelIters := 0
     839           1 : 
     840           1 :         current := i.version
     841           1 :         if current == nil {
     842           1 :                 current = i.readState.current
     843           1 :         }
     844           1 :         numMergingLevels += len(current.L0SublevelFiles)
     845           1 :         numLevelIters += len(current.L0SublevelFiles)
     846           1 : 
     847           1 :         skipStart := i.opts.skipLevelForOpts()
     848           1 :         for level := 1; level < len(current.Levels); level++ {
     849           1 :                 if current.Levels[level].Empty() {
     850           1 :                         continue
     851             :                 }
     852           1 :                 if level > skipStart {
     853           1 :                         continue
     854             :                 }
     855           1 :                 numMergingLevels++
     856           1 :                 numLevelIters++
     857             :         }
     858             : 
     859           1 :         if numMergingLevels > cap(mlevels) {
     860           0 :                 mlevels = make([]mergingIterLevel, 0, numMergingLevels)
     861           0 :         }
     862           1 :         if numLevelIters > cap(levels) {
     863           0 :                 levels = make([]levelIter, 0, numLevelIters)
     864           0 :         }
     865             :         // TODO(bilal): Push these into the iterAlloc buf.
     866           1 :         var rangeDelMiter keyspanimpl.MergingIter
     867           1 :         rangeDelIters := make([]keyspan.FragmentIterator, 0, numMergingLevels)
     868           1 :         rangeDelLevels := make([]keyspanimpl.LevelIter, 0, numLevelIters)
     869           1 : 
     870           1 :         i.iterLevels = make([]IteratorLevel, numMergingLevels)
     871           1 :         mlevelsIndex := 0
     872           1 : 
     873           1 :         // Next are the memtables.
     874           1 :         for j := len(memtables) - 1; j >= 0; j-- {
     875           1 :                 mem := memtables[j]
     876           1 :                 mlevels = append(mlevels, mergingIterLevel{
     877           1 :                         iter: mem.newIter(&i.opts.IterOptions),
     878           1 :                 })
     879           1 :                 i.iterLevels[mlevelsIndex] = IteratorLevel{
     880           1 :                         Kind:           IteratorLevelFlushable,
     881           1 :                         FlushableIndex: j,
     882           1 :                 }
     883           1 :                 mlevelsIndex++
     884           1 :                 if rdi := mem.newRangeDelIter(&i.opts.IterOptions); rdi != nil {
     885           1 :                         rangeDelIters = append(rangeDelIters, rdi)
     886           1 :                 }
     887             :         }
     888             : 
     889             :         // Next are the file levels: L0 sub-levels followed by lower levels.
     890           1 :         levelsIndex := len(levels)
     891           1 :         mlevels = mlevels[:numMergingLevels]
     892           1 :         levels = levels[:numLevelIters]
     893           1 :         rangeDelLevels = rangeDelLevels[:numLevelIters]
     894           1 :         i.opts.IterOptions.snapshotForHideObsoletePoints = i.seqNum
     895           1 :         i.opts.IterOptions.CategoryAndQoS = categoryAndQoS
     896           1 :         addLevelIterForFiles := func(files manifest.LevelIterator, level manifest.Level) {
     897           1 :                 li := &levels[levelsIndex]
     898           1 :                 rli := &rangeDelLevels[levelsIndex]
     899           1 : 
     900           1 :                 li.init(
     901           1 :                         i.ctx, i.opts.IterOptions, i.comparer, i.newIters, files, level,
     902           1 :                         internalIterOpts{})
     903           1 :                 li.initBoundaryContext(&mlevels[mlevelsIndex].levelIterBoundaryContext)
     904           1 :                 mlevels[mlevelsIndex].iter = li
     905           1 :                 rli.Init(keyspan.SpanIterOptions{RangeKeyFilters: i.opts.RangeKeyFilters},
     906           1 :                         i.comparer.Compare, tableNewRangeDelIter(i.ctx, i.newIters), files, level,
     907           1 :                         manifest.KeyTypePoint)
     908           1 :                 rangeDelIters = append(rangeDelIters, rli)
     909           1 : 
     910           1 :                 levelsIndex++
     911           1 :                 mlevelsIndex++
     912           1 :         }
     913             : 
     914           1 :         for j := len(current.L0SublevelFiles) - 1; j >= 0; j-- {
     915           1 :                 i.iterLevels[mlevelsIndex] = IteratorLevel{
     916           1 :                         Kind:     IteratorLevelLSM,
     917           1 :                         Level:    0,
     918           1 :                         Sublevel: j,
     919           1 :                 }
     920           1 :                 addLevelIterForFiles(current.L0SublevelFiles[j].Iter(), manifest.L0Sublevel(j))
     921           1 :         }
     922             :         // Add level iterators for the non-empty non-L0 levels.
     923           1 :         for level := 1; level < numLevels; level++ {
     924           1 :                 if current.Levels[level].Empty() {
     925           1 :                         continue
     926             :                 }
     927             : 
     928           1 :                 if level > skipStart {
     929           1 :                         continue
     930             :                 }
     931           1 :                 i.iterLevels[mlevelsIndex] = IteratorLevel{Kind: IteratorLevelLSM, Level: level}
     932           1 :                 levIter := current.Levels[level].Iter()
     933           1 :                 if level == skipStart {
     934           1 :                         nonRemoteFiles := make([]*manifest.FileMetadata, 0)
     935           1 :                         for f := levIter.First(); f != nil; f = levIter.Next() {
     936           1 :                                 meta, err := i.db.objProvider.Lookup(fileTypeTable, f.FileBacking.DiskFileNum)
     937           1 :                                 if err != nil {
     938           0 :                                         return err
     939           0 :                                 }
     940           1 :                                 if (meta.IsShared() && i.opts.visitSharedFile != nil) ||
     941           1 :                                         (meta.IsExternal() && i.opts.visitExternalFile != nil) {
     942           1 :                                         // Skip this file.
     943           1 :                                         continue
     944             :                                 }
     945           1 :                                 nonRemoteFiles = append(nonRemoteFiles, f)
     946             :                         }
     947           1 :                         levSlice := manifest.NewLevelSliceKeySorted(i.db.cmp, nonRemoteFiles)
     948           1 :                         levIter = levSlice.Iter()
     949             :                 }
     950             : 
     951           1 :                 addLevelIterForFiles(levIter, manifest.Level(level))
     952             :         }
     953             : 
     954           1 :         buf.merging.init(&i.opts.IterOptions, &InternalIteratorStats{}, i.comparer.Compare, i.comparer.Split, mlevels...)
     955           1 :         buf.merging.snapshot = i.seqNum
     956           1 :         rangeDelMiter.Init(i.comparer.Compare, keyspan.VisibleTransform(i.seqNum), new(keyspanimpl.MergingBuffers), rangeDelIters...)
     957           1 : 
     958           1 :         if i.opts.includeObsoleteKeys {
     959           1 :                 iiter := &keyspan.InterleavingIter{}
     960           1 :                 iiter.Init(i.comparer, &buf.merging, &rangeDelMiter,
     961           1 :                         keyspan.InterleavingIterOpts{
     962           1 :                                 LowerBound: i.opts.LowerBound,
     963           1 :                                 UpperBound: i.opts.UpperBound,
     964           1 :                         })
     965           1 :                 i.pointKeyIter = iiter
     966           1 :         } else {
     967           1 :                 pcIter := &pointCollapsingIterator{
     968           1 :                         comparer: i.comparer,
     969           1 :                         merge:    i.merge,
     970           1 :                         seqNum:   i.seqNum,
     971           1 :                 }
     972           1 :                 pcIter.iter.Init(i.comparer, &buf.merging, &rangeDelMiter, keyspan.InterleavingIterOpts{
     973           1 :                         LowerBound: i.opts.LowerBound,
     974           1 :                         UpperBound: i.opts.UpperBound,
     975           1 :                 })
     976           1 :                 i.pointKeyIter = pcIter
     977           1 :         }
     978           1 :         i.iter = i.pointKeyIter
     979           1 :         return nil
     980             : }
     981             : 
     982             : // constructRangeKeyIter constructs the range-key iterator stack, populating
     983             : // i.rangeKey.rangeKeyIter with the resulting iterator. This is similar to
     984             : // Iterator.constructRangeKeyIter, except it doesn't handle batches and ensures
     985             : // iterConfig does *not* elide unsets/deletes.
     986           1 : func (i *scanInternalIterator) constructRangeKeyIter() error {
     987           1 :         // We want the bounded iter from iterConfig, but not the collapsing of
     988           1 :         // RangeKeyUnsets and RangeKeyDels.
     989           1 :         i.rangeKey.rangeKeyIter = i.rangeKey.iterConfig.Init(
     990           1 :                 i.comparer, i.seqNum, i.opts.LowerBound, i.opts.UpperBound,
     991           1 :                 nil /* hasPrefix */, nil /* prefix */, true, /* internalKeys */
     992           1 :                 &i.rangeKey.rangeKeyBuffers.internal)
     993           1 : 
     994           1 :         // Next are the flushables: memtables and large batches.
     995           1 :         if i.readState != nil {
     996           1 :                 for j := len(i.readState.memtables) - 1; j >= 0; j-- {
     997           1 :                         mem := i.readState.memtables[j]
     998           1 :                         // We only need to read from memtables which contain sequence numbers older
     999           1 :                         // than seqNum.
    1000           1 :                         if logSeqNum := mem.logSeqNum; logSeqNum >= i.seqNum {
    1001           1 :                                 continue
    1002             :                         }
    1003           1 :                         if rki := mem.newRangeKeyIter(&i.opts.IterOptions); rki != nil {
    1004           1 :                                 i.rangeKey.iterConfig.AddLevel(rki)
    1005           1 :                         }
    1006             :                 }
    1007             :         }
    1008             : 
    1009           1 :         current := i.version
    1010           1 :         if current == nil {
    1011           1 :                 current = i.readState.current
    1012           1 :         }
    1013             :         // Next are the file levels: L0 sub-levels followed by lower levels.
    1014             :         //
    1015             :         // Add file-specific iterators for L0 files containing range keys. This is less
    1016             :         // efficient than using levelIters for sublevels of L0 files containing
    1017             :         // range keys, but range keys are expected to be sparse anyway, reducing the
    1018             :         // cost benefit of maintaining a separate L0Sublevels instance for range key
    1019             :         // files and then using it here.
    1020             :         //
    1021             :         // NB: We iterate L0's files in reverse order. They're sorted by
    1022             :         // LargestSeqNum ascending, and we need to add them to the merging iterator
    1023             :         // in LargestSeqNum descending to preserve the merging iterator's invariants
    1024             :         // around Key Trailer order.
    1025           1 :         iter := current.RangeKeyLevels[0].Iter()
    1026           1 :         for f := iter.Last(); f != nil; f = iter.Prev() {
    1027           1 :                 spanIter, err := i.newIterRangeKey(f, i.opts.SpanIterOptions())
    1028           1 :                 if err != nil {
    1029           0 :                         return err
    1030           0 :                 }
    1031           1 :                 i.rangeKey.iterConfig.AddLevel(spanIter)
    1032             :         }
    1033             :         // Add level iterators for the non-empty non-L0 levels.
    1034           1 :         skipStart := i.opts.skipLevelForOpts()
    1035           1 :         for level := 1; level < len(current.RangeKeyLevels); level++ {
    1036           1 :                 if current.RangeKeyLevels[level].Empty() {
    1037           1 :                         continue
    1038             :                 }
    1039           1 :                 if level > skipStart {
    1040           1 :                         continue
    1041             :                 }
    1042           1 :                 li := i.rangeKey.iterConfig.NewLevelIter()
    1043           1 :                 spanIterOpts := i.opts.SpanIterOptions()
    1044           1 :                 levIter := current.RangeKeyLevels[level].Iter()
    1045           1 :                 if level == skipStart {
    1046           1 :                         nonRemoteFiles := make([]*manifest.FileMetadata, 0)
    1047           1 :                         for f := levIter.First(); f != nil; f = levIter.Next() {
    1048           1 :                                 meta, err := i.db.objProvider.Lookup(fileTypeTable, f.FileBacking.DiskFileNum)
    1049           1 :                                 if err != nil {
    1050           0 :                                         return err
    1051           0 :                                 }
    1052           1 :                                 if (meta.IsShared() && i.opts.visitSharedFile != nil) ||
    1053           1 :                                         (meta.IsExternal() && i.opts.visitExternalFile != nil) {
    1054           1 :                                         // Skip this file.
    1055           1 :                                         continue
    1056             :                                 }
    1057           0 :                                 nonRemoteFiles = append(nonRemoteFiles, f)
    1058             :                         }
    1059           1 :                         levSlice := manifest.NewLevelSliceKeySorted(i.db.cmp, nonRemoteFiles)
    1060           1 :                         levIter = levSlice.Iter()
    1061             :                 }
    1062           1 :                 li.Init(spanIterOpts, i.comparer.Compare, i.newIterRangeKey, levIter,
    1063           1 :                         manifest.Level(level), manifest.KeyTypeRange)
    1064           1 :                 i.rangeKey.iterConfig.AddLevel(li)
    1065             :         }
    1066           1 :         return nil
    1067             : }
    1068             : 
    1069             : // seekGE seeks this iterator to the first key that's greater than or equal
    1070             : // to the specified user key.
    1071           1 : func (i *scanInternalIterator) seekGE(key []byte) bool {
    1072           1 :         i.iterKV = i.iter.SeekGE(key, base.SeekGEFlagsNone)
    1073           1 :         return i.iterKV != nil
    1074           1 : }
    1075             : 
    1076             : // unsafeKey returns the unsafe InternalKey at the current position. The value
    1077             : // is nil if the iterator is invalid or exhausted.
    1078           1 : func (i *scanInternalIterator) unsafeKey() *InternalKey {
    1079           1 :         return &i.iterKV.K
    1080           1 : }
    1081             : 
    1082             : // lazyValue returns a value pointer to the value at the current iterator
    1083             : // position. Behaviour undefined if unsafeKey() returns a Range key or Rangedel
    1084             : // kind key.
    1085           1 : func (i *scanInternalIterator) lazyValue() LazyValue {
    1086           1 :         return i.iterKV.V
    1087           1 : }
    1088             : 
    1089             : // unsafeRangeDel returns a range key span. Behaviour undefined if UnsafeKey returns
    1090             : // a non-rangedel kind.
    1091           1 : func (i *scanInternalIterator) unsafeRangeDel() *keyspan.Span {
    1092           1 :         type spanInternalIterator interface {
    1093           1 :                 Span() *keyspan.Span
    1094           1 :         }
    1095           1 :         return i.pointKeyIter.(spanInternalIterator).Span()
    1096           1 : }
    1097             : 
    1098             : // unsafeSpan returns a range key span. Behaviour undefined if UnsafeKey returns
    1099             : // a non-rangekey type.
    1100           1 : func (i *scanInternalIterator) unsafeSpan() *keyspan.Span {
    1101           1 :         return i.rangeKey.iiter.Span()
    1102           1 : }
    1103             : 
    1104             : // next advances the iterator in the forward direction, and returns the
    1105             : // iterator's new validity state.
    1106           1 : func (i *scanInternalIterator) next() bool {
    1107           1 :         i.iterKV = i.iter.Next()
    1108           1 :         return i.iterKV != nil
    1109           1 : }
    1110             : 
    1111             : // error returns an error from the internal iterator, if there's any.
    1112           1 : func (i *scanInternalIterator) error() error {
    1113           1 :         return i.iter.Error()
    1114           1 : }
    1115             : 
    1116             : // close closes this iterator, and releases any pooled objects.
    1117           1 : func (i *scanInternalIterator) close() error {
    1118           1 :         if err := i.iter.Close(); err != nil {
    1119           0 :                 return err
    1120           0 :         }
    1121           1 :         if i.readState != nil {
    1122           1 :                 i.readState.unref()
    1123           1 :         }
    1124           1 :         if i.version != nil {
    1125           1 :                 i.version.Unref()
    1126           1 :         }
    1127           1 :         if i.rangeKey != nil {
    1128           1 :                 i.rangeKey.PrepareForReuse()
    1129           1 :                 *i.rangeKey = iteratorRangeKeyState{
    1130           1 :                         rangeKeyBuffers: i.rangeKey.rangeKeyBuffers,
    1131           1 :                 }
    1132           1 :                 iterRangeKeyStateAllocPool.Put(i.rangeKey)
    1133           1 :                 i.rangeKey = nil
    1134           1 :         }
    1135           1 :         if alloc := i.alloc; alloc != nil {
    1136           1 :                 for j := range i.boundsBuf {
    1137           1 :                         if cap(i.boundsBuf[j]) >= maxKeyBufCacheSize {
    1138           0 :                                 alloc.boundsBuf[j] = nil
    1139           1 :                         } else {
    1140           1 :                                 alloc.boundsBuf[j] = i.boundsBuf[j]
    1141           1 :                         }
    1142             :                 }
    1143           1 :                 *alloc = iterAlloc{
    1144           1 :                         keyBuf:              alloc.keyBuf[:0],
    1145           1 :                         boundsBuf:           alloc.boundsBuf,
    1146           1 :                         prefixOrFullSeekKey: alloc.prefixOrFullSeekKey[:0],
    1147           1 :                 }
    1148           1 :                 iterAllocPool.Put(alloc)
    1149           1 :                 i.alloc = nil
    1150             :         }
    1151           1 :         return nil
    1152             : }
    1153             : 
    1154           1 : func (i *scanInternalIterator) initializeBoundBufs(lower, upper []byte) {
    1155           1 :         buf := i.boundsBuf[i.boundsBufIdx][:0]
    1156           1 :         if lower != nil {
    1157           1 :                 buf = append(buf, lower...)
    1158           1 :                 i.opts.LowerBound = buf
    1159           1 :         } else {
    1160           1 :                 i.opts.LowerBound = nil
    1161           1 :         }
    1162           1 :         if upper != nil {
    1163           1 :                 buf = append(buf, upper...)
    1164           1 :                 i.opts.UpperBound = buf[len(buf)-len(upper):]
    1165           1 :         } else {
    1166           1 :                 i.opts.UpperBound = nil
    1167           1 :         }
    1168           1 :         i.boundsBuf[i.boundsBufIdx] = buf
    1169           1 :         i.boundsBufIdx = 1 - i.boundsBufIdx
    1170             : }

Generated by: LCOV version 1.14