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

Generated by: LCOV version 2.0-1