LCOV - code coverage report
Current view: top level - pebble - db.go (source / functions) Hit Total Coverage
Test: 2023-11-20 08:16Z b9be64b8 - tests + meta.lcov Lines: 1531 1698 90.2 %
Date: 2023-11-20 08:17:03 Functions: 0 0 -

          Line data    Source code
       1             : // Copyright 2012 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 provides an ordered key/value store.
       6             : package pebble // import "github.com/cockroachdb/pebble"
       7             : 
       8             : import (
       9             :         "context"
      10             :         "fmt"
      11             :         "io"
      12             :         "os"
      13             :         "strconv"
      14             :         "sync"
      15             :         "sync/atomic"
      16             :         "time"
      17             : 
      18             :         "github.com/cockroachdb/errors"
      19             :         "github.com/cockroachdb/pebble/internal/arenaskl"
      20             :         "github.com/cockroachdb/pebble/internal/base"
      21             :         "github.com/cockroachdb/pebble/internal/invalidating"
      22             :         "github.com/cockroachdb/pebble/internal/invariants"
      23             :         "github.com/cockroachdb/pebble/internal/keyspan"
      24             :         "github.com/cockroachdb/pebble/internal/manifest"
      25             :         "github.com/cockroachdb/pebble/internal/manual"
      26             :         "github.com/cockroachdb/pebble/objstorage"
      27             :         "github.com/cockroachdb/pebble/objstorage/remote"
      28             :         "github.com/cockroachdb/pebble/rangekey"
      29             :         "github.com/cockroachdb/pebble/record"
      30             :         "github.com/cockroachdb/pebble/sstable"
      31             :         "github.com/cockroachdb/pebble/vfs"
      32             :         "github.com/cockroachdb/pebble/vfs/atomicfs"
      33             :         "github.com/cockroachdb/tokenbucket"
      34             :         "github.com/prometheus/client_golang/prometheus"
      35             : )
      36             : 
      37             : const (
      38             :         // minTableCacheSize is the minimum size of the table cache, for a single db.
      39             :         minTableCacheSize = 64
      40             : 
      41             :         // numNonTableCacheFiles is an approximation for the number of files
      42             :         // that we don't use for table caches, for a given db.
      43             :         numNonTableCacheFiles = 10
      44             : )
      45             : 
      46             : var (
      47             :         // ErrNotFound is returned when a get operation does not find the requested
      48             :         // key.
      49             :         ErrNotFound = base.ErrNotFound
      50             :         // ErrClosed is panicked when an operation is performed on a closed snapshot or
      51             :         // DB. Use errors.Is(err, ErrClosed) to check for this error.
      52             :         ErrClosed = errors.New("pebble: closed")
      53             :         // ErrReadOnly is returned when a write operation is performed on a read-only
      54             :         // database.
      55             :         ErrReadOnly = errors.New("pebble: read-only")
      56             :         // errNoSplit indicates that the user is trying to perform a range key
      57             :         // operation but the configured Comparer does not provide a Split
      58             :         // implementation.
      59             :         errNoSplit = errors.New("pebble: Comparer.Split required for range key operations")
      60             : )
      61             : 
      62             : // Reader is a readable key/value store.
      63             : //
      64             : // It is safe to call Get and NewIter from concurrent goroutines.
      65             : type Reader interface {
      66             :         // Get gets the value for the given key. It returns ErrNotFound if the DB
      67             :         // does not contain the key.
      68             :         //
      69             :         // The caller should not modify the contents of the returned slice, but it is
      70             :         // safe to modify the contents of the argument after Get returns. The
      71             :         // returned slice will remain valid until the returned Closer is closed. On
      72             :         // success, the caller MUST call closer.Close() or a memory leak will occur.
      73             :         Get(key []byte) (value []byte, closer io.Closer, err error)
      74             : 
      75             :         // NewIter returns an iterator that is unpositioned (Iterator.Valid() will
      76             :         // return false). The iterator can be positioned via a call to SeekGE,
      77             :         // SeekLT, First or Last.
      78             :         NewIter(o *IterOptions) (*Iterator, error)
      79             : 
      80             :         // NewIterWithContext is like NewIter, and additionally accepts a context
      81             :         // for tracing.
      82             :         NewIterWithContext(ctx context.Context, o *IterOptions) (*Iterator, error)
      83             : 
      84             :         // Close closes the Reader. It may or may not close any underlying io.Reader
      85             :         // or io.Writer, depending on how the DB was created.
      86             :         //
      87             :         // It is not safe to close a DB until all outstanding iterators are closed.
      88             :         // It is valid to call Close multiple times. Other methods should not be
      89             :         // called after the DB has been closed.
      90             :         Close() error
      91             : }
      92             : 
      93             : // Writer is a writable key/value store.
      94             : //
      95             : // Goroutine safety is dependent on the specific implementation.
      96             : type Writer interface {
      97             :         // Apply the operations contained in the batch to the DB.
      98             :         //
      99             :         // It is safe to modify the contents of the arguments after Apply returns.
     100             :         Apply(batch *Batch, o *WriteOptions) error
     101             : 
     102             :         // Delete deletes the value for the given key. Deletes are blind all will
     103             :         // succeed even if the given key does not exist.
     104             :         //
     105             :         // It is safe to modify the contents of the arguments after Delete returns.
     106             :         Delete(key []byte, o *WriteOptions) error
     107             : 
     108             :         // DeleteSized behaves identically to Delete, but takes an additional
     109             :         // argument indicating the size of the value being deleted. DeleteSized
     110             :         // should be preferred when the caller has the expectation that there exists
     111             :         // a single internal KV pair for the key (eg, the key has not been
     112             :         // overwritten recently), and the caller knows the size of its value.
     113             :         //
     114             :         // DeleteSized will record the value size within the tombstone and use it to
     115             :         // inform compaction-picking heuristics which strive to reduce space
     116             :         // amplification in the LSM. This "calling your shot" mechanic allows the
     117             :         // storage engine to more accurately estimate and reduce space
     118             :         // amplification.
     119             :         //
     120             :         // It is safe to modify the contents of the arguments after DeleteSized
     121             :         // returns.
     122             :         DeleteSized(key []byte, valueSize uint32, _ *WriteOptions) error
     123             : 
     124             :         // SingleDelete is similar to Delete in that it deletes the value for the given key. Like Delete,
     125             :         // it is a blind operation that will succeed even if the given key does not exist.
     126             :         //
     127             :         // WARNING: Undefined (non-deterministic) behavior will result if a key is overwritten and
     128             :         // then deleted using SingleDelete. The record may appear deleted immediately, but be
     129             :         // resurrected at a later time after compactions have been performed. Or the record may
     130             :         // be deleted permanently. A Delete operation lays down a "tombstone" which shadows all
     131             :         // previous versions of a key. The SingleDelete operation is akin to "anti-matter" and will
     132             :         // only delete the most recently written version for a key. These different semantics allow
     133             :         // the DB to avoid propagating a SingleDelete operation during a compaction as soon as the
     134             :         // corresponding Set operation is encountered. These semantics require extreme care to handle
     135             :         // properly. Only use if you have a workload where the performance gain is critical and you
     136             :         // can guarantee that a record is written once and then deleted once.
     137             :         //
     138             :         // SingleDelete is internally transformed into a Delete if the most recent record for a key is either
     139             :         // a Merge or Delete record.
     140             :         //
     141             :         // It is safe to modify the contents of the arguments after SingleDelete returns.
     142             :         SingleDelete(key []byte, o *WriteOptions) error
     143             : 
     144             :         // DeleteRange deletes all of the point keys (and values) in the range
     145             :         // [start,end) (inclusive on start, exclusive on end). DeleteRange does NOT
     146             :         // delete overlapping range keys (eg, keys set via RangeKeySet).
     147             :         //
     148             :         // It is safe to modify the contents of the arguments after DeleteRange
     149             :         // returns.
     150             :         DeleteRange(start, end []byte, o *WriteOptions) error
     151             : 
     152             :         // LogData adds the specified to the batch. The data will be written to the
     153             :         // WAL, but not added to memtables or sstables. Log data is never indexed,
     154             :         // which makes it useful for testing WAL performance.
     155             :         //
     156             :         // It is safe to modify the contents of the argument after LogData returns.
     157             :         LogData(data []byte, opts *WriteOptions) error
     158             : 
     159             :         // Merge merges the value for the given key. The details of the merge are
     160             :         // dependent upon the configured merge operation.
     161             :         //
     162             :         // It is safe to modify the contents of the arguments after Merge returns.
     163             :         Merge(key, value []byte, o *WriteOptions) error
     164             : 
     165             :         // Set sets the value for the given key. It overwrites any previous value
     166             :         // for that key; a DB is not a multi-map.
     167             :         //
     168             :         // It is safe to modify the contents of the arguments after Set returns.
     169             :         Set(key, value []byte, o *WriteOptions) error
     170             : 
     171             :         // RangeKeySet sets a range key mapping the key range [start, end) at the MVCC
     172             :         // timestamp suffix to value. The suffix is optional. If any portion of the key
     173             :         // range [start, end) is already set by a range key with the same suffix value,
     174             :         // RangeKeySet overrides it.
     175             :         //
     176             :         // It is safe to modify the contents of the arguments after RangeKeySet returns.
     177             :         RangeKeySet(start, end, suffix, value []byte, opts *WriteOptions) error
     178             : 
     179             :         // RangeKeyUnset removes a range key mapping the key range [start, end) at the
     180             :         // MVCC timestamp suffix. The suffix may be omitted to remove an unsuffixed
     181             :         // range key. RangeKeyUnset only removes portions of range keys that fall within
     182             :         // the [start, end) key span, and only range keys with suffixes that exactly
     183             :         // match the unset suffix.
     184             :         //
     185             :         // It is safe to modify the contents of the arguments after RangeKeyUnset
     186             :         // returns.
     187             :         RangeKeyUnset(start, end, suffix []byte, opts *WriteOptions) error
     188             : 
     189             :         // RangeKeyDelete deletes all of the range keys in the range [start,end)
     190             :         // (inclusive on start, exclusive on end). It does not delete point keys (for
     191             :         // that use DeleteRange). RangeKeyDelete removes all range keys within the
     192             :         // bounds, including those with or without suffixes.
     193             :         //
     194             :         // It is safe to modify the contents of the arguments after RangeKeyDelete
     195             :         // returns.
     196             :         RangeKeyDelete(start, end []byte, opts *WriteOptions) error
     197             : }
     198             : 
     199             : // CPUWorkHandle represents a handle used by the CPUWorkPermissionGranter API.
     200             : type CPUWorkHandle interface {
     201             :         // Permitted indicates whether Pebble can use additional CPU resources.
     202             :         Permitted() bool
     203             : }
     204             : 
     205             : // CPUWorkPermissionGranter is used to request permission to opportunistically
     206             : // use additional CPUs to speed up internal background work.
     207             : type CPUWorkPermissionGranter interface {
     208             :         // GetPermission returns a handle regardless of whether permission is granted
     209             :         // or not. In the latter case, the handle is only useful for recording
     210             :         // the CPU time actually spent on this calling goroutine.
     211             :         GetPermission(time.Duration) CPUWorkHandle
     212             :         // CPUWorkDone must be called regardless of whether CPUWorkHandle.Permitted
     213             :         // returns true or false.
     214             :         CPUWorkDone(CPUWorkHandle)
     215             : }
     216             : 
     217             : // Use a default implementation for the CPU work granter to avoid excessive nil
     218             : // checks in the code.
     219             : type defaultCPUWorkHandle struct{}
     220             : 
     221           1 : func (d defaultCPUWorkHandle) Permitted() bool {
     222           1 :         return false
     223           1 : }
     224             : 
     225             : type defaultCPUWorkGranter struct{}
     226             : 
     227           2 : func (d defaultCPUWorkGranter) GetPermission(_ time.Duration) CPUWorkHandle {
     228           2 :         return defaultCPUWorkHandle{}
     229           2 : }
     230             : 
     231           2 : func (d defaultCPUWorkGranter) CPUWorkDone(_ CPUWorkHandle) {}
     232             : 
     233             : // DB provides a concurrent, persistent ordered key/value store.
     234             : //
     235             : // A DB's basic operations (Get, Set, Delete) should be self-explanatory. Get
     236             : // and Delete will return ErrNotFound if the requested key is not in the store.
     237             : // Callers are free to ignore this error.
     238             : //
     239             : // A DB also allows for iterating over the key/value pairs in key order. If d
     240             : // is a DB, the code below prints all key/value pairs whose keys are 'greater
     241             : // than or equal to' k:
     242             : //
     243             : //      iter := d.NewIter(readOptions)
     244             : //      for iter.SeekGE(k); iter.Valid(); iter.Next() {
     245             : //              fmt.Printf("key=%q value=%q\n", iter.Key(), iter.Value())
     246             : //      }
     247             : //      return iter.Close()
     248             : //
     249             : // The Options struct holds the optional parameters for the DB, including a
     250             : // Comparer to define a 'less than' relationship over keys. It is always valid
     251             : // to pass a nil *Options, which means to use the default parameter values. Any
     252             : // zero field of a non-nil *Options also means to use the default value for
     253             : // that parameter. Thus, the code below uses a custom Comparer, but the default
     254             : // values for every other parameter:
     255             : //
     256             : //      db := pebble.Open(&Options{
     257             : //              Comparer: myComparer,
     258             : //      })
     259             : type DB struct {
     260             :         // The count and size of referenced memtables. This includes memtables
     261             :         // present in DB.mu.mem.queue, as well as memtables that have been flushed
     262             :         // but are still referenced by an inuse readState, as well as up to one
     263             :         // memTable waiting to be reused and stored in d.memTableRecycle.
     264             :         memTableCount    atomic.Int64
     265             :         memTableReserved atomic.Int64 // number of bytes reserved in the cache for memtables
     266             :         // memTableRecycle holds a pointer to an obsolete memtable. The next
     267             :         // memtable allocation will reuse this memtable if it has not already been
     268             :         // recycled.
     269             :         memTableRecycle atomic.Pointer[memTable]
     270             : 
     271             :         // The size of the current log file (i.e. db.mu.log.queue[len(queue)-1].
     272             :         logSize atomic.Uint64
     273             : 
     274             :         // The number of bytes available on disk.
     275             :         diskAvailBytes atomic.Uint64
     276             : 
     277             :         cacheID        uint64
     278             :         dirname        string
     279             :         walDirname     string
     280             :         opts           *Options
     281             :         cmp            Compare
     282             :         equal          Equal
     283             :         merge          Merge
     284             :         split          Split
     285             :         abbreviatedKey AbbreviatedKey
     286             :         // The threshold for determining when a batch is "large" and will skip being
     287             :         // inserted into a memtable.
     288             :         largeBatchThreshold uint64
     289             :         // The current OPTIONS file number.
     290             :         optionsFileNum base.DiskFileNum
     291             :         // The on-disk size of the current OPTIONS file.
     292             :         optionsFileSize uint64
     293             : 
     294             :         // objProvider is used to access and manage SSTs.
     295             :         objProvider objstorage.Provider
     296             : 
     297             :         fileLock *Lock
     298             :         dataDir  vfs.File
     299             :         walDir   vfs.File
     300             : 
     301             :         tableCache           *tableCacheContainer
     302             :         newIters             tableNewIters
     303             :         tableNewRangeKeyIter keyspan.TableNewSpanIter
     304             : 
     305             :         commit *commitPipeline
     306             : 
     307             :         // readState provides access to the state needed for reading without needing
     308             :         // to acquire DB.mu.
     309             :         readState struct {
     310             :                 sync.RWMutex
     311             :                 val *readState
     312             :         }
     313             :         // logRecycler holds a set of log file numbers that are available for
     314             :         // reuse. Writing to a recycled log file is faster than to a new log file on
     315             :         // some common filesystems (xfs, and ext3/4) due to avoiding metadata
     316             :         // updates.
     317             :         logRecycler logRecycler
     318             : 
     319             :         closed   *atomic.Value
     320             :         closedCh chan struct{}
     321             : 
     322             :         cleanupManager *cleanupManager
     323             : 
     324             :         // During an iterator close, we may asynchronously schedule read compactions.
     325             :         // We want to wait for those goroutines to finish, before closing the DB.
     326             :         // compactionShedulers.Wait() should not be called while the DB.mu is held.
     327             :         compactionSchedulers sync.WaitGroup
     328             : 
     329             :         // The main mutex protecting internal DB state. This mutex encompasses many
     330             :         // fields because those fields need to be accessed and updated atomically. In
     331             :         // particular, the current version, log.*, mem.*, and snapshot list need to
     332             :         // be accessed and updated atomically during compaction.
     333             :         //
     334             :         // Care is taken to avoid holding DB.mu during IO operations. Accomplishing
     335             :         // this sometimes requires releasing DB.mu in a method that was called with
     336             :         // it held. See versionSet.logAndApply() and DB.makeRoomForWrite() for
     337             :         // examples. This is a common pattern, so be careful about expectations that
     338             :         // DB.mu will be held continuously across a set of calls.
     339             :         mu struct {
     340             :                 sync.Mutex
     341             : 
     342             :                 formatVers struct {
     343             :                         // vers is the database's current format major version.
     344             :                         // Backwards-incompatible features are gated behind new
     345             :                         // format major versions and not enabled until a database's
     346             :                         // version is ratcheted upwards.
     347             :                         //
     348             :                         // Although this is under the `mu` prefix, readers may read vers
     349             :                         // atomically without holding d.mu. Writers must only write to this
     350             :                         // value through finalizeFormatVersUpgrade which requires d.mu is
     351             :                         // held.
     352             :                         vers atomic.Uint64
     353             :                         // marker is the atomic marker for the format major version.
     354             :                         // When a database's version is ratcheted upwards, the
     355             :                         // marker is moved in order to atomically record the new
     356             :                         // version.
     357             :                         marker *atomicfs.Marker
     358             :                         // ratcheting when set to true indicates that the database is
     359             :                         // currently in the process of ratcheting the format major version
     360             :                         // to vers + 1. As a part of ratcheting the format major version,
     361             :                         // migrations may drop and re-acquire the mutex.
     362             :                         ratcheting bool
     363             :                 }
     364             : 
     365             :                 // The ID of the next job. Job IDs are passed to event listener
     366             :                 // notifications and act as a mechanism for tying together the events and
     367             :                 // log messages for a single job such as a flush, compaction, or file
     368             :                 // ingestion. Job IDs are not serialized to disk or used for correctness.
     369             :                 nextJobID int
     370             : 
     371             :                 // The collection of immutable versions and state about the log and visible
     372             :                 // sequence numbers. Use the pointer here to ensure the atomic fields in
     373             :                 // version set are aligned properly.
     374             :                 versions *versionSet
     375             : 
     376             :                 log struct {
     377             :                         // The queue of logs, containing both flushed and unflushed logs. The
     378             :                         // flushed logs will be a prefix, the unflushed logs a suffix. The
     379             :                         // delimeter between flushed and unflushed logs is
     380             :                         // versionSet.minUnflushedLogNum.
     381             :                         queue []fileInfo
     382             :                         // The number of input bytes to the log. This is the raw size of the
     383             :                         // batches written to the WAL, without the overhead of the record
     384             :                         // envelopes.
     385             :                         bytesIn uint64
     386             :                         // The LogWriter is protected by commitPipeline.mu. This allows log
     387             :                         // writes to be performed without holding DB.mu, but requires both
     388             :                         // commitPipeline.mu and DB.mu to be held when rotating the WAL/memtable
     389             :                         // (i.e. makeRoomForWrite).
     390             :                         *record.LogWriter
     391             :                         // Can be nil.
     392             :                         metrics struct {
     393             :                                 fsyncLatency prometheus.Histogram
     394             :                                 record.LogWriterMetrics
     395             :                         }
     396             :                         registerLogWriterForTesting func(w *record.LogWriter)
     397             :                 }
     398             : 
     399             :                 mem struct {
     400             :                         // The current mutable memTable.
     401             :                         mutable *memTable
     402             :                         // Queue of flushables (the mutable memtable is at end). Elements are
     403             :                         // added to the end of the slice and removed from the beginning. Once an
     404             :                         // index is set it is never modified making a fixed slice immutable and
     405             :                         // safe for concurrent reads.
     406             :                         queue flushableList
     407             :                         // nextSize is the size of the next memtable. The memtable size starts at
     408             :                         // min(256KB,Options.MemTableSize) and doubles each time a new memtable
     409             :                         // is allocated up to Options.MemTableSize. This reduces the memory
     410             :                         // footprint of memtables when lots of DB instances are used concurrently
     411             :                         // in test environments.
     412             :                         nextSize uint64
     413             :                 }
     414             : 
     415             :                 compact struct {
     416             :                         // Condition variable used to signal when a flush or compaction has
     417             :                         // completed. Used by the write-stall mechanism to wait for the stall
     418             :                         // condition to clear. See DB.makeRoomForWrite().
     419             :                         cond sync.Cond
     420             :                         // True when a flush is in progress.
     421             :                         flushing bool
     422             :                         // The number of ongoing compactions.
     423             :                         compactingCount int
     424             :                         // The list of deletion hints, suggesting ranges for delete-only
     425             :                         // compactions.
     426             :                         deletionHints []deleteCompactionHint
     427             :                         // The list of manual compactions. The next manual compaction to perform
     428             :                         // is at the start of the list. New entries are added to the end.
     429             :                         manual []*manualCompaction
     430             :                         // inProgress is the set of in-progress flushes and compactions.
     431             :                         // It's used in the calculation of some metrics and to initialize L0
     432             :                         // sublevels' state. Some of the compactions contained within this
     433             :                         // map may have already committed an edit to the version but are
     434             :                         // lingering performing cleanup, like deleting obsolete files.
     435             :                         inProgress map[*compaction]struct{}
     436             : 
     437             :                         // rescheduleReadCompaction indicates to an iterator that a read compaction
     438             :                         // should be scheduled.
     439             :                         rescheduleReadCompaction bool
     440             : 
     441             :                         // readCompactions is a readCompactionQueue which keeps track of the
     442             :                         // compactions which we might have to perform.
     443             :                         readCompactions readCompactionQueue
     444             : 
     445             :                         // The cumulative duration of all completed compactions since Open.
     446             :                         // Does not include flushes.
     447             :                         duration time.Duration
     448             :                         // Flush throughput metric.
     449             :                         flushWriteThroughput ThroughputMetric
     450             :                         // The idle start time for the flush "loop", i.e., when the flushing
     451             :                         // bool above transitions to false.
     452             :                         noOngoingFlushStartTime time.Time
     453             :                 }
     454             : 
     455             :                 // Non-zero when file cleaning is disabled. The disabled count acts as a
     456             :                 // reference count to prohibit file cleaning. See
     457             :                 // DB.{disable,Enable}FileDeletions().
     458             :                 disableFileDeletions int
     459             : 
     460             :                 snapshots struct {
     461             :                         // The list of active snapshots.
     462             :                         snapshotList
     463             : 
     464             :                         // The cumulative count and size of snapshot-pinned keys written to
     465             :                         // sstables.
     466             :                         cumulativePinnedCount uint64
     467             :                         cumulativePinnedSize  uint64
     468             :                 }
     469             : 
     470             :                 tableStats struct {
     471             :                         // Condition variable used to signal the completion of a
     472             :                         // job to collect table stats.
     473             :                         cond sync.Cond
     474             :                         // True when a stat collection operation is in progress.
     475             :                         loading bool
     476             :                         // True if stat collection has loaded statistics for all tables
     477             :                         // other than those listed explicitly in pending. This flag starts
     478             :                         // as false when a database is opened and flips to true once stat
     479             :                         // collection has caught up.
     480             :                         loadedInitial bool
     481             :                         // A slice of files for which stats have not been computed.
     482             :                         // Compactions, ingests, flushes append files to be processed. An
     483             :                         // active stat collection goroutine clears the list and processes
     484             :                         // them.
     485             :                         pending []manifest.NewFileEntry
     486             :                 }
     487             : 
     488             :                 tableValidation struct {
     489             :                         // cond is a condition variable used to signal the completion of a
     490             :                         // job to validate one or more sstables.
     491             :                         cond sync.Cond
     492             :                         // pending is a slice of metadata for sstables waiting to be
     493             :                         // validated. Only physical sstables should be added to the pending
     494             :                         // queue.
     495             :                         pending []newFileEntry
     496             :                         // validating is set to true when validation is running.
     497             :                         validating bool
     498             :                 }
     499             :         }
     500             : 
     501             :         // Normally equal to time.Now() but may be overridden in tests.
     502             :         timeNow func() time.Time
     503             :         // the time at database Open; may be used to compute metrics like effective
     504             :         // compaction concurrency
     505             :         openedAt time.Time
     506             : }
     507             : 
     508             : var _ Reader = (*DB)(nil)
     509             : var _ Writer = (*DB)(nil)
     510             : 
     511             : // TestOnlyWaitForCleaning MUST only be used in tests.
     512           1 : func (d *DB) TestOnlyWaitForCleaning() {
     513           1 :         d.cleanupManager.Wait()
     514           1 : }
     515             : 
     516             : // Get gets the value for the given key. It returns ErrNotFound if the DB does
     517             : // not contain the key.
     518             : //
     519             : // The caller should not modify the contents of the returned slice, but it is
     520             : // safe to modify the contents of the argument after Get returns. The returned
     521             : // slice will remain valid until the returned Closer is closed. On success, the
     522             : // caller MUST call closer.Close() or a memory leak will occur.
     523           2 : func (d *DB) Get(key []byte) ([]byte, io.Closer, error) {
     524           2 :         return d.getInternal(key, nil /* batch */, nil /* snapshot */)
     525           2 : }
     526             : 
     527             : type getIterAlloc struct {
     528             :         dbi    Iterator
     529             :         keyBuf []byte
     530             :         get    getIter
     531             : }
     532             : 
     533             : var getIterAllocPool = sync.Pool{
     534           2 :         New: func() interface{} {
     535           2 :                 return &getIterAlloc{}
     536           2 :         },
     537             : }
     538             : 
     539           2 : func (d *DB) getInternal(key []byte, b *Batch, s *Snapshot) ([]byte, io.Closer, error) {
     540           2 :         if err := d.closed.Load(); err != nil {
     541           1 :                 panic(err)
     542             :         }
     543             : 
     544             :         // Grab and reference the current readState. This prevents the underlying
     545             :         // files in the associated version from being deleted if there is a current
     546             :         // compaction. The readState is unref'd by Iterator.Close().
     547           2 :         readState := d.loadReadState()
     548           2 : 
     549           2 :         // Determine the seqnum to read at after grabbing the read state (current and
     550           2 :         // memtables) above.
     551           2 :         var seqNum uint64
     552           2 :         if s != nil {
     553           2 :                 seqNum = s.seqNum
     554           2 :         } else {
     555           2 :                 seqNum = d.mu.versions.visibleSeqNum.Load()
     556           2 :         }
     557             : 
     558           2 :         buf := getIterAllocPool.Get().(*getIterAlloc)
     559           2 : 
     560           2 :         get := &buf.get
     561           2 :         *get = getIter{
     562           2 :                 logger:   d.opts.Logger,
     563           2 :                 comparer: d.opts.Comparer,
     564           2 :                 newIters: d.newIters,
     565           2 :                 snapshot: seqNum,
     566           2 :                 key:      key,
     567           2 :                 batch:    b,
     568           2 :                 mem:      readState.memtables,
     569           2 :                 l0:       readState.current.L0SublevelFiles,
     570           2 :                 version:  readState.current,
     571           2 :         }
     572           2 : 
     573           2 :         // Strip off memtables which cannot possibly contain the seqNum being read
     574           2 :         // at.
     575           2 :         for len(get.mem) > 0 {
     576           2 :                 n := len(get.mem)
     577           2 :                 if logSeqNum := get.mem[n-1].logSeqNum; logSeqNum < seqNum {
     578           2 :                         break
     579             :                 }
     580           2 :                 get.mem = get.mem[:n-1]
     581             :         }
     582             : 
     583           2 :         i := &buf.dbi
     584           2 :         pointIter := get
     585           2 :         *i = Iterator{
     586           2 :                 ctx:          context.Background(),
     587           2 :                 getIterAlloc: buf,
     588           2 :                 iter:         pointIter,
     589           2 :                 pointIter:    pointIter,
     590           2 :                 merge:        d.merge,
     591           2 :                 comparer:     *d.opts.Comparer,
     592           2 :                 readState:    readState,
     593           2 :                 keyBuf:       buf.keyBuf,
     594           2 :         }
     595           2 : 
     596           2 :         if !i.First() {
     597           2 :                 err := i.Close()
     598           2 :                 if err != nil {
     599           1 :                         return nil, nil, err
     600           1 :                 }
     601           2 :                 return nil, nil, ErrNotFound
     602             :         }
     603           2 :         return i.Value(), i, nil
     604             : }
     605             : 
     606             : // Set sets the value for the given key. It overwrites any previous value
     607             : // for that key; a DB is not a multi-map.
     608             : //
     609             : // It is safe to modify the contents of the arguments after Set returns.
     610           2 : func (d *DB) Set(key, value []byte, opts *WriteOptions) error {
     611           2 :         b := newBatch(d)
     612           2 :         _ = b.Set(key, value, opts)
     613           2 :         if err := d.Apply(b, opts); err != nil {
     614           1 :                 return err
     615           1 :         }
     616             :         // Only release the batch on success.
     617           2 :         b.release()
     618           2 :         return nil
     619             : }
     620             : 
     621             : // Delete deletes the value for the given key. Deletes are blind all will
     622             : // succeed even if the given key does not exist.
     623             : //
     624             : // It is safe to modify the contents of the arguments after Delete returns.
     625           2 : func (d *DB) Delete(key []byte, opts *WriteOptions) error {
     626           2 :         b := newBatch(d)
     627           2 :         _ = b.Delete(key, opts)
     628           2 :         if err := d.Apply(b, opts); err != nil {
     629           1 :                 return err
     630           1 :         }
     631             :         // Only release the batch on success.
     632           2 :         b.release()
     633           2 :         return nil
     634             : }
     635             : 
     636             : // DeleteSized behaves identically to Delete, but takes an additional
     637             : // argument indicating the size of the value being deleted. DeleteSized
     638             : // should be preferred when the caller has the expectation that there exists
     639             : // a single internal KV pair for the key (eg, the key has not been
     640             : // overwritten recently), and the caller knows the size of its value.
     641             : //
     642             : // DeleteSized will record the value size within the tombstone and use it to
     643             : // inform compaction-picking heuristics which strive to reduce space
     644             : // amplification in the LSM. This "calling your shot" mechanic allows the
     645             : // storage engine to more accurately estimate and reduce space amplification.
     646             : //
     647             : // It is safe to modify the contents of the arguments after DeleteSized
     648             : // returns.
     649           1 : func (d *DB) DeleteSized(key []byte, valueSize uint32, opts *WriteOptions) error {
     650           1 :         b := newBatch(d)
     651           1 :         _ = b.DeleteSized(key, valueSize, opts)
     652           1 :         if err := d.Apply(b, opts); err != nil {
     653           0 :                 return err
     654           0 :         }
     655             :         // Only release the batch on success.
     656           1 :         b.release()
     657           1 :         return nil
     658             : }
     659             : 
     660             : // SingleDelete adds an action to the batch that single deletes the entry for key.
     661             : // See Writer.SingleDelete for more details on the semantics of SingleDelete.
     662             : //
     663             : // It is safe to modify the contents of the arguments after SingleDelete returns.
     664           2 : func (d *DB) SingleDelete(key []byte, opts *WriteOptions) error {
     665           2 :         b := newBatch(d)
     666           2 :         _ = b.SingleDelete(key, opts)
     667           2 :         if err := d.Apply(b, opts); err != nil {
     668           0 :                 return err
     669           0 :         }
     670             :         // Only release the batch on success.
     671           2 :         b.release()
     672           2 :         return nil
     673             : }
     674             : 
     675             : // DeleteRange deletes all of the keys (and values) in the range [start,end)
     676             : // (inclusive on start, exclusive on end).
     677             : //
     678             : // It is safe to modify the contents of the arguments after DeleteRange
     679             : // returns.
     680           2 : func (d *DB) DeleteRange(start, end []byte, opts *WriteOptions) error {
     681           2 :         b := newBatch(d)
     682           2 :         _ = b.DeleteRange(start, end, opts)
     683           2 :         if err := d.Apply(b, opts); err != nil {
     684           1 :                 return err
     685           1 :         }
     686             :         // Only release the batch on success.
     687           2 :         b.release()
     688           2 :         return nil
     689             : }
     690             : 
     691             : // Merge adds an action to the DB that merges the value at key with the new
     692             : // value. The details of the merge are dependent upon the configured merge
     693             : // operator.
     694             : //
     695             : // It is safe to modify the contents of the arguments after Merge returns.
     696           2 : func (d *DB) Merge(key, value []byte, opts *WriteOptions) error {
     697           2 :         b := newBatch(d)
     698           2 :         _ = b.Merge(key, value, opts)
     699           2 :         if err := d.Apply(b, opts); err != nil {
     700           1 :                 return err
     701           1 :         }
     702             :         // Only release the batch on success.
     703           2 :         b.release()
     704           2 :         return nil
     705             : }
     706             : 
     707             : // LogData adds the specified to the batch. The data will be written to the
     708             : // WAL, but not added to memtables or sstables. Log data is never indexed,
     709             : // which makes it useful for testing WAL performance.
     710             : //
     711             : // It is safe to modify the contents of the argument after LogData returns.
     712           1 : func (d *DB) LogData(data []byte, opts *WriteOptions) error {
     713           1 :         b := newBatch(d)
     714           1 :         _ = b.LogData(data, opts)
     715           1 :         if err := d.Apply(b, opts); err != nil {
     716           1 :                 return err
     717           1 :         }
     718             :         // Only release the batch on success.
     719           1 :         b.release()
     720           1 :         return nil
     721             : }
     722             : 
     723             : // RangeKeySet sets a range key mapping the key range [start, end) at the MVCC
     724             : // timestamp suffix to value. The suffix is optional. If any portion of the key
     725             : // range [start, end) is already set by a range key with the same suffix value,
     726             : // RangeKeySet overrides it.
     727             : //
     728             : // It is safe to modify the contents of the arguments after RangeKeySet returns.
     729           2 : func (d *DB) RangeKeySet(start, end, suffix, value []byte, opts *WriteOptions) error {
     730           2 :         b := newBatch(d)
     731           2 :         _ = b.RangeKeySet(start, end, suffix, value, opts)
     732           2 :         if err := d.Apply(b, opts); err != nil {
     733           0 :                 return err
     734           0 :         }
     735             :         // Only release the batch on success.
     736           2 :         b.release()
     737           2 :         return nil
     738             : }
     739             : 
     740             : // RangeKeyUnset removes a range key mapping the key range [start, end) at the
     741             : // MVCC timestamp suffix. The suffix may be omitted to remove an unsuffixed
     742             : // range key. RangeKeyUnset only removes portions of range keys that fall within
     743             : // the [start, end) key span, and only range keys with suffixes that exactly
     744             : // match the unset suffix.
     745             : //
     746             : // It is safe to modify the contents of the arguments after RangeKeyUnset
     747             : // returns.
     748           2 : func (d *DB) RangeKeyUnset(start, end, suffix []byte, opts *WriteOptions) error {
     749           2 :         b := newBatch(d)
     750           2 :         _ = b.RangeKeyUnset(start, end, suffix, opts)
     751           2 :         if err := d.Apply(b, opts); err != nil {
     752           0 :                 return err
     753           0 :         }
     754             :         // Only release the batch on success.
     755           2 :         b.release()
     756           2 :         return nil
     757             : }
     758             : 
     759             : // RangeKeyDelete deletes all of the range keys in the range [start,end)
     760             : // (inclusive on start, exclusive on end). It does not delete point keys (for
     761             : // that use DeleteRange). RangeKeyDelete removes all range keys within the
     762             : // bounds, including those with or without suffixes.
     763             : //
     764             : // It is safe to modify the contents of the arguments after RangeKeyDelete
     765             : // returns.
     766           2 : func (d *DB) RangeKeyDelete(start, end []byte, opts *WriteOptions) error {
     767           2 :         b := newBatch(d)
     768           2 :         _ = b.RangeKeyDelete(start, end, opts)
     769           2 :         if err := d.Apply(b, opts); err != nil {
     770           0 :                 return err
     771           0 :         }
     772             :         // Only release the batch on success.
     773           2 :         b.release()
     774           2 :         return nil
     775             : }
     776             : 
     777             : // Apply the operations contained in the batch to the DB. If the batch is large
     778             : // the contents of the batch may be retained by the database. If that occurs
     779             : // the batch contents will be cleared preventing the caller from attempting to
     780             : // reuse them.
     781             : //
     782             : // It is safe to modify the contents of the arguments after Apply returns.
     783           2 : func (d *DB) Apply(batch *Batch, opts *WriteOptions) error {
     784           2 :         return d.applyInternal(batch, opts, false)
     785           2 : }
     786             : 
     787             : // ApplyNoSyncWait must only be used when opts.Sync is true and the caller
     788             : // does not want to wait for the WAL fsync to happen. The method will return
     789             : // once the mutation is applied to the memtable and is visible (note that a
     790             : // mutation is visible before the WAL sync even in the wait case, so we have
     791             : // not weakened the durability semantics). The caller must call Batch.SyncWait
     792             : // to wait for the WAL fsync. The caller must not Close the batch without
     793             : // first calling Batch.SyncWait.
     794             : //
     795             : // RECOMMENDATION: Prefer using Apply unless you really understand why you
     796             : // need ApplyNoSyncWait.
     797             : // EXPERIMENTAL: API/feature subject to change. Do not yet use outside
     798             : // CockroachDB.
     799           2 : func (d *DB) ApplyNoSyncWait(batch *Batch, opts *WriteOptions) error {
     800           2 :         if !opts.Sync {
     801           0 :                 return errors.Errorf("cannot request asynchonous apply when WriteOptions.Sync is false")
     802           0 :         }
     803           2 :         return d.applyInternal(batch, opts, true)
     804             : }
     805             : 
     806             : // REQUIRES: noSyncWait => opts.Sync
     807           2 : func (d *DB) applyInternal(batch *Batch, opts *WriteOptions, noSyncWait bool) error {
     808           2 :         if err := d.closed.Load(); err != nil {
     809           1 :                 panic(err)
     810             :         }
     811           2 :         if batch.committing {
     812           0 :                 panic("pebble: batch already committing")
     813             :         }
     814           2 :         if batch.applied.Load() {
     815           0 :                 panic("pebble: batch already applied")
     816             :         }
     817           2 :         if d.opts.ReadOnly {
     818           1 :                 return ErrReadOnly
     819           1 :         }
     820           2 :         if batch.db != nil && batch.db != d {
     821           1 :                 panic(fmt.Sprintf("pebble: batch db mismatch: %p != %p", batch.db, d))
     822             :         }
     823             : 
     824           2 :         sync := opts.GetSync()
     825           2 :         if sync && d.opts.DisableWAL {
     826           0 :                 return errors.New("pebble: WAL disabled")
     827           0 :         }
     828             : 
     829           2 :         if batch.minimumFormatMajorVersion != FormatMostCompatible {
     830           2 :                 if fmv := d.FormatMajorVersion(); fmv < batch.minimumFormatMajorVersion {
     831           1 :                         panic(fmt.Sprintf(
     832           1 :                                 "pebble: batch requires at least format major version %d (current: %d)",
     833           1 :                                 batch.minimumFormatMajorVersion, fmv,
     834           1 :                         ))
     835             :                 }
     836             :         }
     837             : 
     838           2 :         if batch.countRangeKeys > 0 {
     839           2 :                 if d.split == nil {
     840           0 :                         return errNoSplit
     841           0 :                 }
     842             :                 // TODO(jackson): Assert that all range key operands are suffixless.
     843             :         }
     844           2 :         batch.committing = true
     845           2 : 
     846           2 :         if batch.db == nil {
     847           1 :                 batch.refreshMemTableSize()
     848           1 :         }
     849           2 :         if batch.memTableSize >= d.largeBatchThreshold {
     850           2 :                 batch.flushable = newFlushableBatch(batch, d.opts.Comparer)
     851           2 :         }
     852           2 :         if err := d.commit.Commit(batch, sync, noSyncWait); err != nil {
     853           0 :                 // There isn't much we can do on an error here. The commit pipeline will be
     854           0 :                 // horked at this point.
     855           0 :                 d.opts.Logger.Fatalf("pebble: fatal commit error: %v", err)
     856           0 :         }
     857             :         // If this is a large batch, we need to clear the batch contents as the
     858             :         // flushable batch may still be present in the flushables queue.
     859             :         //
     860             :         // TODO(peter): Currently large batches are written to the WAL. We could
     861             :         // skip the WAL write and instead wait for the large batch to be flushed to
     862             :         // an sstable. For a 100 MB batch, this might actually be faster. For a 1
     863             :         // GB batch this is almost certainly faster.
     864           2 :         if batch.flushable != nil {
     865           2 :                 batch.data = nil
     866           2 :         }
     867           2 :         return nil
     868             : }
     869             : 
     870           2 : func (d *DB) commitApply(b *Batch, mem *memTable) error {
     871           2 :         if b.flushable != nil {
     872           2 :                 // This is a large batch which was already added to the immutable queue.
     873           2 :                 return nil
     874           2 :         }
     875           2 :         err := mem.apply(b, b.SeqNum())
     876           2 :         if err != nil {
     877           0 :                 return err
     878           0 :         }
     879             : 
     880             :         // If the batch contains range tombstones and the database is configured
     881             :         // to flush range deletions, schedule a delayed flush so that disk space
     882             :         // may be reclaimed without additional writes or an explicit flush.
     883           2 :         if b.countRangeDels > 0 && d.opts.FlushDelayDeleteRange > 0 {
     884           2 :                 d.mu.Lock()
     885           2 :                 d.maybeScheduleDelayedFlush(mem, d.opts.FlushDelayDeleteRange)
     886           2 :                 d.mu.Unlock()
     887           2 :         }
     888             : 
     889             :         // If the batch contains range keys and the database is configured to flush
     890             :         // range keys, schedule a delayed flush so that the range keys are cleared
     891             :         // from the memtable.
     892           2 :         if b.countRangeKeys > 0 && d.opts.FlushDelayRangeKey > 0 {
     893           2 :                 d.mu.Lock()
     894           2 :                 d.maybeScheduleDelayedFlush(mem, d.opts.FlushDelayRangeKey)
     895           2 :                 d.mu.Unlock()
     896           2 :         }
     897             : 
     898           2 :         if mem.writerUnref() {
     899           2 :                 d.mu.Lock()
     900           2 :                 d.maybeScheduleFlush()
     901           2 :                 d.mu.Unlock()
     902           2 :         }
     903           2 :         return nil
     904             : }
     905             : 
     906           2 : func (d *DB) commitWrite(b *Batch, syncWG *sync.WaitGroup, syncErr *error) (*memTable, error) {
     907           2 :         var size int64
     908           2 :         repr := b.Repr()
     909           2 : 
     910           2 :         if b.flushable != nil {
     911           2 :                 // We have a large batch. Such batches are special in that they don't get
     912           2 :                 // added to the memtable, and are instead inserted into the queue of
     913           2 :                 // memtables. The call to makeRoomForWrite with this batch will force the
     914           2 :                 // current memtable to be flushed. We want the large batch to be part of
     915           2 :                 // the same log, so we add it to the WAL here, rather than after the call
     916           2 :                 // to makeRoomForWrite().
     917           2 :                 //
     918           2 :                 // Set the sequence number since it was not set to the correct value earlier
     919           2 :                 // (see comment in newFlushableBatch()).
     920           2 :                 b.flushable.setSeqNum(b.SeqNum())
     921           2 :                 if !d.opts.DisableWAL {
     922           2 :                         var err error
     923           2 :                         size, err = d.mu.log.SyncRecord(repr, syncWG, syncErr)
     924           2 :                         if err != nil {
     925           0 :                                 panic(err)
     926             :                         }
     927             :                 }
     928             :         }
     929             : 
     930           2 :         d.mu.Lock()
     931           2 : 
     932           2 :         var err error
     933           2 :         if !b.ingestedSSTBatch {
     934           2 :                 // Batches which contain keys of kind InternalKeyKindIngestSST will
     935           2 :                 // never be applied to the memtable, so we don't need to make room for
     936           2 :                 // write. For the other cases, switch out the memtable if there was not
     937           2 :                 // enough room to store the batch.
     938           2 :                 err = d.makeRoomForWrite(b)
     939           2 :         }
     940             : 
     941           2 :         if err == nil && !d.opts.DisableWAL {
     942           2 :                 d.mu.log.bytesIn += uint64(len(repr))
     943           2 :         }
     944             : 
     945             :         // Grab a reference to the memtable while holding DB.mu. Note that for
     946             :         // non-flushable batches (b.flushable == nil) makeRoomForWrite() added a
     947             :         // reference to the memtable which will prevent it from being flushed until
     948             :         // we unreference it. This reference is dropped in DB.commitApply().
     949           2 :         mem := d.mu.mem.mutable
     950           2 : 
     951           2 :         d.mu.Unlock()
     952           2 :         if err != nil {
     953           0 :                 return nil, err
     954           0 :         }
     955             : 
     956           2 :         if d.opts.DisableWAL {
     957           2 :                 return mem, nil
     958           2 :         }
     959             : 
     960           2 :         if b.flushable == nil {
     961           2 :                 size, err = d.mu.log.SyncRecord(repr, syncWG, syncErr)
     962           2 :                 if err != nil {
     963           0 :                         panic(err)
     964             :                 }
     965             :         }
     966             : 
     967           2 :         d.logSize.Store(uint64(size))
     968           2 :         return mem, err
     969             : }
     970             : 
     971             : type iterAlloc struct {
     972             :         dbi                 Iterator
     973             :         keyBuf              []byte
     974             :         boundsBuf           [2][]byte
     975             :         prefixOrFullSeekKey []byte
     976             :         merging             mergingIter
     977             :         mlevels             [3 + numLevels]mergingIterLevel
     978             :         levels              [3 + numLevels]levelIter
     979             :         levelsPositioned    [3 + numLevels]bool
     980             : }
     981             : 
     982             : var iterAllocPool = sync.Pool{
     983           2 :         New: func() interface{} {
     984           2 :                 return &iterAlloc{}
     985           2 :         },
     986             : }
     987             : 
     988             : // snapshotIterOpts denotes snapshot-related iterator options when calling
     989             : // newIter. These are the possible cases for a snapshotIterOpts:
     990             : //   - No snapshot: All fields are zero values.
     991             : //   - Classic snapshot: Only `seqNum` is set. The latest readState will be used
     992             : //     and the specified seqNum will be used as the snapshot seqNum.
     993             : //   - EventuallyFileOnlySnapshot (EFOS) behaving as a classic snapshot. Only
     994             : //     the `seqNum` is set. The latest readState will be used
     995             : //     and the specified seqNum will be used as the snapshot seqNum.
     996             : //   - EFOS in file-only state: Only `seqNum` and `vers` are set. All the
     997             : //     relevant SSTs are referenced by the *version.
     998             : type snapshotIterOpts struct {
     999             :         seqNum uint64
    1000             :         vers   *version
    1001             : }
    1002             : 
    1003             : type batchIterOpts struct {
    1004             :         batchOnly bool
    1005             : }
    1006             : type newIterOpts struct {
    1007             :         snapshot snapshotIterOpts
    1008             :         batch    batchIterOpts
    1009             : }
    1010             : 
    1011             : // newIter constructs a new iterator, merging in batch iterators as an extra
    1012             : // level.
    1013             : func (d *DB) newIter(
    1014             :         ctx context.Context, batch *Batch, internalOpts newIterOpts, o *IterOptions,
    1015           2 : ) *Iterator {
    1016           2 :         if internalOpts.batch.batchOnly {
    1017           1 :                 if batch == nil {
    1018           0 :                         panic("batchOnly is true, but batch is nil")
    1019             :                 }
    1020           1 :                 if internalOpts.snapshot.vers != nil {
    1021           0 :                         panic("batchOnly is true, but snapshotIterOpts is initialized")
    1022             :                 }
    1023             :         }
    1024           2 :         if err := d.closed.Load(); err != nil {
    1025           1 :                 panic(err)
    1026             :         }
    1027           2 :         seqNum := internalOpts.snapshot.seqNum
    1028           2 :         if o.rangeKeys() {
    1029           2 :                 if d.FormatMajorVersion() < FormatRangeKeys {
    1030           1 :                         panic(fmt.Sprintf(
    1031           1 :                                 "pebble: range keys require at least format major version %d (current: %d)",
    1032           1 :                                 FormatRangeKeys, d.FormatMajorVersion(),
    1033           1 :                         ))
    1034             :                 }
    1035             :         }
    1036           2 :         if o != nil && o.RangeKeyMasking.Suffix != nil && o.KeyTypes != IterKeyTypePointsAndRanges {
    1037           0 :                 panic("pebble: range key masking requires IterKeyTypePointsAndRanges")
    1038             :         }
    1039           2 :         if (batch != nil || seqNum != 0) && (o != nil && o.OnlyReadGuaranteedDurable) {
    1040           1 :                 // We could add support for OnlyReadGuaranteedDurable on snapshots if
    1041           1 :                 // there was a need: this would require checking that the sequence number
    1042           1 :                 // of the snapshot has been flushed, by comparing with
    1043           1 :                 // DB.mem.queue[0].logSeqNum.
    1044           1 :                 panic("OnlyReadGuaranteedDurable is not supported for batches or snapshots")
    1045             :         }
    1046           2 :         var readState *readState
    1047           2 :         var newIters tableNewIters
    1048           2 :         var newIterRangeKey keyspan.TableNewSpanIter
    1049           2 :         if !internalOpts.batch.batchOnly {
    1050           2 :                 // Grab and reference the current readState. This prevents the underlying
    1051           2 :                 // files in the associated version from being deleted if there is a current
    1052           2 :                 // compaction. The readState is unref'd by Iterator.Close().
    1053           2 :                 if internalOpts.snapshot.vers == nil {
    1054           2 :                         // NB: loadReadState() calls readState.ref().
    1055           2 :                         readState = d.loadReadState()
    1056           2 :                 } else {
    1057           2 :                         // vers != nil
    1058           2 :                         internalOpts.snapshot.vers.Ref()
    1059           2 :                 }
    1060             : 
    1061             :                 // Determine the seqnum to read at after grabbing the read state (current and
    1062             :                 // memtables) above.
    1063           2 :                 if seqNum == 0 {
    1064           2 :                         seqNum = d.mu.versions.visibleSeqNum.Load()
    1065           2 :                 }
    1066           2 :                 newIters = d.newIters
    1067           2 :                 newIterRangeKey = d.tableNewRangeKeyIter
    1068             :         }
    1069             : 
    1070             :         // Bundle various structures under a single umbrella in order to allocate
    1071             :         // them together.
    1072           2 :         buf := iterAllocPool.Get().(*iterAlloc)
    1073           2 :         dbi := &buf.dbi
    1074           2 :         *dbi = Iterator{
    1075           2 :                 ctx:                 ctx,
    1076           2 :                 alloc:               buf,
    1077           2 :                 merge:               d.merge,
    1078           2 :                 comparer:            *d.opts.Comparer,
    1079           2 :                 readState:           readState,
    1080           2 :                 version:             internalOpts.snapshot.vers,
    1081           2 :                 keyBuf:              buf.keyBuf,
    1082           2 :                 prefixOrFullSeekKey: buf.prefixOrFullSeekKey,
    1083           2 :                 boundsBuf:           buf.boundsBuf,
    1084           2 :                 batch:               batch,
    1085           2 :                 newIters:            newIters,
    1086           2 :                 newIterRangeKey:     newIterRangeKey,
    1087           2 :                 seqNum:              seqNum,
    1088           2 :                 batchOnlyIter:       internalOpts.batch.batchOnly,
    1089           2 :         }
    1090           2 :         if o != nil {
    1091           2 :                 dbi.opts = *o
    1092           2 :                 dbi.processBounds(o.LowerBound, o.UpperBound)
    1093           2 :         }
    1094           2 :         dbi.opts.logger = d.opts.Logger
    1095           2 :         if d.opts.private.disableLazyCombinedIteration {
    1096           1 :                 dbi.opts.disableLazyCombinedIteration = true
    1097           1 :         }
    1098           2 :         if batch != nil {
    1099           2 :                 dbi.batchSeqNum = dbi.batch.nextSeqNum()
    1100           2 :         }
    1101           2 :         return finishInitializingIter(ctx, buf)
    1102             : }
    1103             : 
    1104             : // finishInitializingIter is a helper for doing the non-trivial initialization
    1105             : // of an Iterator. It's invoked to perform the initial initialization of an
    1106             : // Iterator during NewIter or Clone, and to perform reinitialization due to a
    1107             : // change in IterOptions by a call to Iterator.SetOptions.
    1108           2 : func finishInitializingIter(ctx context.Context, buf *iterAlloc) *Iterator {
    1109           2 :         // Short-hand.
    1110           2 :         dbi := &buf.dbi
    1111           2 :         var memtables flushableList
    1112           2 :         if dbi.readState != nil {
    1113           2 :                 memtables = dbi.readState.memtables
    1114           2 :         }
    1115           2 :         if dbi.opts.OnlyReadGuaranteedDurable {
    1116           1 :                 memtables = nil
    1117           2 :         } else {
    1118           2 :                 // We only need to read from memtables which contain sequence numbers older
    1119           2 :                 // than seqNum. Trim off newer memtables.
    1120           2 :                 for i := len(memtables) - 1; i >= 0; i-- {
    1121           2 :                         if logSeqNum := memtables[i].logSeqNum; logSeqNum < dbi.seqNum {
    1122           2 :                                 break
    1123             :                         }
    1124           2 :                         memtables = memtables[:i]
    1125             :                 }
    1126             :         }
    1127             : 
    1128           2 :         if dbi.opts.pointKeys() {
    1129           2 :                 // Construct the point iterator, initializing dbi.pointIter to point to
    1130           2 :                 // dbi.merging. If this is called during a SetOptions call and this
    1131           2 :                 // Iterator has already initialized dbi.merging, constructPointIter is a
    1132           2 :                 // noop and an initialized pointIter already exists in dbi.pointIter.
    1133           2 :                 dbi.constructPointIter(ctx, memtables, buf)
    1134           2 :                 dbi.iter = dbi.pointIter
    1135           2 :         } else {
    1136           2 :                 dbi.iter = emptyIter
    1137           2 :         }
    1138             : 
    1139           2 :         if dbi.opts.rangeKeys() {
    1140           2 :                 dbi.rangeKeyMasking.init(dbi, dbi.comparer.Compare, dbi.comparer.Split)
    1141           2 : 
    1142           2 :                 // When iterating over both point and range keys, don't create the
    1143           2 :                 // range-key iterator stack immediately if we can avoid it. This
    1144           2 :                 // optimization takes advantage of the expected sparseness of range
    1145           2 :                 // keys, and configures the point-key iterator to dynamically switch to
    1146           2 :                 // combined iteration when it observes a file containing range keys.
    1147           2 :                 //
    1148           2 :                 // Lazy combined iteration is not possible if a batch or a memtable
    1149           2 :                 // contains any range keys.
    1150           2 :                 useLazyCombinedIteration := dbi.rangeKey == nil &&
    1151           2 :                         dbi.opts.KeyTypes == IterKeyTypePointsAndRanges &&
    1152           2 :                         (dbi.batch == nil || dbi.batch.countRangeKeys == 0) &&
    1153           2 :                         !dbi.opts.disableLazyCombinedIteration
    1154           2 :                 if useLazyCombinedIteration {
    1155           2 :                         // The user requested combined iteration, and there's no indexed
    1156           2 :                         // batch currently containing range keys that would prevent lazy
    1157           2 :                         // combined iteration. Check the memtables to see if they contain
    1158           2 :                         // any range keys.
    1159           2 :                         for i := range memtables {
    1160           2 :                                 if memtables[i].containsRangeKeys() {
    1161           2 :                                         useLazyCombinedIteration = false
    1162           2 :                                         break
    1163             :                                 }
    1164             :                         }
    1165             :                 }
    1166             : 
    1167           2 :                 if useLazyCombinedIteration {
    1168           2 :                         dbi.lazyCombinedIter = lazyCombinedIter{
    1169           2 :                                 parent:    dbi,
    1170           2 :                                 pointIter: dbi.pointIter,
    1171           2 :                                 combinedIterState: combinedIterState{
    1172           2 :                                         initialized: false,
    1173           2 :                                 },
    1174           2 :                         }
    1175           2 :                         dbi.iter = &dbi.lazyCombinedIter
    1176           2 :                         dbi.iter = invalidating.MaybeWrapIfInvariants(dbi.iter)
    1177           2 :                 } else {
    1178           2 :                         dbi.lazyCombinedIter.combinedIterState = combinedIterState{
    1179           2 :                                 initialized: true,
    1180           2 :                         }
    1181           2 :                         if dbi.rangeKey == nil {
    1182           2 :                                 dbi.rangeKey = iterRangeKeyStateAllocPool.Get().(*iteratorRangeKeyState)
    1183           2 :                                 dbi.rangeKey.init(dbi.comparer.Compare, dbi.comparer.Split, &dbi.opts)
    1184           2 :                                 dbi.constructRangeKeyIter()
    1185           2 :                         } else {
    1186           2 :                                 dbi.rangeKey.iterConfig.SetBounds(dbi.opts.LowerBound, dbi.opts.UpperBound)
    1187           2 :                         }
    1188             : 
    1189             :                         // Wrap the point iterator (currently dbi.iter) with an interleaving
    1190             :                         // iterator that interleaves range keys pulled from
    1191             :                         // dbi.rangeKey.rangeKeyIter.
    1192             :                         //
    1193             :                         // NB: The interleaving iterator is always reinitialized, even if
    1194             :                         // dbi already had an initialized range key iterator, in case the point
    1195             :                         // iterator changed or the range key masking suffix changed.
    1196           2 :                         dbi.rangeKey.iiter.Init(&dbi.comparer, dbi.iter, dbi.rangeKey.rangeKeyIter,
    1197           2 :                                 keyspan.InterleavingIterOpts{
    1198           2 :                                         Mask:       &dbi.rangeKeyMasking,
    1199           2 :                                         LowerBound: dbi.opts.LowerBound,
    1200           2 :                                         UpperBound: dbi.opts.UpperBound,
    1201           2 :                                 })
    1202           2 :                         dbi.iter = &dbi.rangeKey.iiter
    1203             :                 }
    1204           2 :         } else {
    1205           2 :                 // !dbi.opts.rangeKeys()
    1206           2 :                 //
    1207           2 :                 // Reset the combined iterator state. The initialized=true ensures the
    1208           2 :                 // iterator doesn't unnecessarily try to switch to combined iteration.
    1209           2 :                 dbi.lazyCombinedIter.combinedIterState = combinedIterState{initialized: true}
    1210           2 :         }
    1211           2 :         return dbi
    1212             : }
    1213             : 
    1214             : // ScanInternal scans all internal keys within the specified bounds, truncating
    1215             : // any rangedels and rangekeys to those bounds if they span past them. For use
    1216             : // when an external user needs to be aware of all internal keys that make up a
    1217             : // key range.
    1218             : //
    1219             : // Keys deleted by range deletions must not be returned or exposed by this
    1220             : // method, while the range deletion deleting that key must be exposed using
    1221             : // visitRangeDel. Keys that would be masked by range key masking (if an
    1222             : // appropriate prefix were set) should be exposed, alongside the range key
    1223             : // that would have masked it. This method also collapses all point keys into
    1224             : // one InternalKey; so only one internal key at most per user key is returned
    1225             : // to visitPointKey.
    1226             : //
    1227             : // If visitSharedFile is not nil, ScanInternal iterates in skip-shared iteration
    1228             : // mode. In this iteration mode, sstables in levels L5 and L6 are skipped, and
    1229             : // their metadatas truncated to [lower, upper) and passed into visitSharedFile.
    1230             : // ErrInvalidSkipSharedIteration is returned if visitSharedFile is not nil and an
    1231             : // sstable in L5 or L6 is found that is not in shared storage according to
    1232             : // provider.IsShared, or an sstable in those levels contains a newer key than the
    1233             : // snapshot sequence number (only applicable for snapshot.ScanInternal). Examples
    1234             : // of when this could happen could be if Pebble started writing sstables before a
    1235             : // creator ID was set (as creator IDs are necessary to enable shared storage)
    1236             : // resulting in some lower level SSTs being on non-shared storage. Skip-shared
    1237             : // iteration is invalid in those cases.
    1238             : func (d *DB) ScanInternal(
    1239             :         ctx context.Context,
    1240             :         categoryAndQoS sstable.CategoryAndQoS,
    1241             :         lower, upper []byte,
    1242             :         visitPointKey func(key *InternalKey, value LazyValue, iterInfo IteratorLevel) error,
    1243             :         visitRangeDel func(start, end []byte, seqNum uint64) error,
    1244             :         visitRangeKey func(start, end []byte, keys []rangekey.Key) error,
    1245             :         visitSharedFile func(sst *SharedSSTMeta) error,
    1246           1 : ) error {
    1247           1 :         scanInternalOpts := &scanInternalOptions{
    1248           1 :                 CategoryAndQoS:   categoryAndQoS,
    1249           1 :                 visitPointKey:    visitPointKey,
    1250           1 :                 visitRangeDel:    visitRangeDel,
    1251           1 :                 visitRangeKey:    visitRangeKey,
    1252           1 :                 visitSharedFile:  visitSharedFile,
    1253           1 :                 skipSharedLevels: visitSharedFile != nil,
    1254           1 :                 IterOptions: IterOptions{
    1255           1 :                         KeyTypes:   IterKeyTypePointsAndRanges,
    1256           1 :                         LowerBound: lower,
    1257           1 :                         UpperBound: upper,
    1258           1 :                 },
    1259           1 :         }
    1260           1 :         iter := d.newInternalIter(ctx, snapshotIterOpts{} /* snapshot */, scanInternalOpts)
    1261           1 :         defer iter.close()
    1262           1 :         return scanInternalImpl(ctx, lower, upper, iter, scanInternalOpts)
    1263           1 : }
    1264             : 
    1265             : // newInternalIter constructs and returns a new scanInternalIterator on this db.
    1266             : // If o.skipSharedLevels is true, levels below sharedLevelsStart are *not* added
    1267             : // to the internal iterator.
    1268             : //
    1269             : // TODO(bilal): This method has a lot of similarities with db.newIter as well as
    1270             : // finishInitializingIter. Both pairs of methods should be refactored to reduce
    1271             : // this duplication.
    1272             : func (d *DB) newInternalIter(
    1273             :         ctx context.Context, sOpts snapshotIterOpts, o *scanInternalOptions,
    1274           1 : ) *scanInternalIterator {
    1275           1 :         if err := d.closed.Load(); err != nil {
    1276           0 :                 panic(err)
    1277             :         }
    1278             :         // Grab and reference the current readState. This prevents the underlying
    1279             :         // files in the associated version from being deleted if there is a current
    1280             :         // compaction. The readState is unref'd by Iterator.Close().
    1281           1 :         var readState *readState
    1282           1 :         if sOpts.vers == nil {
    1283           1 :                 readState = d.loadReadState()
    1284           1 :         }
    1285           1 :         if sOpts.vers != nil {
    1286           1 :                 sOpts.vers.Ref()
    1287           1 :         }
    1288             : 
    1289             :         // Determine the seqnum to read at after grabbing the read state (current and
    1290             :         // memtables) above.
    1291           1 :         seqNum := sOpts.seqNum
    1292           1 :         if seqNum == 0 {
    1293           1 :                 seqNum = d.mu.versions.visibleSeqNum.Load()
    1294           1 :         }
    1295             : 
    1296             :         // Bundle various structures under a single umbrella in order to allocate
    1297             :         // them together.
    1298           1 :         buf := iterAllocPool.Get().(*iterAlloc)
    1299           1 :         dbi := &scanInternalIterator{
    1300           1 :                 ctx:             ctx,
    1301           1 :                 db:              d,
    1302           1 :                 comparer:        d.opts.Comparer,
    1303           1 :                 merge:           d.opts.Merger.Merge,
    1304           1 :                 readState:       readState,
    1305           1 :                 version:         sOpts.vers,
    1306           1 :                 alloc:           buf,
    1307           1 :                 newIters:        d.newIters,
    1308           1 :                 newIterRangeKey: d.tableNewRangeKeyIter,
    1309           1 :                 seqNum:          seqNum,
    1310           1 :                 mergingIter:     &buf.merging,
    1311           1 :         }
    1312           1 :         dbi.opts = *o
    1313           1 :         dbi.opts.logger = d.opts.Logger
    1314           1 :         if d.opts.private.disableLazyCombinedIteration {
    1315           0 :                 dbi.opts.disableLazyCombinedIteration = true
    1316           0 :         }
    1317           1 :         return finishInitializingInternalIter(buf, dbi)
    1318             : }
    1319             : 
    1320           1 : func finishInitializingInternalIter(buf *iterAlloc, i *scanInternalIterator) *scanInternalIterator {
    1321           1 :         // Short-hand.
    1322           1 :         var memtables flushableList
    1323           1 :         if i.readState != nil {
    1324           1 :                 memtables = i.readState.memtables
    1325           1 :         }
    1326             :         // We only need to read from memtables which contain sequence numbers older
    1327             :         // than seqNum. Trim off newer memtables.
    1328           1 :         for j := len(memtables) - 1; j >= 0; j-- {
    1329           1 :                 if logSeqNum := memtables[j].logSeqNum; logSeqNum < i.seqNum {
    1330           1 :                         break
    1331             :                 }
    1332           1 :                 memtables = memtables[:j]
    1333             :         }
    1334           1 :         i.initializeBoundBufs(i.opts.LowerBound, i.opts.UpperBound)
    1335           1 : 
    1336           1 :         i.constructPointIter(i.opts.CategoryAndQoS, memtables, buf)
    1337           1 : 
    1338           1 :         // For internal iterators, we skip the lazy combined iteration optimization
    1339           1 :         // entirely, and create the range key iterator stack directly.
    1340           1 :         i.rangeKey = iterRangeKeyStateAllocPool.Get().(*iteratorRangeKeyState)
    1341           1 :         i.rangeKey.init(i.comparer.Compare, i.comparer.Split, &i.opts.IterOptions)
    1342           1 :         i.constructRangeKeyIter()
    1343           1 : 
    1344           1 :         // Wrap the point iterator (currently i.iter) with an interleaving
    1345           1 :         // iterator that interleaves range keys pulled from
    1346           1 :         // i.rangeKey.rangeKeyIter.
    1347           1 :         i.rangeKey.iiter.Init(i.comparer, i.iter, i.rangeKey.rangeKeyIter,
    1348           1 :                 keyspan.InterleavingIterOpts{
    1349           1 :                         LowerBound: i.opts.LowerBound,
    1350           1 :                         UpperBound: i.opts.UpperBound,
    1351           1 :                 })
    1352           1 :         i.iter = &i.rangeKey.iiter
    1353           1 : 
    1354           1 :         return i
    1355             : }
    1356             : 
    1357             : func (i *Iterator) constructPointIter(
    1358             :         ctx context.Context, memtables flushableList, buf *iterAlloc,
    1359           2 : ) {
    1360           2 :         if i.pointIter != nil {
    1361           2 :                 // Already have one.
    1362           2 :                 return
    1363           2 :         }
    1364           2 :         internalOpts := internalIterOpts{stats: &i.stats.InternalStats}
    1365           2 :         if i.opts.RangeKeyMasking.Filter != nil {
    1366           2 :                 internalOpts.boundLimitedFilter = &i.rangeKeyMasking
    1367           2 :         }
    1368             : 
    1369             :         // Merging levels and levels from iterAlloc.
    1370           2 :         mlevels := buf.mlevels[:0]
    1371           2 :         levels := buf.levels[:0]
    1372           2 : 
    1373           2 :         // We compute the number of levels needed ahead of time and reallocate a slice if
    1374           2 :         // the array from the iterAlloc isn't large enough. Doing this allocation once
    1375           2 :         // should improve the performance.
    1376           2 :         numMergingLevels := 0
    1377           2 :         numLevelIters := 0
    1378           2 :         if i.batch != nil {
    1379           2 :                 numMergingLevels++
    1380           2 :         }
    1381             : 
    1382           2 :         var current *version
    1383           2 :         if !i.batchOnlyIter {
    1384           2 :                 numMergingLevels += len(memtables)
    1385           2 : 
    1386           2 :                 current = i.version
    1387           2 :                 if current == nil {
    1388           2 :                         current = i.readState.current
    1389           2 :                 }
    1390           2 :                 numMergingLevels += len(current.L0SublevelFiles)
    1391           2 :                 numLevelIters += len(current.L0SublevelFiles)
    1392           2 :                 for level := 1; level < len(current.Levels); level++ {
    1393           2 :                         if current.Levels[level].Empty() {
    1394           2 :                                 continue
    1395             :                         }
    1396           2 :                         numMergingLevels++
    1397           2 :                         numLevelIters++
    1398             :                 }
    1399             :         }
    1400             : 
    1401           2 :         if numMergingLevels > cap(mlevels) {
    1402           2 :                 mlevels = make([]mergingIterLevel, 0, numMergingLevels)
    1403           2 :         }
    1404           2 :         if numLevelIters > cap(levels) {
    1405           2 :                 levels = make([]levelIter, 0, numLevelIters)
    1406           2 :         }
    1407             : 
    1408             :         // Top-level is the batch, if any.
    1409           2 :         if i.batch != nil {
    1410           2 :                 if i.batch.index == nil {
    1411           0 :                         // This isn't an indexed batch. Include an error iterator so that
    1412           0 :                         // the resulting iterator correctly surfaces ErrIndexed.
    1413           0 :                         mlevels = append(mlevels, mergingIterLevel{
    1414           0 :                                 iter:         newErrorIter(ErrNotIndexed),
    1415           0 :                                 rangeDelIter: newErrorKeyspanIter(ErrNotIndexed),
    1416           0 :                         })
    1417           2 :                 } else {
    1418           2 :                         i.batch.initInternalIter(&i.opts, &i.batchPointIter)
    1419           2 :                         i.batch.initRangeDelIter(&i.opts, &i.batchRangeDelIter, i.batchSeqNum)
    1420           2 :                         // Only include the batch's rangedel iterator if it's non-empty.
    1421           2 :                         // This requires some subtle logic in the case a rangedel is later
    1422           2 :                         // written to the batch and the view of the batch is refreshed
    1423           2 :                         // during a call to SetOptions—in this case, we need to reconstruct
    1424           2 :                         // the point iterator to add the batch rangedel iterator.
    1425           2 :                         var rangeDelIter keyspan.FragmentIterator
    1426           2 :                         if i.batchRangeDelIter.Count() > 0 {
    1427           2 :                                 rangeDelIter = &i.batchRangeDelIter
    1428           2 :                         }
    1429           2 :                         mlevels = append(mlevels, mergingIterLevel{
    1430           2 :                                 iter:         &i.batchPointIter,
    1431           2 :                                 rangeDelIter: rangeDelIter,
    1432           2 :                         })
    1433             :                 }
    1434             :         }
    1435             : 
    1436           2 :         if !i.batchOnlyIter {
    1437           2 :                 // Next are the memtables.
    1438           2 :                 for j := len(memtables) - 1; j >= 0; j-- {
    1439           2 :                         mem := memtables[j]
    1440           2 :                         mlevels = append(mlevels, mergingIterLevel{
    1441           2 :                                 iter:         mem.newIter(&i.opts),
    1442           2 :                                 rangeDelIter: mem.newRangeDelIter(&i.opts),
    1443           2 :                         })
    1444           2 :                 }
    1445             : 
    1446             :                 // Next are the file levels: L0 sub-levels followed by lower levels.
    1447           2 :                 mlevelsIndex := len(mlevels)
    1448           2 :                 levelsIndex := len(levels)
    1449           2 :                 mlevels = mlevels[:numMergingLevels]
    1450           2 :                 levels = levels[:numLevelIters]
    1451           2 :                 i.opts.snapshotForHideObsoletePoints = buf.dbi.seqNum
    1452           2 :                 addLevelIterForFiles := func(files manifest.LevelIterator, level manifest.Level) {
    1453           2 :                         li := &levels[levelsIndex]
    1454           2 : 
    1455           2 :                         li.init(ctx, i.opts, &i.comparer, i.newIters, files, level, internalOpts)
    1456           2 :                         li.initRangeDel(&mlevels[mlevelsIndex].rangeDelIter)
    1457           2 :                         li.initBoundaryContext(&mlevels[mlevelsIndex].levelIterBoundaryContext)
    1458           2 :                         li.initCombinedIterState(&i.lazyCombinedIter.combinedIterState)
    1459           2 :                         mlevels[mlevelsIndex].levelIter = li
    1460           2 :                         mlevels[mlevelsIndex].iter = invalidating.MaybeWrapIfInvariants(li)
    1461           2 : 
    1462           2 :                         levelsIndex++
    1463           2 :                         mlevelsIndex++
    1464           2 :                 }
    1465             : 
    1466             :                 // Add level iterators for the L0 sublevels, iterating from newest to
    1467             :                 // oldest.
    1468           2 :                 for i := len(current.L0SublevelFiles) - 1; i >= 0; i-- {
    1469           2 :                         addLevelIterForFiles(current.L0SublevelFiles[i].Iter(), manifest.L0Sublevel(i))
    1470           2 :                 }
    1471             : 
    1472             :                 // Add level iterators for the non-empty non-L0 levels.
    1473           2 :                 for level := 1; level < len(current.Levels); level++ {
    1474           2 :                         if current.Levels[level].Empty() {
    1475           2 :                                 continue
    1476             :                         }
    1477           2 :                         addLevelIterForFiles(current.Levels[level].Iter(), manifest.Level(level))
    1478             :                 }
    1479             :         }
    1480           2 :         buf.merging.init(&i.opts, &i.stats.InternalStats, i.comparer.Compare, i.comparer.Split, mlevels...)
    1481           2 :         if len(mlevels) <= cap(buf.levelsPositioned) {
    1482           2 :                 buf.merging.levelsPositioned = buf.levelsPositioned[:len(mlevels)]
    1483           2 :         }
    1484           2 :         buf.merging.snapshot = i.seqNum
    1485           2 :         buf.merging.batchSnapshot = i.batchSeqNum
    1486           2 :         buf.merging.combinedIterState = &i.lazyCombinedIter.combinedIterState
    1487           2 :         i.pointIter = invalidating.MaybeWrapIfInvariants(&buf.merging)
    1488           2 :         i.merging = &buf.merging
    1489             : }
    1490             : 
    1491             : // NewBatch returns a new empty write-only batch. Any reads on the batch will
    1492             : // return an error. If the batch is committed it will be applied to the DB.
    1493           2 : func (d *DB) NewBatch() *Batch {
    1494           2 :         return newBatch(d)
    1495           2 : }
    1496             : 
    1497             : // NewBatchWithSize is mostly identical to NewBatch, but it will allocate the
    1498             : // the specified memory space for the internal slice in advance.
    1499           0 : func (d *DB) NewBatchWithSize(size int) *Batch {
    1500           0 :         return newBatchWithSize(d, size)
    1501           0 : }
    1502             : 
    1503             : // NewIndexedBatch returns a new empty read-write batch. Any reads on the batch
    1504             : // will read from both the batch and the DB. If the batch is committed it will
    1505             : // be applied to the DB. An indexed batch is slower that a non-indexed batch
    1506             : // for insert operations. If you do not need to perform reads on the batch, use
    1507             : // NewBatch instead.
    1508           2 : func (d *DB) NewIndexedBatch() *Batch {
    1509           2 :         return newIndexedBatch(d, d.opts.Comparer)
    1510           2 : }
    1511             : 
    1512             : // NewIndexedBatchWithSize is mostly identical to NewIndexedBatch, but it will
    1513             : // allocate the the specified memory space for the internal slice in advance.
    1514           0 : func (d *DB) NewIndexedBatchWithSize(size int) *Batch {
    1515           0 :         return newIndexedBatchWithSize(d, d.opts.Comparer, size)
    1516           0 : }
    1517             : 
    1518             : // NewIter returns an iterator that is unpositioned (Iterator.Valid() will
    1519             : // return false). The iterator can be positioned via a call to SeekGE, SeekLT,
    1520             : // First or Last. The iterator provides a point-in-time view of the current DB
    1521             : // state. This view is maintained by preventing file deletions and preventing
    1522             : // memtables referenced by the iterator from being deleted. Using an iterator
    1523             : // to maintain a long-lived point-in-time view of the DB state can lead to an
    1524             : // apparent memory and disk usage leak. Use snapshots (see NewSnapshot) for
    1525             : // point-in-time snapshots which avoids these problems.
    1526           2 : func (d *DB) NewIter(o *IterOptions) (*Iterator, error) {
    1527           2 :         return d.NewIterWithContext(context.Background(), o)
    1528           2 : }
    1529             : 
    1530             : // NewIterWithContext is like NewIter, and additionally accepts a context for
    1531             : // tracing.
    1532           2 : func (d *DB) NewIterWithContext(ctx context.Context, o *IterOptions) (*Iterator, error) {
    1533           2 :         return d.newIter(ctx, nil /* batch */, newIterOpts{}, o), nil
    1534           2 : }
    1535             : 
    1536             : // NewSnapshot returns a point-in-time view of the current DB state. Iterators
    1537             : // created with this handle will all observe a stable snapshot of the current
    1538             : // DB state. The caller must call Snapshot.Close() when the snapshot is no
    1539             : // longer needed. Snapshots are not persisted across DB restarts (close ->
    1540             : // open). Unlike the implicit snapshot maintained by an iterator, a snapshot
    1541             : // will not prevent memtables from being released or sstables from being
    1542             : // deleted. Instead, a snapshot prevents deletion of sequence numbers
    1543             : // referenced by the snapshot.
    1544           2 : func (d *DB) NewSnapshot() *Snapshot {
    1545           2 :         if err := d.closed.Load(); err != nil {
    1546           1 :                 panic(err)
    1547             :         }
    1548             : 
    1549           2 :         d.mu.Lock()
    1550           2 :         s := &Snapshot{
    1551           2 :                 db:     d,
    1552           2 :                 seqNum: d.mu.versions.visibleSeqNum.Load(),
    1553           2 :         }
    1554           2 :         d.mu.snapshots.pushBack(s)
    1555           2 :         d.mu.Unlock()
    1556           2 :         return s
    1557             : }
    1558             : 
    1559             : // NewEventuallyFileOnlySnapshot returns a point-in-time view of the current DB
    1560             : // state, similar to NewSnapshot, but with consistency constrained to the
    1561             : // provided set of key ranges. See the comment at EventuallyFileOnlySnapshot for
    1562             : // its semantics.
    1563           2 : func (d *DB) NewEventuallyFileOnlySnapshot(keyRanges []KeyRange) *EventuallyFileOnlySnapshot {
    1564           2 :         if err := d.closed.Load(); err != nil {
    1565           0 :                 panic(err)
    1566             :         }
    1567             : 
    1568           2 :         internalKeyRanges := make([]internalKeyRange, len(keyRanges))
    1569           2 :         for i := range keyRanges {
    1570           2 :                 if i > 0 && d.cmp(keyRanges[i-1].End, keyRanges[i].Start) > 0 {
    1571           0 :                         panic("pebble: key ranges for eventually-file-only-snapshot not in order")
    1572             :                 }
    1573           2 :                 internalKeyRanges[i] = internalKeyRange{
    1574           2 :                         smallest: base.MakeInternalKey(keyRanges[i].Start, InternalKeySeqNumMax, InternalKeyKindMax),
    1575           2 :                         largest:  base.MakeExclusiveSentinelKey(InternalKeyKindRangeDelete, keyRanges[i].End),
    1576           2 :                 }
    1577             :         }
    1578             : 
    1579           2 :         return d.makeEventuallyFileOnlySnapshot(keyRanges, internalKeyRanges)
    1580             : }
    1581             : 
    1582             : // Close closes the DB.
    1583             : //
    1584             : // It is not safe to close a DB until all outstanding iterators are closed
    1585             : // or to call Close concurrently with any other DB method. It is not valid
    1586             : // to call any of a DB's methods after the DB has been closed.
    1587           2 : func (d *DB) Close() error {
    1588           2 :         // Lock the commit pipeline for the duration of Close. This prevents a race
    1589           2 :         // with makeRoomForWrite. Rotating the WAL in makeRoomForWrite requires
    1590           2 :         // dropping d.mu several times for I/O. If Close only holds d.mu, an
    1591           2 :         // in-progress WAL rotation may re-acquire d.mu only once the database is
    1592           2 :         // closed.
    1593           2 :         //
    1594           2 :         // Additionally, locking the commit pipeline makes it more likely that
    1595           2 :         // (illegal) concurrent writes will observe d.closed.Load() != nil, creating
    1596           2 :         // more understable panics if the database is improperly used concurrently
    1597           2 :         // during Close.
    1598           2 :         d.commit.mu.Lock()
    1599           2 :         defer d.commit.mu.Unlock()
    1600           2 :         d.mu.Lock()
    1601           2 :         defer d.mu.Unlock()
    1602           2 :         if err := d.closed.Load(); err != nil {
    1603           1 :                 panic(err)
    1604             :         }
    1605             : 
    1606             :         // Clear the finalizer that is used to check that an unreferenced DB has been
    1607             :         // closed. We're closing the DB here, so the check performed by that
    1608             :         // finalizer isn't necessary.
    1609             :         //
    1610             :         // Note: this is a no-op if invariants are disabled or race is enabled.
    1611           2 :         invariants.SetFinalizer(d.closed, nil)
    1612           2 : 
    1613           2 :         d.closed.Store(errors.WithStack(ErrClosed))
    1614           2 :         close(d.closedCh)
    1615           2 : 
    1616           2 :         defer d.opts.Cache.Unref()
    1617           2 : 
    1618           2 :         for d.mu.compact.compactingCount > 0 || d.mu.compact.flushing {
    1619           2 :                 d.mu.compact.cond.Wait()
    1620           2 :         }
    1621           2 :         for d.mu.tableStats.loading {
    1622           2 :                 d.mu.tableStats.cond.Wait()
    1623           2 :         }
    1624           2 :         for d.mu.tableValidation.validating {
    1625           2 :                 d.mu.tableValidation.cond.Wait()
    1626           2 :         }
    1627             : 
    1628           2 :         var err error
    1629           2 :         if n := len(d.mu.compact.inProgress); n > 0 {
    1630           1 :                 err = errors.Errorf("pebble: %d unexpected in-progress compactions", errors.Safe(n))
    1631           1 :         }
    1632           2 :         err = firstError(err, d.mu.formatVers.marker.Close())
    1633           2 :         err = firstError(err, d.tableCache.close())
    1634           2 :         if !d.opts.ReadOnly {
    1635           2 :                 err = firstError(err, d.mu.log.Close())
    1636           2 :         } else if d.mu.log.LogWriter != nil {
    1637           0 :                 panic("pebble: log-writer should be nil in read-only mode")
    1638             :         }
    1639           2 :         err = firstError(err, d.fileLock.Close())
    1640           2 : 
    1641           2 :         // Note that versionSet.close() only closes the MANIFEST. The versions list
    1642           2 :         // is still valid for the checks below.
    1643           2 :         err = firstError(err, d.mu.versions.close())
    1644           2 : 
    1645           2 :         err = firstError(err, d.dataDir.Close())
    1646           2 :         if d.dataDir != d.walDir {
    1647           2 :                 err = firstError(err, d.walDir.Close())
    1648           2 :         }
    1649             : 
    1650           2 :         d.readState.val.unrefLocked()
    1651           2 : 
    1652           2 :         current := d.mu.versions.currentVersion()
    1653           2 :         for v := d.mu.versions.versions.Front(); true; v = v.Next() {
    1654           2 :                 refs := v.Refs()
    1655           2 :                 if v == current {
    1656           2 :                         if refs != 1 {
    1657           1 :                                 err = firstError(err, errors.Errorf("leaked iterators: current\n%s", v))
    1658           1 :                         }
    1659           2 :                         break
    1660             :                 }
    1661           0 :                 if refs != 0 {
    1662           0 :                         err = firstError(err, errors.Errorf("leaked iterators:\n%s", v))
    1663           0 :                 }
    1664             :         }
    1665             : 
    1666           2 :         for _, mem := range d.mu.mem.queue {
    1667           2 :                 // Usually, we'd want to delete the files returned by readerUnref. But
    1668           2 :                 // in this case, even if we're unreferencing the flushables, the
    1669           2 :                 // flushables aren't obsolete. They will be reconstructed during WAL
    1670           2 :                 // replay.
    1671           2 :                 mem.readerUnrefLocked(false)
    1672           2 :         }
    1673             :         // If there's an unused, recycled memtable, we need to release its memory.
    1674           2 :         if obsoleteMemTable := d.memTableRecycle.Swap(nil); obsoleteMemTable != nil {
    1675           2 :                 d.freeMemTable(obsoleteMemTable)
    1676           2 :         }
    1677           2 :         if reserved := d.memTableReserved.Load(); reserved != 0 {
    1678           1 :                 err = firstError(err, errors.Errorf("leaked memtable reservation: %d", errors.Safe(reserved)))
    1679           1 :         }
    1680             : 
    1681             :         // Since we called d.readState.val.unrefLocked() above, we are expected to
    1682             :         // manually schedule deletion of obsolete files.
    1683           2 :         if len(d.mu.versions.obsoleteTables) > 0 {
    1684           2 :                 d.deleteObsoleteFiles(d.mu.nextJobID)
    1685           2 :         }
    1686             : 
    1687           2 :         d.mu.Unlock()
    1688           2 :         d.compactionSchedulers.Wait()
    1689           2 : 
    1690           2 :         // Wait for all cleaning jobs to finish.
    1691           2 :         d.cleanupManager.Close()
    1692           2 : 
    1693           2 :         // Sanity check metrics.
    1694           2 :         if invariants.Enabled {
    1695           2 :                 m := d.Metrics()
    1696           2 :                 if m.Compact.NumInProgress > 0 || m.Compact.InProgressBytes > 0 {
    1697           0 :                         d.mu.Lock()
    1698           0 :                         panic(fmt.Sprintf("invalid metrics on close:\n%s", m))
    1699             :                 }
    1700             :         }
    1701             : 
    1702           2 :         d.mu.Lock()
    1703           2 : 
    1704           2 :         // As a sanity check, ensure that there are no zombie tables. A non-zero count
    1705           2 :         // hints at a reference count leak.
    1706           2 :         if ztbls := len(d.mu.versions.zombieTables); ztbls > 0 {
    1707           0 :                 err = firstError(err, errors.Errorf("non-zero zombie file count: %d", ztbls))
    1708           0 :         }
    1709             : 
    1710           2 :         err = firstError(err, d.objProvider.Close())
    1711           2 : 
    1712           2 :         // If the options include a closer to 'close' the filesystem, close it.
    1713           2 :         if d.opts.private.fsCloser != nil {
    1714           2 :                 d.opts.private.fsCloser.Close()
    1715           2 :         }
    1716             : 
    1717             :         // Return an error if the user failed to close all open snapshots.
    1718           2 :         if v := d.mu.snapshots.count(); v > 0 {
    1719           1 :                 err = firstError(err, errors.Errorf("leaked snapshots: %d open snapshots on DB %p", v, d))
    1720           1 :         }
    1721             : 
    1722           2 :         return err
    1723             : }
    1724             : 
    1725             : // Compact the specified range of keys in the database.
    1726           2 : func (d *DB) Compact(start, end []byte, parallelize bool) error {
    1727           2 :         if err := d.closed.Load(); err != nil {
    1728           1 :                 panic(err)
    1729             :         }
    1730           2 :         if d.opts.ReadOnly {
    1731           1 :                 return ErrReadOnly
    1732           1 :         }
    1733           2 :         if d.cmp(start, end) >= 0 {
    1734           2 :                 return errors.Errorf("Compact start %s is not less than end %s",
    1735           2 :                         d.opts.Comparer.FormatKey(start), d.opts.Comparer.FormatKey(end))
    1736           2 :         }
    1737           2 :         iStart := base.MakeInternalKey(start, InternalKeySeqNumMax, InternalKeyKindMax)
    1738           2 :         iEnd := base.MakeInternalKey(end, 0, 0)
    1739           2 :         m := (&fileMetadata{}).ExtendPointKeyBounds(d.cmp, iStart, iEnd)
    1740           2 :         meta := []*fileMetadata{m}
    1741           2 : 
    1742           2 :         d.mu.Lock()
    1743           2 :         maxLevelWithFiles := 1
    1744           2 :         cur := d.mu.versions.currentVersion()
    1745           2 :         for level := 0; level < numLevels; level++ {
    1746           2 :                 overlaps := cur.Overlaps(level, d.cmp, start, end, iEnd.IsExclusiveSentinel())
    1747           2 :                 if !overlaps.Empty() {
    1748           2 :                         maxLevelWithFiles = level + 1
    1749           2 :                 }
    1750             :         }
    1751             : 
    1752           2 :         keyRanges := make([]internalKeyRange, len(meta))
    1753           2 :         for i := range meta {
    1754           2 :                 keyRanges[i] = internalKeyRange{smallest: m.Smallest, largest: m.Largest}
    1755           2 :         }
    1756             :         // Determine if any memtable overlaps with the compaction range. We wait for
    1757             :         // any such overlap to flush (initiating a flush if necessary).
    1758           2 :         mem, err := func() (*flushableEntry, error) {
    1759           2 :                 // Check to see if any files overlap with any of the memtables. The queue
    1760           2 :                 // is ordered from oldest to newest with the mutable memtable being the
    1761           2 :                 // last element in the slice. We want to wait for the newest table that
    1762           2 :                 // overlaps.
    1763           2 :                 for i := len(d.mu.mem.queue) - 1; i >= 0; i-- {
    1764           2 :                         mem := d.mu.mem.queue[i]
    1765           2 :                         if ingestMemtableOverlaps(d.cmp, mem, keyRanges) {
    1766           2 :                                 var err error
    1767           2 :                                 if mem.flushable == d.mu.mem.mutable {
    1768           2 :                                         // We have to hold both commitPipeline.mu and DB.mu when calling
    1769           2 :                                         // makeRoomForWrite(). Lock order requirements elsewhere force us to
    1770           2 :                                         // unlock DB.mu in order to grab commitPipeline.mu first.
    1771           2 :                                         d.mu.Unlock()
    1772           2 :                                         d.commit.mu.Lock()
    1773           2 :                                         d.mu.Lock()
    1774           2 :                                         defer d.commit.mu.Unlock()
    1775           2 :                                         if mem.flushable == d.mu.mem.mutable {
    1776           2 :                                                 // Only flush if the active memtable is unchanged.
    1777           2 :                                                 err = d.makeRoomForWrite(nil)
    1778           2 :                                         }
    1779             :                                 }
    1780           2 :                                 mem.flushForced = true
    1781           2 :                                 d.maybeScheduleFlush()
    1782           2 :                                 return mem, err
    1783             :                         }
    1784             :                 }
    1785           2 :                 return nil, nil
    1786             :         }()
    1787             : 
    1788           2 :         d.mu.Unlock()
    1789           2 : 
    1790           2 :         if err != nil {
    1791           0 :                 return err
    1792           0 :         }
    1793           2 :         if mem != nil {
    1794           2 :                 <-mem.flushed
    1795           2 :         }
    1796             : 
    1797           2 :         for level := 0; level < maxLevelWithFiles; {
    1798           2 :                 for {
    1799           2 :                         if err := d.manualCompact(
    1800           2 :                                 iStart.UserKey, iEnd.UserKey, level, parallelize); err != nil {
    1801           1 :                                 if errors.Is(err, ErrCancelledCompaction) {
    1802           1 :                                         continue
    1803             :                                 }
    1804           1 :                                 return err
    1805             :                         }
    1806           2 :                         break
    1807             :                 }
    1808           2 :                 level++
    1809           2 :                 if level == numLevels-1 {
    1810           2 :                         // A manual compaction of the bottommost level occurred.
    1811           2 :                         // There is no next level to try and compact.
    1812           2 :                         break
    1813             :                 }
    1814             :         }
    1815           2 :         return nil
    1816             : }
    1817             : 
    1818           2 : func (d *DB) manualCompact(start, end []byte, level int, parallelize bool) error {
    1819           2 :         d.mu.Lock()
    1820           2 :         curr := d.mu.versions.currentVersion()
    1821           2 :         files := curr.Overlaps(level, d.cmp, start, end, false)
    1822           2 :         if files.Empty() {
    1823           2 :                 d.mu.Unlock()
    1824           2 :                 return nil
    1825           2 :         }
    1826             : 
    1827           2 :         var compactions []*manualCompaction
    1828           2 :         if parallelize {
    1829           2 :                 compactions = append(compactions, d.splitManualCompaction(start, end, level)...)
    1830           2 :         } else {
    1831           2 :                 compactions = append(compactions, &manualCompaction{
    1832           2 :                         level: level,
    1833           2 :                         done:  make(chan error, 1),
    1834           2 :                         start: start,
    1835           2 :                         end:   end,
    1836           2 :                 })
    1837           2 :         }
    1838           2 :         d.mu.compact.manual = append(d.mu.compact.manual, compactions...)
    1839           2 :         d.maybeScheduleCompaction()
    1840           2 :         d.mu.Unlock()
    1841           2 : 
    1842           2 :         // Each of the channels is guaranteed to be eventually sent to once. After a
    1843           2 :         // compaction is possibly picked in d.maybeScheduleCompaction(), either the
    1844           2 :         // compaction is dropped, executed after being scheduled, or retried later.
    1845           2 :         // Assuming eventual progress when a compaction is retried, all outcomes send
    1846           2 :         // a value to the done channel. Since the channels are buffered, it is not
    1847           2 :         // necessary to read from each channel, and so we can exit early in the event
    1848           2 :         // of an error.
    1849           2 :         for _, compaction := range compactions {
    1850           2 :                 if err := <-compaction.done; err != nil {
    1851           1 :                         return err
    1852           1 :                 }
    1853             :         }
    1854           2 :         return nil
    1855             : }
    1856             : 
    1857             : // splitManualCompaction splits a manual compaction over [start,end] on level
    1858             : // such that the resulting compactions have no key overlap.
    1859             : func (d *DB) splitManualCompaction(
    1860             :         start, end []byte, level int,
    1861           2 : ) (splitCompactions []*manualCompaction) {
    1862           2 :         curr := d.mu.versions.currentVersion()
    1863           2 :         endLevel := level + 1
    1864           2 :         baseLevel := d.mu.versions.picker.getBaseLevel()
    1865           2 :         if level == 0 {
    1866           2 :                 endLevel = baseLevel
    1867           2 :         }
    1868           2 :         keyRanges := calculateInuseKeyRanges(curr, d.cmp, level, endLevel, start, end)
    1869           2 :         for _, keyRange := range keyRanges {
    1870           2 :                 splitCompactions = append(splitCompactions, &manualCompaction{
    1871           2 :                         level: level,
    1872           2 :                         done:  make(chan error, 1),
    1873           2 :                         start: keyRange.Start,
    1874           2 :                         end:   keyRange.End,
    1875           2 :                         split: true,
    1876           2 :                 })
    1877           2 :         }
    1878           2 :         return splitCompactions
    1879             : }
    1880             : 
    1881             : // DownloadSpan is a key range passed to the Download method.
    1882             : type DownloadSpan struct {
    1883             :         StartKey []byte
    1884             :         // EndKey is exclusive.
    1885             :         EndKey []byte
    1886             : }
    1887             : 
    1888             : // Download ensures that the LSM does not use any external sstables for the
    1889             : // given key ranges. It does so by performing appropriate compactions so that
    1890             : // all external data becomes available locally.
    1891             : //
    1892             : // Note that calling this method does not imply that all other compactions stop;
    1893             : // it simply informs Pebble of a list of spans for which external data should be
    1894             : // downloaded with high priority.
    1895             : //
    1896             : // The method returns once no external sstasbles overlap the given spans, the
    1897             : // context is canceled, or an error is hit.
    1898             : //
    1899             : // TODO(radu): consider passing a priority/impact knob to express how important
    1900             : // the download is (versus live traffic performance, LSM health).
    1901           0 : func (d *DB) Download(ctx context.Context, spans []DownloadSpan) error {
    1902           0 :         return errors.Errorf("not implemented")
    1903           0 : }
    1904             : 
    1905             : // Flush the memtable to stable storage.
    1906           2 : func (d *DB) Flush() error {
    1907           2 :         flushDone, err := d.AsyncFlush()
    1908           2 :         if err != nil {
    1909           1 :                 return err
    1910           1 :         }
    1911           2 :         <-flushDone
    1912           2 :         return nil
    1913             : }
    1914             : 
    1915             : // AsyncFlush asynchronously flushes the memtable to stable storage.
    1916             : //
    1917             : // If no error is returned, the caller can receive from the returned channel in
    1918             : // order to wait for the flush to complete.
    1919           2 : func (d *DB) AsyncFlush() (<-chan struct{}, error) {
    1920           2 :         if err := d.closed.Load(); err != nil {
    1921           1 :                 panic(err)
    1922             :         }
    1923           2 :         if d.opts.ReadOnly {
    1924           1 :                 return nil, ErrReadOnly
    1925           1 :         }
    1926             : 
    1927           2 :         d.commit.mu.Lock()
    1928           2 :         defer d.commit.mu.Unlock()
    1929           2 :         d.mu.Lock()
    1930           2 :         defer d.mu.Unlock()
    1931           2 :         flushed := d.mu.mem.queue[len(d.mu.mem.queue)-1].flushed
    1932           2 :         err := d.makeRoomForWrite(nil)
    1933           2 :         if err != nil {
    1934           0 :                 return nil, err
    1935           0 :         }
    1936           2 :         return flushed, nil
    1937             : }
    1938             : 
    1939             : // Metrics returns metrics about the database.
    1940           2 : func (d *DB) Metrics() *Metrics {
    1941           2 :         metrics := &Metrics{}
    1942           2 :         recycledLogsCount, recycledLogSize := d.logRecycler.stats()
    1943           2 : 
    1944           2 :         d.mu.Lock()
    1945           2 :         vers := d.mu.versions.currentVersion()
    1946           2 :         *metrics = d.mu.versions.metrics
    1947           2 :         metrics.Compact.EstimatedDebt = d.mu.versions.picker.estimatedCompactionDebt(0)
    1948           2 :         metrics.Compact.InProgressBytes = d.mu.versions.atomicInProgressBytes.Load()
    1949           2 :         metrics.Compact.NumInProgress = int64(d.mu.compact.compactingCount)
    1950           2 :         metrics.Compact.MarkedFiles = vers.Stats.MarkedForCompaction
    1951           2 :         metrics.Compact.Duration = d.mu.compact.duration
    1952           2 :         for c := range d.mu.compact.inProgress {
    1953           1 :                 if c.kind != compactionKindFlush {
    1954           1 :                         metrics.Compact.Duration += d.timeNow().Sub(c.beganAt)
    1955           1 :                 }
    1956             :         }
    1957             : 
    1958           2 :         for _, m := range d.mu.mem.queue {
    1959           2 :                 metrics.MemTable.Size += m.totalBytes()
    1960           2 :         }
    1961           2 :         metrics.Snapshots.Count = d.mu.snapshots.count()
    1962           2 :         if metrics.Snapshots.Count > 0 {
    1963           1 :                 metrics.Snapshots.EarliestSeqNum = d.mu.snapshots.earliest()
    1964           1 :         }
    1965           2 :         metrics.Snapshots.PinnedKeys = d.mu.snapshots.cumulativePinnedCount
    1966           2 :         metrics.Snapshots.PinnedSize = d.mu.snapshots.cumulativePinnedSize
    1967           2 :         metrics.MemTable.Count = int64(len(d.mu.mem.queue))
    1968           2 :         metrics.MemTable.ZombieCount = d.memTableCount.Load() - metrics.MemTable.Count
    1969           2 :         metrics.MemTable.ZombieSize = uint64(d.memTableReserved.Load()) - metrics.MemTable.Size
    1970           2 :         metrics.WAL.ObsoleteFiles = int64(recycledLogsCount)
    1971           2 :         metrics.WAL.ObsoletePhysicalSize = recycledLogSize
    1972           2 :         metrics.WAL.Size = d.logSize.Load()
    1973           2 :         // The current WAL size (d.atomic.logSize) is the current logical size,
    1974           2 :         // which may be less than the WAL's physical size if it was recycled.
    1975           2 :         // The file sizes in d.mu.log.queue are updated to the physical size
    1976           2 :         // during WAL rotation. Use the larger of the two for the current WAL. All
    1977           2 :         // the previous WALs's fileSizes in d.mu.log.queue are already updated.
    1978           2 :         metrics.WAL.PhysicalSize = metrics.WAL.Size
    1979           2 :         if len(d.mu.log.queue) > 0 && metrics.WAL.PhysicalSize < d.mu.log.queue[len(d.mu.log.queue)-1].fileSize {
    1980           1 :                 metrics.WAL.PhysicalSize = d.mu.log.queue[len(d.mu.log.queue)-1].fileSize
    1981           1 :         }
    1982           2 :         for i, n := 0, len(d.mu.log.queue)-1; i < n; i++ {
    1983           2 :                 metrics.WAL.PhysicalSize += d.mu.log.queue[i].fileSize
    1984           2 :         }
    1985             : 
    1986           2 :         metrics.WAL.BytesIn = d.mu.log.bytesIn // protected by d.mu
    1987           2 :         for i, n := 0, len(d.mu.mem.queue)-1; i < n; i++ {
    1988           2 :                 metrics.WAL.Size += d.mu.mem.queue[i].logSize
    1989           2 :         }
    1990           2 :         metrics.WAL.BytesWritten = metrics.Levels[0].BytesIn + metrics.WAL.Size
    1991           2 :         if p := d.mu.versions.picker; p != nil {
    1992           2 :                 compactions := d.getInProgressCompactionInfoLocked(nil)
    1993           2 :                 for level, score := range p.getScores(compactions) {
    1994           2 :                         metrics.Levels[level].Score = score
    1995           2 :                 }
    1996             :         }
    1997           2 :         metrics.Table.ZombieCount = int64(len(d.mu.versions.zombieTables))
    1998           2 :         for _, size := range d.mu.versions.zombieTables {
    1999           1 :                 metrics.Table.ZombieSize += size
    2000           1 :         }
    2001           2 :         metrics.private.optionsFileSize = d.optionsFileSize
    2002           2 : 
    2003           2 :         // TODO(jackson): Consider making these metrics optional.
    2004           2 :         metrics.Keys.RangeKeySetsCount = countRangeKeySetFragments(vers)
    2005           2 :         metrics.Keys.TombstoneCount = countTombstones(vers)
    2006           2 : 
    2007           2 :         d.mu.versions.logLock()
    2008           2 :         metrics.private.manifestFileSize = uint64(d.mu.versions.manifest.Size())
    2009           2 :         metrics.Table.BackingTableCount = uint64(len(d.mu.versions.backingState.fileBackingMap))
    2010           2 :         metrics.Table.BackingTableSize = d.mu.versions.backingState.fileBackingSize
    2011           2 :         if invariants.Enabled {
    2012           2 :                 var totalSize uint64
    2013           2 :                 for _, backing := range d.mu.versions.backingState.fileBackingMap {
    2014           2 :                         totalSize += backing.Size
    2015           2 :                 }
    2016           2 :                 if totalSize != metrics.Table.BackingTableSize {
    2017           0 :                         panic("pebble: invalid backing table size accounting")
    2018             :                 }
    2019             :         }
    2020           2 :         d.mu.versions.logUnlock()
    2021           2 : 
    2022           2 :         metrics.LogWriter.FsyncLatency = d.mu.log.metrics.fsyncLatency
    2023           2 :         if err := metrics.LogWriter.Merge(&d.mu.log.metrics.LogWriterMetrics); err != nil {
    2024           0 :                 d.opts.Logger.Errorf("metrics error: %s", err)
    2025           0 :         }
    2026           2 :         metrics.Flush.WriteThroughput = d.mu.compact.flushWriteThroughput
    2027           2 :         if d.mu.compact.flushing {
    2028           1 :                 metrics.Flush.NumInProgress = 1
    2029           1 :         }
    2030           2 :         for i := 0; i < numLevels; i++ {
    2031           2 :                 metrics.Levels[i].Additional.ValueBlocksSize = valueBlocksSizeForLevel(vers, i)
    2032           2 :         }
    2033             : 
    2034           2 :         d.mu.Unlock()
    2035           2 : 
    2036           2 :         metrics.BlockCache = d.opts.Cache.Metrics()
    2037           2 :         metrics.TableCache, metrics.Filter = d.tableCache.metrics()
    2038           2 :         metrics.TableIters = int64(d.tableCache.iterCount())
    2039           2 :         metrics.CategoryStats = d.tableCache.dbOpts.sstStatsCollector.GetStats()
    2040           2 : 
    2041           2 :         metrics.SecondaryCacheMetrics = d.objProvider.Metrics()
    2042           2 : 
    2043           2 :         metrics.Uptime = d.timeNow().Sub(d.openedAt)
    2044           2 : 
    2045           2 :         return metrics
    2046             : }
    2047             : 
    2048             : // sstablesOptions hold the optional parameters to retrieve TableInfo for all sstables.
    2049             : type sstablesOptions struct {
    2050             :         // set to true will return the sstable properties in TableInfo
    2051             :         withProperties bool
    2052             : 
    2053             :         // if set, return sstables that overlap the key range (end-exclusive)
    2054             :         start []byte
    2055             :         end   []byte
    2056             : 
    2057             :         withApproximateSpanBytes bool
    2058             : }
    2059             : 
    2060             : // SSTablesOption set optional parameter used by `DB.SSTables`.
    2061             : type SSTablesOption func(*sstablesOptions)
    2062             : 
    2063             : // WithProperties enable return sstable properties in each TableInfo.
    2064             : //
    2065             : // NOTE: if most of the sstable properties need to be read from disk,
    2066             : // this options may make method `SSTables` quite slow.
    2067           1 : func WithProperties() SSTablesOption {
    2068           1 :         return func(opt *sstablesOptions) {
    2069           1 :                 opt.withProperties = true
    2070           1 :         }
    2071             : }
    2072             : 
    2073             : // WithKeyRangeFilter ensures returned sstables overlap start and end (end-exclusive)
    2074             : // if start and end are both nil these properties have no effect.
    2075           1 : func WithKeyRangeFilter(start, end []byte) SSTablesOption {
    2076           1 :         return func(opt *sstablesOptions) {
    2077           1 :                 opt.end = end
    2078           1 :                 opt.start = start
    2079           1 :         }
    2080             : }
    2081             : 
    2082             : // WithApproximateSpanBytes enables capturing the approximate number of bytes that
    2083             : // overlap the provided key span for each sstable.
    2084             : // NOTE: this option can only be used with WithKeyRangeFilter and WithProperties
    2085             : // provided.
    2086           1 : func WithApproximateSpanBytes() SSTablesOption {
    2087           1 :         return func(opt *sstablesOptions) {
    2088           1 :                 opt.withApproximateSpanBytes = true
    2089           1 :         }
    2090             : }
    2091             : 
    2092             : // BackingType denotes the type of storage backing a given sstable.
    2093             : type BackingType int
    2094             : 
    2095             : const (
    2096             :         // BackingTypeLocal denotes an sstable stored on local disk according to the
    2097             :         // objprovider. This file is completely owned by us.
    2098             :         BackingTypeLocal BackingType = iota
    2099             :         // BackingTypeShared denotes an sstable stored on shared storage, created
    2100             :         // by this Pebble instance and possibly shared by other Pebble instances.
    2101             :         // These types of files have lifecycle managed by Pebble.
    2102             :         BackingTypeShared
    2103             :         // BackingTypeSharedForeign denotes an sstable stored on shared storage,
    2104             :         // created by a Pebble instance other than this one. These types of files have
    2105             :         // lifecycle managed by Pebble.
    2106             :         BackingTypeSharedForeign
    2107             :         // BackingTypeExternal denotes an sstable stored on external storage,
    2108             :         // not owned by any Pebble instance and with no refcounting/cleanup methods
    2109             :         // or lifecycle management. An example of an external file is a file restored
    2110             :         // from a backup.
    2111             :         BackingTypeExternal
    2112             : )
    2113             : 
    2114             : // SSTableInfo export manifest.TableInfo with sstable.Properties alongside
    2115             : // other file backing info.
    2116             : type SSTableInfo struct {
    2117             :         manifest.TableInfo
    2118             :         // Virtual indicates whether the sstable is virtual.
    2119             :         Virtual bool
    2120             :         // BackingSSTNum is the file number associated with backing sstable which
    2121             :         // backs the sstable associated with this SSTableInfo. If Virtual is false,
    2122             :         // then BackingSSTNum == FileNum.
    2123             :         BackingSSTNum base.FileNum
    2124             :         // BackingType is the type of storage backing this sstable.
    2125             :         BackingType BackingType
    2126             :         // Locator is the remote.Locator backing this sstable, if the backing type is
    2127             :         // not BackingTypeLocal.
    2128             :         Locator remote.Locator
    2129             : 
    2130             :         // Properties is the sstable properties of this table. If Virtual is true,
    2131             :         // then the Properties are associated with the backing sst.
    2132             :         Properties *sstable.Properties
    2133             : }
    2134             : 
    2135             : // SSTables retrieves the current sstables. The returned slice is indexed by
    2136             : // level and each level is indexed by the position of the sstable within the
    2137             : // level. Note that this information may be out of date due to concurrent
    2138             : // flushes and compactions.
    2139           1 : func (d *DB) SSTables(opts ...SSTablesOption) ([][]SSTableInfo, error) {
    2140           1 :         opt := &sstablesOptions{}
    2141           1 :         for _, fn := range opts {
    2142           1 :                 fn(opt)
    2143           1 :         }
    2144             : 
    2145           1 :         if opt.withApproximateSpanBytes && !opt.withProperties {
    2146           1 :                 return nil, errors.Errorf("Cannot use WithApproximateSpanBytes without WithProperties option.")
    2147           1 :         }
    2148           1 :         if opt.withApproximateSpanBytes && (opt.start == nil || opt.end == nil) {
    2149           1 :                 return nil, errors.Errorf("Cannot use WithApproximateSpanBytes without WithKeyRangeFilter option.")
    2150           1 :         }
    2151             : 
    2152             :         // Grab and reference the current readState.
    2153           1 :         readState := d.loadReadState()
    2154           1 :         defer readState.unref()
    2155           1 : 
    2156           1 :         // TODO(peter): This is somewhat expensive, especially on a large
    2157           1 :         // database. It might be worthwhile to unify TableInfo and FileMetadata and
    2158           1 :         // then we could simply return current.Files. Note that RocksDB is doing
    2159           1 :         // something similar to the current code, so perhaps it isn't too bad.
    2160           1 :         srcLevels := readState.current.Levels
    2161           1 :         var totalTables int
    2162           1 :         for i := range srcLevels {
    2163           1 :                 totalTables += srcLevels[i].Len()
    2164           1 :         }
    2165             : 
    2166           1 :         destTables := make([]SSTableInfo, totalTables)
    2167           1 :         destLevels := make([][]SSTableInfo, len(srcLevels))
    2168           1 :         for i := range destLevels {
    2169           1 :                 iter := srcLevels[i].Iter()
    2170           1 :                 j := 0
    2171           1 :                 for m := iter.First(); m != nil; m = iter.Next() {
    2172           1 :                         if opt.start != nil && opt.end != nil && !m.Overlaps(d.opts.Comparer.Compare, opt.start, opt.end, true /* exclusive end */) {
    2173           1 :                                 continue
    2174             :                         }
    2175           1 :                         destTables[j] = SSTableInfo{TableInfo: m.TableInfo()}
    2176           1 :                         if opt.withProperties {
    2177           1 :                                 p, err := d.tableCache.getTableProperties(
    2178           1 :                                         m,
    2179           1 :                                 )
    2180           1 :                                 if err != nil {
    2181           0 :                                         return nil, err
    2182           0 :                                 }
    2183           1 :                                 destTables[j].Properties = p
    2184             :                         }
    2185           1 :                         destTables[j].Virtual = m.Virtual
    2186           1 :                         destTables[j].BackingSSTNum = m.FileBacking.DiskFileNum.FileNum()
    2187           1 :                         objMeta, err := d.objProvider.Lookup(fileTypeTable, m.FileBacking.DiskFileNum)
    2188           1 :                         if err != nil {
    2189           0 :                                 return nil, err
    2190           0 :                         }
    2191           1 :                         if objMeta.IsRemote() {
    2192           0 :                                 if objMeta.IsShared() {
    2193           0 :                                         if d.objProvider.IsSharedForeign(objMeta) {
    2194           0 :                                                 destTables[j].BackingType = BackingTypeSharedForeign
    2195           0 :                                         } else {
    2196           0 :                                                 destTables[j].BackingType = BackingTypeShared
    2197           0 :                                         }
    2198           0 :                                 } else {
    2199           0 :                                         destTables[j].BackingType = BackingTypeExternal
    2200           0 :                                 }
    2201           0 :                                 destTables[j].Locator = objMeta.Remote.Locator
    2202           1 :                         } else {
    2203           1 :                                 destTables[j].BackingType = BackingTypeLocal
    2204           1 :                         }
    2205             : 
    2206           1 :                         if opt.withApproximateSpanBytes {
    2207           1 :                                 var spanBytes uint64
    2208           1 :                                 if m.ContainedWithinSpan(d.opts.Comparer.Compare, opt.start, opt.end) {
    2209           1 :                                         spanBytes = m.Size
    2210           1 :                                 } else {
    2211           1 :                                         size, err := d.tableCache.estimateSize(m, opt.start, opt.end)
    2212           1 :                                         if err != nil {
    2213           0 :                                                 return nil, err
    2214           0 :                                         }
    2215           1 :                                         spanBytes = size
    2216             :                                 }
    2217           1 :                                 propertiesCopy := *destTables[j].Properties
    2218           1 : 
    2219           1 :                                 // Deep copy user properties so approximate span bytes can be added.
    2220           1 :                                 propertiesCopy.UserProperties = make(map[string]string, len(destTables[j].Properties.UserProperties)+1)
    2221           1 :                                 for k, v := range destTables[j].Properties.UserProperties {
    2222           0 :                                         propertiesCopy.UserProperties[k] = v
    2223           0 :                                 }
    2224           1 :                                 propertiesCopy.UserProperties["approximate-span-bytes"] = strconv.FormatUint(spanBytes, 10)
    2225           1 :                                 destTables[j].Properties = &propertiesCopy
    2226             :                         }
    2227           1 :                         j++
    2228             :                 }
    2229           1 :                 destLevels[i] = destTables[:j]
    2230           1 :                 destTables = destTables[j:]
    2231             :         }
    2232             : 
    2233           1 :         return destLevels, nil
    2234             : }
    2235             : 
    2236             : // EstimateDiskUsage returns the estimated filesystem space used in bytes for
    2237             : // storing the range `[start, end]`. The estimation is computed as follows:
    2238             : //
    2239             : //   - For sstables fully contained in the range the whole file size is included.
    2240             : //   - For sstables partially contained in the range the overlapping data block sizes
    2241             : //     are included. Even if a data block partially overlaps, or we cannot determine
    2242             : //     overlap due to abbreviated index keys, the full data block size is included in
    2243             : //     the estimation. Note that unlike fully contained sstables, none of the
    2244             : //     meta-block space is counted for partially overlapped files.
    2245             : //   - For virtual sstables, we use the overlap between start, end and the virtual
    2246             : //     sstable bounds to determine disk usage.
    2247             : //   - There may also exist WAL entries for unflushed keys in this range. This
    2248             : //     estimation currently excludes space used for the range in the WAL.
    2249           1 : func (d *DB) EstimateDiskUsage(start, end []byte) (uint64, error) {
    2250           1 :         bytes, _, _, err := d.EstimateDiskUsageByBackingType(start, end)
    2251           1 :         return bytes, err
    2252           1 : }
    2253             : 
    2254             : // EstimateDiskUsageByBackingType is like EstimateDiskUsage but additionally
    2255             : // returns the subsets of that size in remote ane external files.
    2256             : func (d *DB) EstimateDiskUsageByBackingType(
    2257             :         start, end []byte,
    2258           1 : ) (totalSize, remoteSize, externalSize uint64, _ error) {
    2259           1 :         if err := d.closed.Load(); err != nil {
    2260           0 :                 panic(err)
    2261             :         }
    2262           1 :         if d.opts.Comparer.Compare(start, end) > 0 {
    2263           0 :                 return 0, 0, 0, errors.New("invalid key-range specified (start > end)")
    2264           0 :         }
    2265             : 
    2266             :         // Grab and reference the current readState. This prevents the underlying
    2267             :         // files in the associated version from being deleted if there is a concurrent
    2268             :         // compaction.
    2269           1 :         readState := d.loadReadState()
    2270           1 :         defer readState.unref()
    2271           1 : 
    2272           1 :         for level, files := range readState.current.Levels {
    2273           1 :                 iter := files.Iter()
    2274           1 :                 if level > 0 {
    2275           1 :                         // We can only use `Overlaps` to restrict `files` at L1+ since at L0 it
    2276           1 :                         // expands the range iteratively until it has found a set of files that
    2277           1 :                         // do not overlap any other L0 files outside that set.
    2278           1 :                         overlaps := readState.current.Overlaps(level, d.opts.Comparer.Compare, start, end, false /* exclusiveEnd */)
    2279           1 :                         iter = overlaps.Iter()
    2280           1 :                 }
    2281           1 :                 for file := iter.First(); file != nil; file = iter.Next() {
    2282           1 :                         if d.opts.Comparer.Compare(start, file.Smallest.UserKey) <= 0 &&
    2283           1 :                                 d.opts.Comparer.Compare(file.Largest.UserKey, end) <= 0 {
    2284           1 :                                 // The range fully contains the file, so skip looking it up in
    2285           1 :                                 // table cache/looking at its indexes, and add the full file size.
    2286           1 :                                 meta, err := d.objProvider.Lookup(fileTypeTable, file.FileBacking.DiskFileNum)
    2287           1 :                                 if err != nil {
    2288           0 :                                         return 0, 0, 0, err
    2289           0 :                                 }
    2290           1 :                                 if meta.IsRemote() {
    2291           0 :                                         remoteSize += file.Size
    2292           0 :                                         if meta.Remote.CleanupMethod == objstorage.SharedNoCleanup {
    2293           0 :                                                 externalSize += file.Size
    2294           0 :                                         }
    2295             :                                 }
    2296           1 :                                 totalSize += file.Size
    2297           1 :                         } else if d.opts.Comparer.Compare(file.Smallest.UserKey, end) <= 0 &&
    2298           1 :                                 d.opts.Comparer.Compare(start, file.Largest.UserKey) <= 0 {
    2299           1 :                                 var size uint64
    2300           1 :                                 var err error
    2301           1 :                                 if file.Virtual {
    2302           0 :                                         err = d.tableCache.withVirtualReader(
    2303           0 :                                                 file.VirtualMeta(),
    2304           0 :                                                 func(r sstable.VirtualReader) (err error) {
    2305           0 :                                                         size, err = r.EstimateDiskUsage(start, end)
    2306           0 :                                                         return err
    2307           0 :                                                 },
    2308             :                                         )
    2309           1 :                                 } else {
    2310           1 :                                         err = d.tableCache.withReader(
    2311           1 :                                                 file.PhysicalMeta(),
    2312           1 :                                                 func(r *sstable.Reader) (err error) {
    2313           1 :                                                         size, err = r.EstimateDiskUsage(start, end)
    2314           1 :                                                         return err
    2315           1 :                                                 },
    2316             :                                         )
    2317             :                                 }
    2318           1 :                                 if err != nil {
    2319           0 :                                         return 0, 0, 0, err
    2320           0 :                                 }
    2321           1 :                                 meta, err := d.objProvider.Lookup(fileTypeTable, file.FileBacking.DiskFileNum)
    2322           1 :                                 if err != nil {
    2323           0 :                                         return 0, 0, 0, err
    2324           0 :                                 }
    2325           1 :                                 if meta.IsRemote() {
    2326           0 :                                         remoteSize += size
    2327           0 :                                         if meta.Remote.CleanupMethod == objstorage.SharedNoCleanup {
    2328           0 :                                                 externalSize += size
    2329           0 :                                         }
    2330             :                                 }
    2331           1 :                                 totalSize += size
    2332             :                         }
    2333             :                 }
    2334             :         }
    2335           1 :         return totalSize, remoteSize, externalSize, nil
    2336             : }
    2337             : 
    2338           2 : func (d *DB) walPreallocateSize() int {
    2339           2 :         // Set the WAL preallocate size to 110% of the memtable size. Note that there
    2340           2 :         // is a bit of apples and oranges in units here as the memtabls size
    2341           2 :         // corresponds to the memory usage of the memtable while the WAL size is the
    2342           2 :         // size of the batches (plus overhead) stored in the WAL.
    2343           2 :         //
    2344           2 :         // TODO(peter): 110% of the memtable size is quite hefty for a block
    2345           2 :         // size. This logic is taken from GetWalPreallocateBlockSize in
    2346           2 :         // RocksDB. Could a smaller preallocation block size be used?
    2347           2 :         size := d.opts.MemTableSize
    2348           2 :         size = (size / 10) + size
    2349           2 :         return int(size)
    2350           2 : }
    2351             : 
    2352           2 : func (d *DB) newMemTable(logNum base.DiskFileNum, logSeqNum uint64) (*memTable, *flushableEntry) {
    2353           2 :         size := d.mu.mem.nextSize
    2354           2 :         if d.mu.mem.nextSize < d.opts.MemTableSize {
    2355           2 :                 d.mu.mem.nextSize *= 2
    2356           2 :                 if d.mu.mem.nextSize > d.opts.MemTableSize {
    2357           1 :                         d.mu.mem.nextSize = d.opts.MemTableSize
    2358           1 :                 }
    2359             :         }
    2360             : 
    2361           2 :         memtblOpts := memTableOptions{
    2362           2 :                 Options:   d.opts,
    2363           2 :                 logSeqNum: logSeqNum,
    2364           2 :         }
    2365           2 : 
    2366           2 :         // Before attempting to allocate a new memtable, check if there's one
    2367           2 :         // available for recycling in memTableRecycle. Large contiguous allocations
    2368           2 :         // can be costly as fragmentation makes it more difficult to find a large
    2369           2 :         // contiguous free space. We've observed 64MB allocations taking 10ms+.
    2370           2 :         //
    2371           2 :         // To reduce these costly allocations, up to 1 obsolete memtable is stashed
    2372           2 :         // in `d.memTableRecycle` to allow a future memtable rotation to reuse
    2373           2 :         // existing memory.
    2374           2 :         var mem *memTable
    2375           2 :         mem = d.memTableRecycle.Swap(nil)
    2376           2 :         if mem != nil && uint64(len(mem.arenaBuf)) != size {
    2377           2 :                 d.freeMemTable(mem)
    2378           2 :                 mem = nil
    2379           2 :         }
    2380           2 :         if mem != nil {
    2381           2 :                 // Carry through the existing buffer and memory reservation.
    2382           2 :                 memtblOpts.arenaBuf = mem.arenaBuf
    2383           2 :                 memtblOpts.releaseAccountingReservation = mem.releaseAccountingReservation
    2384           2 :         } else {
    2385           2 :                 mem = new(memTable)
    2386           2 :                 memtblOpts.arenaBuf = manual.New(int(size))
    2387           2 :                 memtblOpts.releaseAccountingReservation = d.opts.Cache.Reserve(int(size))
    2388           2 :                 d.memTableCount.Add(1)
    2389           2 :                 d.memTableReserved.Add(int64(size))
    2390           2 : 
    2391           2 :                 // Note: this is a no-op if invariants are disabled or race is enabled.
    2392           2 :                 invariants.SetFinalizer(mem, checkMemTable)
    2393           2 :         }
    2394           2 :         mem.init(memtblOpts)
    2395           2 : 
    2396           2 :         entry := d.newFlushableEntry(mem, logNum, logSeqNum)
    2397           2 :         entry.releaseMemAccounting = func() {
    2398           2 :                 // If the user leaks iterators, we may be releasing the memtable after
    2399           2 :                 // the DB is already closed. In this case, we want to just release the
    2400           2 :                 // memory because DB.Close won't come along to free it for us.
    2401           2 :                 if err := d.closed.Load(); err != nil {
    2402           2 :                         d.freeMemTable(mem)
    2403           2 :                         return
    2404           2 :                 }
    2405             : 
    2406             :                 // The next memtable allocation might be able to reuse this memtable.
    2407             :                 // Stash it on d.memTableRecycle.
    2408           2 :                 if unusedMem := d.memTableRecycle.Swap(mem); unusedMem != nil {
    2409           2 :                         // There was already a memtable waiting to be recycled. We're now
    2410           2 :                         // responsible for freeing it.
    2411           2 :                         d.freeMemTable(unusedMem)
    2412           2 :                 }
    2413             :         }
    2414           2 :         return mem, entry
    2415             : }
    2416             : 
    2417           2 : func (d *DB) freeMemTable(m *memTable) {
    2418           2 :         d.memTableCount.Add(-1)
    2419           2 :         d.memTableReserved.Add(-int64(len(m.arenaBuf)))
    2420           2 :         m.free()
    2421           2 : }
    2422             : 
    2423             : func (d *DB) newFlushableEntry(
    2424             :         f flushable, logNum base.DiskFileNum, logSeqNum uint64,
    2425           2 : ) *flushableEntry {
    2426           2 :         fe := &flushableEntry{
    2427           2 :                 flushable:      f,
    2428           2 :                 flushed:        make(chan struct{}),
    2429           2 :                 logNum:         logNum,
    2430           2 :                 logSeqNum:      logSeqNum,
    2431           2 :                 deleteFn:       d.mu.versions.addObsolete,
    2432           2 :                 deleteFnLocked: d.mu.versions.addObsoleteLocked,
    2433           2 :         }
    2434           2 :         fe.readerRefs.Store(1)
    2435           2 :         return fe
    2436           2 : }
    2437             : 
    2438             : // makeRoomForWrite ensures that the memtable has room to hold the contents of
    2439             : // Batch. It reserves the space in the memtable and adds a reference to the
    2440             : // memtable. The caller must later ensure that the memtable is unreferenced. If
    2441             : // the memtable is full, or a nil Batch is provided, the current memtable is
    2442             : // rotated (marked as immutable) and a new mutable memtable is allocated. This
    2443             : // memtable rotation also causes a log rotation.
    2444             : //
    2445             : // Both DB.mu and commitPipeline.mu must be held by the caller. Note that DB.mu
    2446             : // may be released and reacquired.
    2447           2 : func (d *DB) makeRoomForWrite(b *Batch) error {
    2448           2 :         if b != nil && b.ingestedSSTBatch {
    2449           0 :                 panic("pebble: invalid function call")
    2450             :         }
    2451             : 
    2452           2 :         force := b == nil || b.flushable != nil
    2453           2 :         stalled := false
    2454           2 :         for {
    2455           2 :                 if b != nil && b.flushable == nil {
    2456           2 :                         err := d.mu.mem.mutable.prepare(b)
    2457           2 :                         if err != arenaskl.ErrArenaFull {
    2458           2 :                                 if stalled {
    2459           2 :                                         d.opts.EventListener.WriteStallEnd()
    2460           2 :                                 }
    2461           2 :                                 return err
    2462             :                         }
    2463           2 :                 } else if !force {
    2464           2 :                         if stalled {
    2465           2 :                                 d.opts.EventListener.WriteStallEnd()
    2466           2 :                         }
    2467           2 :                         return nil
    2468             :                 }
    2469             :                 // force || err == ErrArenaFull, so we need to rotate the current memtable.
    2470           2 :                 {
    2471           2 :                         var size uint64
    2472           2 :                         for i := range d.mu.mem.queue {
    2473           2 :                                 size += d.mu.mem.queue[i].totalBytes()
    2474           2 :                         }
    2475           2 :                         if size >= uint64(d.opts.MemTableStopWritesThreshold)*d.opts.MemTableSize {
    2476           2 :                                 // We have filled up the current memtable, but already queued memtables
    2477           2 :                                 // are still flushing, so we wait.
    2478           2 :                                 if !stalled {
    2479           2 :                                         stalled = true
    2480           2 :                                         d.opts.EventListener.WriteStallBegin(WriteStallBeginInfo{
    2481           2 :                                                 Reason: "memtable count limit reached",
    2482           2 :                                         })
    2483           2 :                                 }
    2484           2 :                                 now := time.Now()
    2485           2 :                                 d.mu.compact.cond.Wait()
    2486           2 :                                 if b != nil {
    2487           2 :                                         b.commitStats.MemTableWriteStallDuration += time.Since(now)
    2488           2 :                                 }
    2489           2 :                                 continue
    2490             :                         }
    2491             :                 }
    2492           2 :                 l0ReadAmp := d.mu.versions.currentVersion().L0Sublevels.ReadAmplification()
    2493           2 :                 if l0ReadAmp >= d.opts.L0StopWritesThreshold {
    2494           2 :                         // There are too many level-0 files, so we wait.
    2495           2 :                         if !stalled {
    2496           2 :                                 stalled = true
    2497           2 :                                 d.opts.EventListener.WriteStallBegin(WriteStallBeginInfo{
    2498           2 :                                         Reason: "L0 file count limit exceeded",
    2499           2 :                                 })
    2500           2 :                         }
    2501           2 :                         now := time.Now()
    2502           2 :                         d.mu.compact.cond.Wait()
    2503           2 :                         if b != nil {
    2504           1 :                                 b.commitStats.L0ReadAmpWriteStallDuration += time.Since(now)
    2505           1 :                         }
    2506           2 :                         continue
    2507             :                 }
    2508             : 
    2509           2 :                 var newLogNum base.DiskFileNum
    2510           2 :                 var prevLogSize uint64
    2511           2 :                 if !d.opts.DisableWAL {
    2512           2 :                         now := time.Now()
    2513           2 :                         newLogNum, prevLogSize = d.recycleWAL()
    2514           2 :                         if b != nil {
    2515           2 :                                 b.commitStats.WALRotationDuration += time.Since(now)
    2516           2 :                         }
    2517             :                 }
    2518             : 
    2519           2 :                 immMem := d.mu.mem.mutable
    2520           2 :                 imm := d.mu.mem.queue[len(d.mu.mem.queue)-1]
    2521           2 :                 imm.logSize = prevLogSize
    2522           2 :                 imm.flushForced = imm.flushForced || (b == nil)
    2523           2 : 
    2524           2 :                 // If we are manually flushing and we used less than half of the bytes in
    2525           2 :                 // the memtable, don't increase the size for the next memtable. This
    2526           2 :                 // reduces memtable memory pressure when an application is frequently
    2527           2 :                 // manually flushing.
    2528           2 :                 if (b == nil) && uint64(immMem.availBytes()) > immMem.totalBytes()/2 {
    2529           2 :                         d.mu.mem.nextSize = immMem.totalBytes()
    2530           2 :                 }
    2531             : 
    2532           2 :                 if b != nil && b.flushable != nil {
    2533           2 :                         // The batch is too large to fit in the memtable so add it directly to
    2534           2 :                         // the immutable queue. The flushable batch is associated with the same
    2535           2 :                         // log as the immutable memtable, but logically occurs after it in
    2536           2 :                         // seqnum space. We ensure while flushing that the flushable batch
    2537           2 :                         // is flushed along with the previous memtable in the flushable
    2538           2 :                         // queue. See the top level comment in DB.flush1 to learn how this
    2539           2 :                         // is ensured.
    2540           2 :                         //
    2541           2 :                         // See DB.commitWrite for the special handling of log writes for large
    2542           2 :                         // batches. In particular, the large batch has already written to
    2543           2 :                         // imm.logNum.
    2544           2 :                         entry := d.newFlushableEntry(b.flushable, imm.logNum, b.SeqNum())
    2545           2 :                         // The large batch is by definition large. Reserve space from the cache
    2546           2 :                         // for it until it is flushed.
    2547           2 :                         entry.releaseMemAccounting = d.opts.Cache.Reserve(int(b.flushable.totalBytes()))
    2548           2 :                         d.mu.mem.queue = append(d.mu.mem.queue, entry)
    2549           2 :                 }
    2550             : 
    2551           2 :                 var logSeqNum uint64
    2552           2 :                 if b != nil {
    2553           2 :                         logSeqNum = b.SeqNum()
    2554           2 :                         if b.flushable != nil {
    2555           2 :                                 logSeqNum += uint64(b.Count())
    2556           2 :                         }
    2557           2 :                 } else {
    2558           2 :                         logSeqNum = d.mu.versions.logSeqNum.Load()
    2559           2 :                 }
    2560           2 :                 d.rotateMemtable(newLogNum, logSeqNum, immMem)
    2561           2 :                 force = false
    2562             :         }
    2563             : }
    2564             : 
    2565             : // Both DB.mu and commitPipeline.mu must be held by the caller.
    2566           2 : func (d *DB) rotateMemtable(newLogNum base.DiskFileNum, logSeqNum uint64, prev *memTable) {
    2567           2 :         // Create a new memtable, scheduling the previous one for flushing. We do
    2568           2 :         // this even if the previous memtable was empty because the DB.Flush
    2569           2 :         // mechanism is dependent on being able to wait for the empty memtable to
    2570           2 :         // flush. We can't just mark the empty memtable as flushed here because we
    2571           2 :         // also have to wait for all previous immutable tables to
    2572           2 :         // flush. Additionally, the memtable is tied to particular WAL file and we
    2573           2 :         // want to go through the flush path in order to recycle that WAL file.
    2574           2 :         //
    2575           2 :         // NB: newLogNum corresponds to the WAL that contains mutations that are
    2576           2 :         // present in the new memtable. When immutable memtables are flushed to
    2577           2 :         // disk, a VersionEdit will be created telling the manifest the minimum
    2578           2 :         // unflushed log number (which will be the next one in d.mu.mem.mutable
    2579           2 :         // that was not flushed).
    2580           2 :         //
    2581           2 :         // NB: prev should be the current mutable memtable.
    2582           2 :         var entry *flushableEntry
    2583           2 :         d.mu.mem.mutable, entry = d.newMemTable(newLogNum, logSeqNum)
    2584           2 :         d.mu.mem.queue = append(d.mu.mem.queue, entry)
    2585           2 :         d.updateReadStateLocked(nil)
    2586           2 :         if prev.writerUnref() {
    2587           2 :                 d.maybeScheduleFlush()
    2588           2 :         }
    2589             : }
    2590             : 
    2591             : // Both DB.mu and commitPipeline.mu must be held by the caller. Note that DB.mu
    2592             : // may be released and reacquired.
    2593           2 : func (d *DB) recycleWAL() (newLogNum base.DiskFileNum, prevLogSize uint64) {
    2594           2 :         if d.opts.DisableWAL {
    2595           0 :                 panic("pebble: invalid function call")
    2596             :         }
    2597             : 
    2598           2 :         jobID := d.mu.nextJobID
    2599           2 :         d.mu.nextJobID++
    2600           2 :         newLogNum = d.mu.versions.getNextDiskFileNum()
    2601           2 : 
    2602           2 :         prevLogSize = uint64(d.mu.log.Size())
    2603           2 : 
    2604           2 :         // The previous log may have grown past its original physical
    2605           2 :         // size. Update its file size in the queue so we have a proper
    2606           2 :         // accounting of its file size.
    2607           2 :         if d.mu.log.queue[len(d.mu.log.queue)-1].fileSize < prevLogSize {
    2608           2 :                 d.mu.log.queue[len(d.mu.log.queue)-1].fileSize = prevLogSize
    2609           2 :         }
    2610           2 :         d.mu.Unlock()
    2611           2 : 
    2612           2 :         var err error
    2613           2 :         // Close the previous log first. This writes an EOF trailer
    2614           2 :         // signifying the end of the file and syncs it to disk. We must
    2615           2 :         // close the previous log before linking the new log file,
    2616           2 :         // otherwise a crash could leave both logs with unclean tails, and
    2617           2 :         // Open will treat the previous log as corrupt.
    2618           2 :         err = d.mu.log.LogWriter.Close()
    2619           2 :         metrics := d.mu.log.LogWriter.Metrics()
    2620           2 :         d.mu.Lock()
    2621           2 :         if err := d.mu.log.metrics.Merge(metrics); err != nil {
    2622           0 :                 d.opts.Logger.Errorf("metrics error: %s", err)
    2623           0 :         }
    2624           2 :         d.mu.Unlock()
    2625           2 : 
    2626           2 :         newLogName := base.MakeFilepath(d.opts.FS, d.walDirname, fileTypeLog, newLogNum)
    2627           2 : 
    2628           2 :         // Try to use a recycled log file. Recycling log files is an important
    2629           2 :         // performance optimization as it is faster to sync a file that has
    2630           2 :         // already been written, than one which is being written for the first
    2631           2 :         // time. This is due to the need to sync file metadata when a file is
    2632           2 :         // being written for the first time. Note this is true even if file
    2633           2 :         // preallocation is performed (e.g. fallocate).
    2634           2 :         var recycleLog fileInfo
    2635           2 :         var recycleOK bool
    2636           2 :         var newLogFile vfs.File
    2637           2 :         if err == nil {
    2638           2 :                 recycleLog, recycleOK = d.logRecycler.peek()
    2639           2 :                 if recycleOK {
    2640           1 :                         recycleLogName := base.MakeFilepath(d.opts.FS, d.walDirname, fileTypeLog, recycleLog.fileNum)
    2641           1 :                         newLogFile, err = d.opts.FS.ReuseForWrite(recycleLogName, newLogName)
    2642           1 :                         base.MustExist(d.opts.FS, newLogName, d.opts.Logger, err)
    2643           2 :                 } else {
    2644           2 :                         newLogFile, err = d.opts.FS.Create(newLogName)
    2645           2 :                         base.MustExist(d.opts.FS, newLogName, d.opts.Logger, err)
    2646           2 :                 }
    2647             :         }
    2648             : 
    2649           2 :         var newLogSize uint64
    2650           2 :         if err == nil && recycleOK {
    2651           1 :                 // Figure out the recycled WAL size. This Stat is necessary
    2652           1 :                 // because ReuseForWrite's contract allows for removing the
    2653           1 :                 // old file and creating a new one. We don't know whether the
    2654           1 :                 // WAL was actually recycled.
    2655           1 :                 // TODO(jackson): Adding a boolean to the ReuseForWrite return
    2656           1 :                 // value indicating whether or not the file was actually
    2657           1 :                 // reused would allow us to skip the stat and use
    2658           1 :                 // recycleLog.fileSize.
    2659           1 :                 var finfo os.FileInfo
    2660           1 :                 finfo, err = newLogFile.Stat()
    2661           1 :                 if err == nil {
    2662           1 :                         newLogSize = uint64(finfo.Size())
    2663           1 :                 }
    2664             :         }
    2665             : 
    2666           2 :         if err == nil {
    2667           2 :                 // TODO(peter): RocksDB delays sync of the parent directory until the
    2668           2 :                 // first time the log is synced. Is that worthwhile?
    2669           2 :                 err = d.walDir.Sync()
    2670           2 :         }
    2671             : 
    2672           2 :         if err != nil && newLogFile != nil {
    2673           0 :                 newLogFile.Close()
    2674           2 :         } else if err == nil {
    2675           2 :                 newLogFile = vfs.NewSyncingFile(newLogFile, vfs.SyncingFileOptions{
    2676           2 :                         NoSyncOnClose:   d.opts.NoSyncOnClose,
    2677           2 :                         BytesPerSync:    d.opts.WALBytesPerSync,
    2678           2 :                         PreallocateSize: d.walPreallocateSize(),
    2679           2 :                 })
    2680           2 :         }
    2681             : 
    2682           2 :         if recycleOK {
    2683           1 :                 err = firstError(err, d.logRecycler.pop(recycleLog.fileNum.FileNum()))
    2684           1 :         }
    2685             : 
    2686           2 :         d.opts.EventListener.WALCreated(WALCreateInfo{
    2687           2 :                 JobID:           jobID,
    2688           2 :                 Path:            newLogName,
    2689           2 :                 FileNum:         newLogNum,
    2690           2 :                 RecycledFileNum: recycleLog.fileNum.FileNum(),
    2691           2 :                 Err:             err,
    2692           2 :         })
    2693           2 : 
    2694           2 :         d.mu.Lock()
    2695           2 : 
    2696           2 :         d.mu.versions.metrics.WAL.Files++
    2697           2 : 
    2698           2 :         if err != nil {
    2699           0 :                 // TODO(peter): avoid chewing through file numbers in a tight loop if there
    2700           0 :                 // is an error here.
    2701           0 :                 //
    2702           0 :                 // What to do here? Stumbling on doesn't seem worthwhile. If we failed to
    2703           0 :                 // close the previous log it is possible we lost a write.
    2704           0 :                 panic(err)
    2705             :         }
    2706             : 
    2707           2 :         d.mu.log.queue = append(d.mu.log.queue, fileInfo{fileNum: newLogNum, fileSize: newLogSize})
    2708           2 :         d.mu.log.LogWriter = record.NewLogWriter(newLogFile, newLogNum, record.LogWriterConfig{
    2709           2 :                 WALFsyncLatency:    d.mu.log.metrics.fsyncLatency,
    2710           2 :                 WALMinSyncInterval: d.opts.WALMinSyncInterval,
    2711           2 :                 QueueSemChan:       d.commit.logSyncQSem,
    2712           2 :         })
    2713           2 :         if d.mu.log.registerLogWriterForTesting != nil {
    2714           0 :                 d.mu.log.registerLogWriterForTesting(d.mu.log.LogWriter)
    2715           0 :         }
    2716             : 
    2717           2 :         return
    2718             : }
    2719             : 
    2720           2 : func (d *DB) getEarliestUnflushedSeqNumLocked() uint64 {
    2721           2 :         seqNum := InternalKeySeqNumMax
    2722           2 :         for i := range d.mu.mem.queue {
    2723           2 :                 logSeqNum := d.mu.mem.queue[i].logSeqNum
    2724           2 :                 if seqNum > logSeqNum {
    2725           2 :                         seqNum = logSeqNum
    2726           2 :                 }
    2727             :         }
    2728           2 :         return seqNum
    2729             : }
    2730             : 
    2731           2 : func (d *DB) getInProgressCompactionInfoLocked(finishing *compaction) (rv []compactionInfo) {
    2732           2 :         for c := range d.mu.compact.inProgress {
    2733           2 :                 if len(c.flushing) == 0 && (finishing == nil || c != finishing) {
    2734           2 :                         info := compactionInfo{
    2735           2 :                                 versionEditApplied: c.versionEditApplied,
    2736           2 :                                 inputs:             c.inputs,
    2737           2 :                                 smallest:           c.smallest,
    2738           2 :                                 largest:            c.largest,
    2739           2 :                                 outputLevel:        -1,
    2740           2 :                         }
    2741           2 :                         if c.outputLevel != nil {
    2742           2 :                                 info.outputLevel = c.outputLevel.level
    2743           2 :                         }
    2744           2 :                         rv = append(rv, info)
    2745             :                 }
    2746             :         }
    2747           2 :         return
    2748             : }
    2749             : 
    2750           2 : func inProgressL0Compactions(inProgress []compactionInfo) []manifest.L0Compaction {
    2751           2 :         var compactions []manifest.L0Compaction
    2752           2 :         for _, info := range inProgress {
    2753           2 :                 // Skip in-progress compactions that have already committed; the L0
    2754           2 :                 // sublevels initialization code requires the set of in-progress
    2755           2 :                 // compactions to be consistent with the current version. Compactions
    2756           2 :                 // with versionEditApplied=true are already applied to the current
    2757           2 :                 // version and but are performing cleanup without the database mutex.
    2758           2 :                 if info.versionEditApplied {
    2759           2 :                         continue
    2760             :                 }
    2761           2 :                 l0 := false
    2762           2 :                 for _, cl := range info.inputs {
    2763           2 :                         l0 = l0 || cl.level == 0
    2764           2 :                 }
    2765           2 :                 if !l0 {
    2766           2 :                         continue
    2767             :                 }
    2768           2 :                 compactions = append(compactions, manifest.L0Compaction{
    2769           2 :                         Smallest:  info.smallest,
    2770           2 :                         Largest:   info.largest,
    2771           2 :                         IsIntraL0: info.outputLevel == 0,
    2772           2 :                 })
    2773             :         }
    2774           2 :         return compactions
    2775             : }
    2776             : 
    2777             : // firstError returns the first non-nil error of err0 and err1, or nil if both
    2778             : // are nil.
    2779           2 : func firstError(err0, err1 error) error {
    2780           2 :         if err0 != nil {
    2781           2 :                 return err0
    2782           2 :         }
    2783           2 :         return err1
    2784             : }
    2785             : 
    2786             : // SetCreatorID sets the CreatorID which is needed in order to use shared objects.
    2787             : // Remote object usage is disabled until this method is called the first time.
    2788             : // Once set, the Creator ID is persisted and cannot change.
    2789             : //
    2790             : // Does nothing if SharedStorage was not set in the options when the DB was
    2791             : // opened or if the DB is in read-only mode.
    2792           2 : func (d *DB) SetCreatorID(creatorID uint64) error {
    2793           2 :         if d.opts.Experimental.RemoteStorage == nil || d.opts.ReadOnly {
    2794           0 :                 return nil
    2795           0 :         }
    2796           2 :         return d.objProvider.SetCreatorID(objstorage.CreatorID(creatorID))
    2797             : }
    2798             : 
    2799             : // KeyStatistics keeps track of the number of keys that have been pinned by a
    2800             : // snapshot as well as counts of the different key kinds in the lsm.
    2801             : //
    2802             : // One way of using the accumulated stats, when we only have sets and dels,
    2803             : // and say the counts are represented as del_count, set_count,
    2804             : // del_latest_count, set_latest_count, snapshot_pinned_count.
    2805             : //
    2806             : //   - del_latest_count + set_latest_count is the set of unique user keys
    2807             : //     (unique).
    2808             : //
    2809             : //   - set_latest_count is the set of live unique user keys (live_unique).
    2810             : //
    2811             : //   - Garbage is del_count + set_count - live_unique.
    2812             : //
    2813             : //   - If everything were in the LSM, del_count+set_count-snapshot_pinned_count
    2814             : //     would also be the set of unique user keys (note that
    2815             : //     snapshot_pinned_count is counting something different -- see comment below).
    2816             : //     But snapshot_pinned_count only counts keys in the LSM so the excess here
    2817             : //     must be keys in memtables.
    2818             : type KeyStatistics struct {
    2819             :         // TODO(sumeer): the SnapshotPinned* are incorrect in that these older
    2820             :         // versions can be in a different level. Either fix the accounting or
    2821             :         // rename these fields.
    2822             : 
    2823             :         // SnapshotPinnedKeys represents obsolete keys that cannot be elided during
    2824             :         // a compaction, because they are required by an open snapshot.
    2825             :         SnapshotPinnedKeys int
    2826             :         // SnapshotPinnedKeysBytes is the total number of bytes of all snapshot
    2827             :         // pinned keys.
    2828             :         SnapshotPinnedKeysBytes uint64
    2829             :         // KindsCount is the count for each kind of key. It includes point keys,
    2830             :         // range deletes and range keys.
    2831             :         KindsCount [InternalKeyKindMax + 1]int
    2832             :         // LatestKindsCount is the count for each kind of key when it is the latest
    2833             :         // kind for a user key. It is only populated for point keys.
    2834             :         LatestKindsCount [InternalKeyKindMax + 1]int
    2835             : }
    2836             : 
    2837             : // LSMKeyStatistics is used by DB.ScanStatistics.
    2838             : type LSMKeyStatistics struct {
    2839             :         Accumulated KeyStatistics
    2840             :         // Levels contains statistics only for point keys. Range deletions and range keys will
    2841             :         // appear in Accumulated but not Levels.
    2842             :         Levels [numLevels]KeyStatistics
    2843             :         // BytesRead represents the logical, pre-compression size of keys and values read
    2844             :         BytesRead uint64
    2845             : }
    2846             : 
    2847             : // ScanStatisticsOptions is used by DB.ScanStatistics.
    2848             : type ScanStatisticsOptions struct {
    2849             :         // LimitBytesPerSecond indicates the number of bytes that are able to be read
    2850             :         // per second using ScanInternal.
    2851             :         // A value of 0 indicates that there is no limit set.
    2852             :         LimitBytesPerSecond int64
    2853             : }
    2854             : 
    2855             : // ScanStatistics returns the count of different key kinds within the lsm for a
    2856             : // key span [lower, upper) as well as the number of snapshot keys.
    2857             : func (d *DB) ScanStatistics(
    2858             :         ctx context.Context, lower, upper []byte, opts ScanStatisticsOptions,
    2859           1 : ) (LSMKeyStatistics, error) {
    2860           1 :         stats := LSMKeyStatistics{}
    2861           1 :         var prevKey InternalKey
    2862           1 :         var rateLimitFunc func(key *InternalKey, val LazyValue) error
    2863           1 :         tb := tokenbucket.TokenBucket{}
    2864           1 : 
    2865           1 :         if opts.LimitBytesPerSecond != 0 {
    2866           0 :                 // Each "token" roughly corresponds to a byte that was read.
    2867           0 :                 tb.Init(tokenbucket.TokensPerSecond(opts.LimitBytesPerSecond), tokenbucket.Tokens(1024))
    2868           0 :                 rateLimitFunc = func(key *InternalKey, val LazyValue) error {
    2869           0 :                         return tb.WaitCtx(ctx, tokenbucket.Tokens(key.Size()+val.Len()))
    2870           0 :                 }
    2871             :         }
    2872             : 
    2873           1 :         scanInternalOpts := &scanInternalOptions{
    2874           1 :                 visitPointKey: func(key *InternalKey, value LazyValue, iterInfo IteratorLevel) error {
    2875           1 :                         // If the previous key is equal to the current point key, the current key was
    2876           1 :                         // pinned by a snapshot.
    2877           1 :                         size := uint64(key.Size())
    2878           1 :                         kind := key.Kind()
    2879           1 :                         sameKey := d.equal(prevKey.UserKey, key.UserKey)
    2880           1 :                         if iterInfo.Kind == IteratorLevelLSM && sameKey {
    2881           1 :                                 stats.Levels[iterInfo.Level].SnapshotPinnedKeys++
    2882           1 :                                 stats.Levels[iterInfo.Level].SnapshotPinnedKeysBytes += size
    2883           1 :                                 stats.Accumulated.SnapshotPinnedKeys++
    2884           1 :                                 stats.Accumulated.SnapshotPinnedKeysBytes += size
    2885           1 :                         }
    2886           1 :                         if iterInfo.Kind == IteratorLevelLSM {
    2887           1 :                                 stats.Levels[iterInfo.Level].KindsCount[kind]++
    2888           1 :                         }
    2889           1 :                         if !sameKey {
    2890           1 :                                 if iterInfo.Kind == IteratorLevelLSM {
    2891           1 :                                         stats.Levels[iterInfo.Level].LatestKindsCount[kind]++
    2892           1 :                                 }
    2893           1 :                                 stats.Accumulated.LatestKindsCount[kind]++
    2894             :                         }
    2895             : 
    2896           1 :                         stats.Accumulated.KindsCount[kind]++
    2897           1 :                         prevKey.CopyFrom(*key)
    2898           1 :                         stats.BytesRead += uint64(key.Size() + value.Len())
    2899           1 :                         return nil
    2900             :                 },
    2901           0 :                 visitRangeDel: func(start, end []byte, seqNum uint64) error {
    2902           0 :                         stats.Accumulated.KindsCount[InternalKeyKindRangeDelete]++
    2903           0 :                         stats.BytesRead += uint64(len(start) + len(end))
    2904           0 :                         return nil
    2905           0 :                 },
    2906           0 :                 visitRangeKey: func(start, end []byte, keys []rangekey.Key) error {
    2907           0 :                         stats.BytesRead += uint64(len(start) + len(end))
    2908           0 :                         for _, key := range keys {
    2909           0 :                                 stats.Accumulated.KindsCount[key.Kind()]++
    2910           0 :                                 stats.BytesRead += uint64(len(key.Value) + len(key.Suffix))
    2911           0 :                         }
    2912           0 :                         return nil
    2913             :                 },
    2914             :                 includeObsoleteKeys: true,
    2915             :                 IterOptions: IterOptions{
    2916             :                         KeyTypes:   IterKeyTypePointsAndRanges,
    2917             :                         LowerBound: lower,
    2918             :                         UpperBound: upper,
    2919             :                 },
    2920             :                 rateLimitFunc: rateLimitFunc,
    2921             :         }
    2922           1 :         iter := d.newInternalIter(ctx, snapshotIterOpts{}, scanInternalOpts)
    2923           1 :         defer iter.close()
    2924           1 : 
    2925           1 :         err := scanInternalImpl(ctx, lower, upper, iter, scanInternalOpts)
    2926           1 : 
    2927           1 :         if err != nil {
    2928           0 :                 return LSMKeyStatistics{}, err
    2929           0 :         }
    2930             : 
    2931           1 :         return stats, nil
    2932             : }
    2933             : 
    2934             : // ObjProvider returns the objstorage.Provider for this database. Meant to be
    2935             : // used for internal purposes only.
    2936           2 : func (d *DB) ObjProvider() objstorage.Provider {
    2937           2 :         return d.objProvider
    2938           2 : }
    2939             : 
    2940           1 : func (d *DB) checkVirtualBounds(m *fileMetadata) {
    2941           1 :         if !invariants.Enabled {
    2942           0 :                 return
    2943           0 :         }
    2944             : 
    2945           1 :         objMeta, err := d.objProvider.Lookup(fileTypeTable, m.FileBacking.DiskFileNum)
    2946           1 :         if err != nil {
    2947           0 :                 panic(err)
    2948             :         }
    2949           1 :         if objMeta.IsExternal() {
    2950           0 :                 // Nothing to do; bounds are expected to be loose.
    2951           0 :                 return
    2952           0 :         }
    2953             : 
    2954           1 :         if m.HasPointKeys {
    2955           1 :                 pointIter, rangeDelIter, err := d.newIters(context.TODO(), m, nil, internalIterOpts{})
    2956           1 :                 if err != nil {
    2957           0 :                         panic(errors.Wrap(err, "pebble: error creating point iterator"))
    2958             :                 }
    2959             : 
    2960           1 :                 defer pointIter.Close()
    2961           1 :                 if rangeDelIter != nil {
    2962           1 :                         defer rangeDelIter.Close()
    2963           1 :                 }
    2964             : 
    2965           1 :                 pointKey, _ := pointIter.First()
    2966           1 :                 var rangeDel *keyspan.Span
    2967           1 :                 if rangeDelIter != nil {
    2968           1 :                         rangeDel = rangeDelIter.First()
    2969           1 :                 }
    2970             : 
    2971             :                 // Check that the lower bound is tight.
    2972           1 :                 if (rangeDel == nil || d.cmp(rangeDel.SmallestKey().UserKey, m.SmallestPointKey.UserKey) != 0) &&
    2973           1 :                         (pointKey == nil || d.cmp(pointKey.UserKey, m.SmallestPointKey.UserKey) != 0) {
    2974           0 :                         panic(errors.Newf("pebble: virtual sstable %s lower point key bound is not tight", m.FileNum))
    2975             :                 }
    2976             : 
    2977           1 :                 pointKey, _ = pointIter.Last()
    2978           1 :                 rangeDel = nil
    2979           1 :                 if rangeDelIter != nil {
    2980           1 :                         rangeDel = rangeDelIter.Last()
    2981           1 :                 }
    2982             : 
    2983             :                 // Check that the upper bound is tight.
    2984           1 :                 if (rangeDel == nil || d.cmp(rangeDel.LargestKey().UserKey, m.LargestPointKey.UserKey) != 0) &&
    2985           1 :                         (pointKey == nil || d.cmp(pointKey.UserKey, m.LargestPointKey.UserKey) != 0) {
    2986           0 :                         panic(errors.Newf("pebble: virtual sstable %s upper point key bound is not tight", m.FileNum))
    2987             :                 }
    2988             : 
    2989             :                 // Check that iterator keys are within bounds.
    2990           1 :                 for key, _ := pointIter.First(); key != nil; key, _ = pointIter.Next() {
    2991           1 :                         if d.cmp(key.UserKey, m.SmallestPointKey.UserKey) < 0 || d.cmp(key.UserKey, m.LargestPointKey.UserKey) > 0 {
    2992           0 :                                 panic(errors.Newf("pebble: virtual sstable %s point key %s is not within bounds", m.FileNum, key.UserKey))
    2993             :                         }
    2994             :                 }
    2995             : 
    2996           1 :                 if rangeDelIter != nil {
    2997           1 :                         for key := rangeDelIter.First(); key != nil; key = rangeDelIter.Next() {
    2998           1 :                                 if d.cmp(key.SmallestKey().UserKey, m.SmallestPointKey.UserKey) < 0 {
    2999           0 :                                         panic(errors.Newf("pebble: virtual sstable %s point key %s is not within bounds", m.FileNum, key.SmallestKey().UserKey))
    3000             :                                 }
    3001             : 
    3002           1 :                                 if d.cmp(key.LargestKey().UserKey, m.LargestPointKey.UserKey) > 0 {
    3003           0 :                                         panic(errors.Newf("pebble: virtual sstable %s point key %s is not within bounds", m.FileNum, key.LargestKey().UserKey))
    3004             :                                 }
    3005             :                         }
    3006             :                 }
    3007             :         }
    3008             : 
    3009           1 :         if !m.HasRangeKeys {
    3010           1 :                 return
    3011           1 :         }
    3012             : 
    3013           0 :         rangeKeyIter, err := d.tableNewRangeKeyIter(m, keyspan.SpanIterOptions{})
    3014           0 :         defer rangeKeyIter.Close()
    3015           0 : 
    3016           0 :         if err != nil {
    3017           0 :                 panic(errors.Wrap(err, "pebble: error creating range key iterator"))
    3018             :         }
    3019             : 
    3020             :         // Check that the lower bound is tight.
    3021           0 :         if d.cmp(rangeKeyIter.First().SmallestKey().UserKey, m.SmallestRangeKey.UserKey) != 0 {
    3022           0 :                 panic(errors.Newf("pebble: virtual sstable %s lower range key bound is not tight", m.FileNum))
    3023             :         }
    3024             : 
    3025             :         // Check that upper bound is tight.
    3026           0 :         if d.cmp(rangeKeyIter.Last().LargestKey().UserKey, m.LargestRangeKey.UserKey) != 0 {
    3027           0 :                 panic(errors.Newf("pebble: virtual sstable %s upper range key bound is not tight", m.FileNum))
    3028             :         }
    3029             : 
    3030           0 :         for key := rangeKeyIter.First(); key != nil; key = rangeKeyIter.Next() {
    3031           0 :                 if d.cmp(key.SmallestKey().UserKey, m.SmallestRangeKey.UserKey) < 0 {
    3032           0 :                         panic(errors.Newf("pebble: virtual sstable %s point key %s is not within bounds", m.FileNum, key.SmallestKey().UserKey))
    3033             :                 }
    3034           0 :                 if d.cmp(key.LargestKey().UserKey, m.LargestRangeKey.UserKey) > 0 {
    3035           0 :                         panic(errors.Newf("pebble: virtual sstable %s point key %s is not within bounds", m.FileNum, key.LargestKey().UserKey))
    3036             :                 }
    3037             :         }
    3038             : }

Generated by: LCOV version 1.14