LCOV - code coverage report
Current view: top level - pebble - options.go (source / functions) Coverage Total Hit
Test: 2025-07-07 08:18Z 6f57a213 - tests only.lcov Lines: 89.7 % 1187 1065
Test Date: 2025-07-07 08:19:55 Functions: - 0 0

            Line data    Source code
       1              : // Copyright 2011 The LevelDB-Go and Pebble Authors. All rights reserved. Use
       2              : // of this source code is governed by a BSD-style license that can be found in
       3              : // the LICENSE file.
       4              : 
       5              : package pebble
       6              : 
       7              : import (
       8              :         "bytes"
       9              :         "fmt"
      10              :         "io"
      11              :         "regexp"
      12              :         "runtime"
      13              :         "slices"
      14              :         "sort"
      15              :         "strconv"
      16              :         "strings"
      17              :         "time"
      18              :         "unicode"
      19              : 
      20              :         "github.com/cockroachdb/crlib/fifo"
      21              :         "github.com/cockroachdb/errors"
      22              :         "github.com/cockroachdb/pebble/internal/base"
      23              :         "github.com/cockroachdb/pebble/internal/cache"
      24              :         "github.com/cockroachdb/pebble/internal/humanize"
      25              :         "github.com/cockroachdb/pebble/internal/keyspan"
      26              :         "github.com/cockroachdb/pebble/internal/manifest"
      27              :         "github.com/cockroachdb/pebble/internal/testkeys"
      28              :         "github.com/cockroachdb/pebble/objstorage/objstorageprovider"
      29              :         "github.com/cockroachdb/pebble/objstorage/remote"
      30              :         "github.com/cockroachdb/pebble/rangekey"
      31              :         "github.com/cockroachdb/pebble/sstable"
      32              :         "github.com/cockroachdb/pebble/sstable/blob"
      33              :         "github.com/cockroachdb/pebble/sstable/block"
      34              :         "github.com/cockroachdb/pebble/sstable/colblk"
      35              :         "github.com/cockroachdb/pebble/vfs"
      36              :         "github.com/cockroachdb/pebble/wal"
      37              :         "github.com/cockroachdb/redact"
      38              : )
      39              : 
      40              : const (
      41              :         cacheDefaultSize       = 8 << 20 // 8 MB
      42              :         defaultLevelMultiplier = 10
      43              : )
      44              : 
      45              : // FilterType exports the base.FilterType type.
      46              : type FilterType = base.FilterType
      47              : 
      48              : // Exported TableFilter constants.
      49              : const (
      50              :         TableFilter = base.TableFilter
      51              : )
      52              : 
      53              : // FilterWriter exports the base.FilterWriter type.
      54              : type FilterWriter = base.FilterWriter
      55              : 
      56              : // FilterPolicy exports the base.FilterPolicy type.
      57              : type FilterPolicy = base.FilterPolicy
      58              : 
      59              : var NoFilterPolicy = base.NoFilterPolicy
      60              : 
      61              : // KeySchema exports the colblk.KeySchema type.
      62              : type KeySchema = colblk.KeySchema
      63              : 
      64              : // BlockPropertyCollector exports the sstable.BlockPropertyCollector type.
      65              : type BlockPropertyCollector = sstable.BlockPropertyCollector
      66              : 
      67              : // BlockPropertyFilter exports the sstable.BlockPropertyFilter type.
      68              : type BlockPropertyFilter = base.BlockPropertyFilter
      69              : 
      70              : // ShortAttributeExtractor exports the base.ShortAttributeExtractor type.
      71              : type ShortAttributeExtractor = base.ShortAttributeExtractor
      72              : 
      73              : // UserKeyPrefixBound exports the sstable.UserKeyPrefixBound type.
      74              : type UserKeyPrefixBound = sstable.UserKeyPrefixBound
      75              : 
      76              : // IterKeyType configures which types of keys an iterator should surface.
      77              : type IterKeyType int8
      78              : 
      79              : const (
      80              :         // IterKeyTypePointsOnly configures an iterator to iterate over point keys
      81              :         // only.
      82              :         IterKeyTypePointsOnly IterKeyType = iota
      83              :         // IterKeyTypeRangesOnly configures an iterator to iterate over range keys
      84              :         // only.
      85              :         IterKeyTypeRangesOnly
      86              :         // IterKeyTypePointsAndRanges configures an iterator iterate over both point
      87              :         // keys and range keys simultaneously.
      88              :         IterKeyTypePointsAndRanges
      89              : )
      90              : 
      91              : // String implements fmt.Stringer.
      92            1 : func (t IterKeyType) String() string {
      93            1 :         switch t {
      94            1 :         case IterKeyTypePointsOnly:
      95            1 :                 return "points-only"
      96            1 :         case IterKeyTypeRangesOnly:
      97            1 :                 return "ranges-only"
      98            1 :         case IterKeyTypePointsAndRanges:
      99            1 :                 return "points-and-ranges"
     100            0 :         default:
     101            0 :                 panic(fmt.Sprintf("unknown key type %d", t))
     102              :         }
     103              : }
     104              : 
     105              : // IterOptions hold the optional per-query parameters for NewIter.
     106              : //
     107              : // Like Options, a nil *IterOptions is valid and means to use the default
     108              : // values.
     109              : type IterOptions struct {
     110              :         // LowerBound specifies the smallest key (inclusive) that the iterator will
     111              :         // return during iteration. If the iterator is seeked or iterated past this
     112              :         // boundary the iterator will return Valid()==false. Setting LowerBound
     113              :         // effectively truncates the key space visible to the iterator.
     114              :         LowerBound []byte
     115              :         // UpperBound specifies the largest key (exclusive) that the iterator will
     116              :         // return during iteration. If the iterator is seeked or iterated past this
     117              :         // boundary the iterator will return Valid()==false. Setting UpperBound
     118              :         // effectively truncates the key space visible to the iterator.
     119              :         UpperBound []byte
     120              :         // SkipPoint may be used to skip over point keys that don't match an
     121              :         // arbitrary predicate during iteration. If set, the Iterator invokes
     122              :         // SkipPoint for keys encountered. If SkipPoint returns true, the iterator
     123              :         // will skip the key without yielding it to the iterator operation in
     124              :         // progress.
     125              :         //
     126              :         // SkipPoint must be a pure function and always return the same result when
     127              :         // provided the same arguments. The iterator may call SkipPoint multiple
     128              :         // times for the same user key.
     129              :         SkipPoint func(userKey []byte) bool
     130              :         // PointKeyFilters can be used to avoid scanning tables and blocks in tables
     131              :         // when iterating over point keys. This slice represents an intersection
     132              :         // across all filters, i.e., all filters must indicate that the block is
     133              :         // relevant.
     134              :         //
     135              :         // Performance note: When len(PointKeyFilters) > 0, the caller should ensure
     136              :         // that cap(PointKeyFilters) is at least len(PointKeyFilters)+1. This helps
     137              :         // avoid allocations in Pebble internal code that mutates the slice.
     138              :         PointKeyFilters []BlockPropertyFilter
     139              :         // RangeKeyFilters can be usefd to avoid scanning tables and blocks in tables
     140              :         // when iterating over range keys. The same requirements that apply to
     141              :         // PointKeyFilters apply here too.
     142              :         RangeKeyFilters []BlockPropertyFilter
     143              :         // KeyTypes configures which types of keys to iterate over: point keys,
     144              :         // range keys, or both.
     145              :         KeyTypes IterKeyType
     146              :         // RangeKeyMasking can be used to enable automatic masking of point keys by
     147              :         // range keys. Range key masking is only supported during combined range key
     148              :         // and point key iteration mode (IterKeyTypePointsAndRanges).
     149              :         RangeKeyMasking RangeKeyMasking
     150              : 
     151              :         // OnlyReadGuaranteedDurable is an advanced option that is only supported by
     152              :         // the Reader implemented by DB. When set to true, only the guaranteed to be
     153              :         // durable state is visible in the iterator.
     154              :         // - This definition is made under the assumption that the FS implementation
     155              :         //   is providing a durability guarantee when data is synced.
     156              :         // - The visible state represents a consistent point in the history of the
     157              :         //   DB.
     158              :         // - The implementation is free to choose a conservative definition of what
     159              :         //   is guaranteed durable. For simplicity, the current implementation
     160              :         //   ignores memtables. A more sophisticated implementation could track the
     161              :         //   highest seqnum that is synced to the WAL and published and use that as
     162              :         //   the visible seqnum for an iterator. Note that the latter approach is
     163              :         //   not strictly better than the former since we can have DBs that are (a)
     164              :         //   synced more rarely than memtable flushes, (b) have no WAL. (a) is
     165              :         //   likely to be true in a future CockroachDB context where the DB
     166              :         //   containing the state machine may be rarely synced.
     167              :         // NB: this current implementation relies on the fact that memtables are
     168              :         // flushed in seqnum order, and any ingested sstables that happen to have a
     169              :         // lower seqnum than a non-flushed memtable don't have any overlapping keys.
     170              :         // This is the fundamental level invariant used in other code too, like when
     171              :         // merging iterators.
     172              :         //
     173              :         // Semantically, using this option provides the caller a "snapshot" as of
     174              :         // the time the most recent memtable was flushed. An alternate interface
     175              :         // would be to add a NewSnapshot variant. Creating a snapshot is heavier
     176              :         // weight than creating an iterator, so we have opted to support this
     177              :         // iterator option.
     178              :         OnlyReadGuaranteedDurable bool
     179              :         // UseL6Filters allows the caller to opt into reading filter blocks for L6
     180              :         // sstables. Helpful if a lot of SeekPrefixGEs are expected in quick
     181              :         // succession, that are also likely to not yield a single key. Filter blocks in
     182              :         // L6 can be relatively large, often larger than data blocks, so the benefit of
     183              :         // loading them in the cache is minimized if the probability of the key
     184              :         // existing is not low or if we just expect a one-time Seek (where loading the
     185              :         // data block directly is better).
     186              :         UseL6Filters bool
     187              :         // Category is used for categorized iterator stats. This should not be
     188              :         // changed by calling SetOptions.
     189              :         Category block.Category
     190              : 
     191              :         DebugRangeKeyStack bool
     192              : 
     193              :         // Internal options.
     194              : 
     195              :         logger Logger
     196              :         // Layer corresponding to this file. Only passed in if constructed by a
     197              :         // levelIter.
     198              :         layer manifest.Layer
     199              :         // disableLazyCombinedIteration is an internal testing option.
     200              :         disableLazyCombinedIteration bool
     201              :         // snapshotForHideObsoletePoints is specified for/by levelIter when opening
     202              :         // files and is used to decide whether to hide obsolete points. A value of 0
     203              :         // implies obsolete points should not be hidden.
     204              :         snapshotForHideObsoletePoints base.SeqNum
     205              : 
     206              :         // NB: If adding new Options, you must account for them in iterator
     207              :         // construction and Iterator.SetOptions.
     208              : }
     209              : 
     210              : // GetLowerBound returns the LowerBound or nil if the receiver is nil.
     211            1 : func (o *IterOptions) GetLowerBound() []byte {
     212            1 :         if o == nil {
     213            1 :                 return nil
     214            1 :         }
     215            1 :         return o.LowerBound
     216              : }
     217              : 
     218              : // GetUpperBound returns the UpperBound or nil if the receiver is nil.
     219            1 : func (o *IterOptions) GetUpperBound() []byte {
     220            1 :         if o == nil {
     221            1 :                 return nil
     222            1 :         }
     223            1 :         return o.UpperBound
     224              : }
     225              : 
     226            1 : func (o *IterOptions) pointKeys() bool {
     227            1 :         if o == nil {
     228            0 :                 return true
     229            0 :         }
     230            1 :         return o.KeyTypes == IterKeyTypePointsOnly || o.KeyTypes == IterKeyTypePointsAndRanges
     231              : }
     232              : 
     233            1 : func (o *IterOptions) rangeKeys() bool {
     234            1 :         if o == nil {
     235            0 :                 return false
     236            0 :         }
     237            1 :         return o.KeyTypes == IterKeyTypeRangesOnly || o.KeyTypes == IterKeyTypePointsAndRanges
     238              : }
     239              : 
     240            1 : func (o *IterOptions) getLogger() Logger {
     241            1 :         if o == nil || o.logger == nil {
     242            1 :                 return DefaultLogger
     243            1 :         }
     244            1 :         return o.logger
     245              : }
     246              : 
     247              : // SpanIterOptions creates a SpanIterOptions from this IterOptions.
     248            1 : func (o *IterOptions) SpanIterOptions() keyspan.SpanIterOptions {
     249            1 :         if o == nil {
     250            1 :                 return keyspan.SpanIterOptions{}
     251            1 :         }
     252            1 :         return keyspan.SpanIterOptions{
     253            1 :                 RangeKeyFilters: o.RangeKeyFilters,
     254            1 :         }
     255              : }
     256              : 
     257              : // scanInternalOptions is similar to IterOptions, meant for use with
     258              : // scanInternalIterator.
     259              : type scanInternalOptions struct {
     260              :         IterOptions
     261              : 
     262              :         category block.Category
     263              : 
     264              :         visitPointKey     func(key *InternalKey, value LazyValue, iterInfo IteratorLevel) error
     265              :         visitRangeDel     func(start, end []byte, seqNum SeqNum) error
     266              :         visitRangeKey     func(start, end []byte, keys []rangekey.Key) error
     267              :         visitSharedFile   func(sst *SharedSSTMeta) error
     268              :         visitExternalFile func(sst *ExternalFile) error
     269              : 
     270              :         // includeObsoleteKeys specifies whether keys shadowed by newer internal keys
     271              :         // are exposed. If false, only one internal key per user key is exposed.
     272              :         includeObsoleteKeys bool
     273              : 
     274              :         // rateLimitFunc is used to limit the amount of bytes read per second.
     275              :         rateLimitFunc func(key *InternalKey, value LazyValue) error
     276              : }
     277              : 
     278              : // RangeKeyMasking configures automatic hiding of point keys by range keys. A
     279              : // non-nil Suffix enables range-key masking. When enabled, range keys with
     280              : // suffixes ≥ Suffix behave as masks. All point keys that are contained within a
     281              : // masking range key's bounds and have suffixes greater than the range key's
     282              : // suffix are automatically skipped.
     283              : //
     284              : // Specifically, when configured with a RangeKeyMasking.Suffix _s_, and there
     285              : // exists a range key with suffix _r_ covering a point key with suffix _p_, and
     286              : //
     287              : //      _s_ ≤ _r_ < _p_
     288              : //
     289              : // then the point key is elided.
     290              : //
     291              : // Range-key masking may only be used when iterating over both point keys and
     292              : // range keys with IterKeyTypePointsAndRanges.
     293              : type RangeKeyMasking struct {
     294              :         // Suffix configures which range keys may mask point keys. Only range keys
     295              :         // that are defined at suffixes greater than or equal to Suffix will mask
     296              :         // point keys.
     297              :         Suffix []byte
     298              :         // Filter is an optional field that may be used to improve performance of
     299              :         // range-key masking through a block-property filter defined over key
     300              :         // suffixes. If non-nil, Filter is called by Pebble to construct a
     301              :         // block-property filter mask at iterator creation. The filter is used to
     302              :         // skip whole point-key blocks containing point keys with suffixes greater
     303              :         // than a covering range-key's suffix.
     304              :         //
     305              :         // To use this functionality, the caller must create and configure (through
     306              :         // Options.BlockPropertyCollectors) a block-property collector that records
     307              :         // the maxmimum suffix contained within a block. The caller then must write
     308              :         // and provide a BlockPropertyFilterMask implementation on that same
     309              :         // property. See the BlockPropertyFilterMask type for more information.
     310              :         Filter func() BlockPropertyFilterMask
     311              : }
     312              : 
     313              : // BlockPropertyFilterMask extends the BlockPropertyFilter interface for use
     314              : // with range-key masking. Unlike an ordinary block property filter, a
     315              : // BlockPropertyFilterMask's filtering criteria is allowed to change when Pebble
     316              : // invokes its SetSuffix method.
     317              : //
     318              : // When a Pebble iterator steps into a range key's bounds and the range key has
     319              : // a suffix greater than or equal to RangeKeyMasking.Suffix, the range key acts
     320              : // as a mask. The masking range key hides all point keys that fall within the
     321              : // range key's bounds and have suffixes > the range key's suffix. Without a
     322              : // filter mask configured, Pebble performs this hiding by stepping through point
     323              : // keys and comparing suffixes. If large numbers of point keys are masked, this
     324              : // requires Pebble to load, iterate through and discard a large number of
     325              : // sstable blocks containing masked point keys.
     326              : //
     327              : // If a block-property collector and a filter mask are configured, Pebble may
     328              : // skip loading some point-key blocks altogether. If a block's keys are known to
     329              : // all fall within the bounds of the masking range key and the block was
     330              : // annotated by a block-property collector with the maximal suffix, Pebble can
     331              : // ask the filter mask to compare the property to the current masking range
     332              : // key's suffix. If the mask reports no intersection, the block may be skipped.
     333              : //
     334              : // If unsuffixed and suffixed keys are written to the database, care must be
     335              : // taken to avoid unintentionally masking un-suffixed keys located in the same
     336              : // block as suffixed keys. One solution is to interpret unsuffixed keys as
     337              : // containing the maximal suffix value, ensuring that blocks containing
     338              : // unsuffixed keys are always loaded.
     339              : type BlockPropertyFilterMask interface {
     340              :         BlockPropertyFilter
     341              : 
     342              :         // SetSuffix configures the mask with the suffix of a range key. The filter
     343              :         // should return false from Intersects whenever it's provided with a
     344              :         // property encoding a block's minimum suffix that's greater (according to
     345              :         // Compare) than the provided suffix.
     346              :         SetSuffix(suffix []byte) error
     347              : }
     348              : 
     349              : // WriteOptions hold the optional per-query parameters for Set and Delete
     350              : // operations.
     351              : //
     352              : // Like Options, a nil *WriteOptions is valid and means to use the default
     353              : // values.
     354              : type WriteOptions struct {
     355              :         // Sync is whether to sync writes through the OS buffer cache and down onto
     356              :         // the actual disk, if applicable. Setting Sync is required for durability of
     357              :         // individual write operations but can result in slower writes.
     358              :         //
     359              :         // If false, and the process or machine crashes, then a recent write may be
     360              :         // lost. This is due to the recently written data being buffered inside the
     361              :         // process running Pebble. This differs from the semantics of a write system
     362              :         // call in which the data is buffered in the OS buffer cache and would thus
     363              :         // survive a process crash.
     364              :         //
     365              :         // The default value is true.
     366              :         Sync bool
     367              : }
     368              : 
     369              : // Sync specifies the default write options for writes which synchronize to
     370              : // disk.
     371              : var Sync = &WriteOptions{Sync: true}
     372              : 
     373              : // NoSync specifies the default write options for writes which do not
     374              : // synchronize to disk.
     375              : var NoSync = &WriteOptions{Sync: false}
     376              : 
     377              : // GetSync returns the Sync value or true if the receiver is nil.
     378            1 : func (o *WriteOptions) GetSync() bool {
     379            1 :         return o == nil || o.Sync
     380            1 : }
     381              : 
     382              : // LevelOptions holds the optional per-level parameters.
     383              : type LevelOptions struct {
     384              :         // BlockRestartInterval is the number of keys between restart points
     385              :         // for delta encoding of keys.
     386              :         //
     387              :         // The default value is 16 for L0, and the value from the previous level for
     388              :         // all other levels.
     389              :         BlockRestartInterval int
     390              : 
     391              :         // BlockSize is the target uncompressed size in bytes of each table block.
     392              :         //
     393              :         // The default value is 4096 for L0, and the value from the previous level for
     394              :         // all other levels.
     395              :         BlockSize int
     396              : 
     397              :         // BlockSizeThreshold finishes a block if the block size is larger than the
     398              :         // specified percentage of the target block size and adding the next entry
     399              :         // would cause the block to be larger than the target block size.
     400              :         //
     401              :         // The default value is 90 for L0, and the value from the previous level for
     402              :         // all other levels.
     403              :         BlockSizeThreshold int
     404              : 
     405              :         // Compression defines the per-block compression to use.
     406              :         //
     407              :         // The default value is Snappy for L0, or the function from the previous level
     408              :         // for all other levels.
     409              :         //
     410              :         // ApplyCompressionSettings can be used to initialize this field for all levels.
     411              :         Compression func() *sstable.CompressionProfile
     412              : 
     413              :         // FilterPolicy defines a filter algorithm (such as a Bloom filter) that can
     414              :         // reduce disk reads for Get calls.
     415              :         //
     416              :         // One such implementation is bloom.FilterPolicy(10) from the pebble/bloom
     417              :         // package.
     418              :         //
     419              :         // The default value for L0 is NoFilterPolicy (no filter), and the value from
     420              :         // the previous level for all other levels.
     421              :         FilterPolicy FilterPolicy
     422              : 
     423              :         // FilterType is a legacy field. The default and only possible value is
     424              :         // TableFilter.
     425              :         FilterType FilterType
     426              : 
     427              :         // IndexBlockSize is the target uncompressed size in bytes of each index
     428              :         // block. When the index block size is larger than this target, two-level
     429              :         // indexes are automatically enabled. Setting this option to a large value
     430              :         // (such as math.MaxInt32) disables the automatic creation of two-level
     431              :         // indexes.
     432              :         //
     433              :         // The default value is the value of BlockSize for L0, or the value from the
     434              :         // previous level for all other levels.
     435              :         IndexBlockSize int
     436              : }
     437              : 
     438              : // EnsureL0Defaults ensures that the L0 default values for the options have been
     439              : // initialized.
     440            1 : func (o *LevelOptions) EnsureL0Defaults() {
     441            1 :         if o.BlockRestartInterval <= 0 {
     442            1 :                 o.BlockRestartInterval = base.DefaultBlockRestartInterval
     443            1 :         }
     444            1 :         if o.BlockSize <= 0 {
     445            1 :                 o.BlockSize = base.DefaultBlockSize
     446            1 :         } else if o.BlockSize > sstable.MaximumRestartOffset {
     447            0 :                 panic(errors.Errorf("BlockSize %d exceeds MaximumRestartOffset", o.BlockSize))
     448              :         }
     449            1 :         if o.BlockSizeThreshold <= 0 {
     450            1 :                 o.BlockSizeThreshold = base.DefaultBlockSizeThreshold
     451            1 :         }
     452            1 :         if o.Compression == nil {
     453            1 :                 o.Compression = func() *sstable.CompressionProfile { return sstable.SnappyCompression }
     454              :         }
     455            1 :         if o.FilterPolicy == nil {
     456            1 :                 o.FilterPolicy = NoFilterPolicy
     457            1 :         }
     458            1 :         if o.IndexBlockSize <= 0 {
     459            1 :                 o.IndexBlockSize = o.BlockSize
     460            1 :         }
     461              : }
     462              : 
     463              : // EnsureL1PlusDefaults ensures that the L1+ default values for the options have
     464              : // been initialized. Requires the fully initialized options for the level above.
     465            1 : func (o *LevelOptions) EnsureL1PlusDefaults(previousLevel *LevelOptions) {
     466            1 :         if o.BlockRestartInterval <= 0 {
     467            1 :                 o.BlockRestartInterval = previousLevel.BlockRestartInterval
     468            1 :         }
     469            1 :         if o.BlockSize <= 0 {
     470            1 :                 o.BlockSize = previousLevel.BlockSize
     471            1 :         } else if o.BlockSize > sstable.MaximumRestartOffset {
     472            0 :                 panic(errors.Errorf("BlockSize %d exceeds MaximumRestartOffset", o.BlockSize))
     473              :         }
     474            1 :         if o.BlockSizeThreshold <= 0 {
     475            1 :                 o.BlockSizeThreshold = previousLevel.BlockSizeThreshold
     476            1 :         }
     477            1 :         if o.Compression == nil {
     478            1 :                 o.Compression = previousLevel.Compression
     479            1 :         }
     480            1 :         if o.FilterPolicy == nil {
     481            1 :                 o.FilterPolicy = previousLevel.FilterPolicy
     482            1 :         }
     483            1 :         if o.IndexBlockSize <= 0 {
     484            1 :                 o.IndexBlockSize = previousLevel.IndexBlockSize
     485            1 :         }
     486              : }
     487              : 
     488              : // Options holds the optional parameters for configuring pebble. These options
     489              : // apply to the DB at large; per-query options are defined by the IterOptions
     490              : // and WriteOptions types.
     491              : type Options struct {
     492              :         // Sync sstables periodically in order to smooth out writes to disk. This
     493              :         // option does not provide any persistency guarantee, but is used to avoid
     494              :         // latency spikes if the OS automatically decides to write out a large chunk
     495              :         // of dirty filesystem buffers. This option only controls SSTable syncs; WAL
     496              :         // syncs are controlled by WALBytesPerSync.
     497              :         //
     498              :         // The default value is 512KB.
     499              :         BytesPerSync int
     500              : 
     501              :         // Cache is used to cache uncompressed blocks from sstables. If it is nil,
     502              :         // a block cache of CacheSize will be created for each DB.
     503              :         Cache *cache.Cache
     504              :         // CacheSize is used when Cache is not set. The default value is 8 MB.
     505              :         CacheSize int64
     506              : 
     507              :         // LoadBlockSema, if set, is used to limit the number of blocks that can be
     508              :         // loaded (i.e. read from the filesystem) in parallel. Each load acquires one
     509              :         // unit from the semaphore for the duration of the read.
     510              :         LoadBlockSema *fifo.Semaphore
     511              : 
     512              :         // Cleaner cleans obsolete files.
     513              :         //
     514              :         // The default cleaner uses the DeleteCleaner.
     515              :         Cleaner Cleaner
     516              : 
     517              :         // Local contains option that pertain to files stored on the local filesystem.
     518              :         Local struct {
     519              :                 // ReadaheadConfig is used to retrieve the current readahead mode; it is
     520              :                 // consulted whenever a read handle is initialized.
     521              :                 ReadaheadConfig *ReadaheadConfig
     522              : 
     523              :                 // TODO(radu): move BytesPerSync, LoadBlockSema, Cleaner here.
     524              :         }
     525              : 
     526              :         // Comparer defines a total ordering over the space of []byte keys: a 'less
     527              :         // than' relationship. The same comparison algorithm must be used for reads
     528              :         // and writes over the lifetime of the DB.
     529              :         //
     530              :         // The default value uses the same ordering as bytes.Compare.
     531              :         Comparer *Comparer
     532              : 
     533              :         // DebugCheck is invoked, if non-nil, whenever a new version is being
     534              :         // installed. Typically, this is set to pebble.DebugCheckLevels in tests
     535              :         // or tools only, to check invariants over all the data in the database.
     536              :         DebugCheck func(*DB) error
     537              : 
     538              :         // Disable the write-ahead log (WAL). Disabling the write-ahead log prohibits
     539              :         // crash recovery, but can improve performance if crash recovery is not
     540              :         // needed (e.g. when only temporary state is being stored in the database).
     541              :         //
     542              :         // TODO(peter): untested
     543              :         DisableWAL bool
     544              : 
     545              :         // ErrorIfExists causes an error on Open if the database already exists.
     546              :         // The error can be checked with errors.Is(err, ErrDBAlreadyExists).
     547              :         //
     548              :         // The default value is false.
     549              :         ErrorIfExists bool
     550              : 
     551              :         // ErrorIfNotExists causes an error on Open if the database does not already
     552              :         // exist. The error can be checked with errors.Is(err, ErrDBDoesNotExist).
     553              :         //
     554              :         // The default value is false which will cause a database to be created if it
     555              :         // does not already exist.
     556              :         ErrorIfNotExists bool
     557              : 
     558              :         // ErrorIfNotPristine causes an error on Open if the database already exists
     559              :         // and any operations have been performed on the database. The error can be
     560              :         // checked with errors.Is(err, ErrDBNotPristine).
     561              :         //
     562              :         // Note that a database that contained keys that were all subsequently deleted
     563              :         // may or may not trigger the error. Currently, we check if there are any live
     564              :         // SSTs or log records to replay.
     565              :         ErrorIfNotPristine bool
     566              : 
     567              :         // EventListener provides hooks to listening to significant DB events such as
     568              :         // flushes, compactions, and table deletion.
     569              :         EventListener *EventListener
     570              : 
     571              :         // Experimental contains experimental options which are off by default.
     572              :         // These options are temporary and will eventually either be deleted, moved
     573              :         // out of the experimental group, or made the non-adjustable default. These
     574              :         // options may change at any time, so do not rely on them.
     575              :         Experimental struct {
     576              :                 // The threshold of L0 read-amplification at which compaction concurrency
     577              :                 // is enabled (if CompactionDebtConcurrency was not already exceeded).
     578              :                 // Every multiple of this value enables another concurrent
     579              :                 // compaction up to CompactionConcurrencyRange.
     580              :                 L0CompactionConcurrency int
     581              : 
     582              :                 // CompactionDebtConcurrency controls the threshold of compaction debt
     583              :                 // at which additional compaction concurrency slots are added. For every
     584              :                 // multiple of this value in compaction debt bytes, an additional
     585              :                 // concurrent compaction is added. This works "on top" of
     586              :                 // L0CompactionConcurrency, so the higher of the count of compaction
     587              :                 // concurrency slots as determined by the two options is chosen.
     588              :                 CompactionDebtConcurrency uint64
     589              : 
     590              :                 // CompactionGarbageFractionForMaxConcurrency is the fraction of garbage
     591              :                 // due to DELs and RANGEDELs that causes MaxConcurrentCompactions to be
     592              :                 // allowed. Concurrent compactions are allowed in a linear manner upto
     593              :                 // this limit being reached. A value <= 0.0 disables adding concurrency
     594              :                 // due to garbage.
     595              :                 CompactionGarbageFractionForMaxConcurrency func() float64
     596              : 
     597              :                 // IngestSplit, if it returns true, allows for ingest-time splitting of
     598              :                 // existing sstables into two virtual sstables to allow ingestion sstables to
     599              :                 // slot into a lower level than they otherwise would have.
     600              :                 IngestSplit func() bool
     601              : 
     602              :                 // ReadCompactionRate controls the frequency of read triggered
     603              :                 // compactions by adjusting `AllowedSeeks` in manifest.TableMetadata:
     604              :                 //
     605              :                 // AllowedSeeks = FileSize / ReadCompactionRate
     606              :                 //
     607              :                 // From LevelDB:
     608              :                 // ```
     609              :                 // We arrange to automatically compact this file after
     610              :                 // a certain number of seeks. Let's assume:
     611              :                 //   (1) One seek costs 10ms
     612              :                 //   (2) Writing or reading 1MB costs 10ms (100MB/s)
     613              :                 //   (3) A compaction of 1MB does 25MB of IO:
     614              :                 //         1MB read from this level
     615              :                 //         10-12MB read from next level (boundaries may be misaligned)
     616              :                 //         10-12MB written to next level
     617              :                 // This implies that 25 seeks cost the same as the compaction
     618              :                 // of 1MB of data.  I.e., one seek costs approximately the
     619              :                 // same as the compaction of 40KB of data.  We are a little
     620              :                 // conservative and allow approximately one seek for every 16KB
     621              :                 // of data before triggering a compaction.
     622              :                 // ```
     623              :                 ReadCompactionRate int64
     624              : 
     625              :                 // ReadSamplingMultiplier is a multiplier for the readSamplingPeriod in
     626              :                 // iterator.maybeSampleRead() to control the frequency of read sampling
     627              :                 // to trigger a read triggered compaction. A value of -1 prevents sampling
     628              :                 // and disables read triggered compactions. The default is 1 << 4. which
     629              :                 // gets multiplied with a constant of 1 << 16 to yield 1 << 20 (1MB).
     630              :                 ReadSamplingMultiplier int64
     631              : 
     632              :                 // NumDeletionsThreshold defines the minimum number of point tombstones
     633              :                 // that must be present in a single data block for that block to be
     634              :                 // considered tombstone-dense for the purposes of triggering a
     635              :                 // tombstone density compaction. Data blocks may also be considered
     636              :                 // tombstone-dense if they meet the criteria defined by
     637              :                 // DeletionSizeRatioThreshold below. Tombstone-dense blocks are identified
     638              :                 // when sstables are written, and so this is effectively an option for
     639              :                 // sstable writers. The default value is 100.
     640              :                 NumDeletionsThreshold int
     641              : 
     642              :                 // DeletionSizeRatioThreshold defines the minimum ratio of the size of
     643              :                 // point tombstones to the size of a data block that must be reached
     644              :                 // for that block to be considered tombstone-dense for the purposes of
     645              :                 // triggering a tombstone density compaction. Data blocks may also be
     646              :                 // considered tombstone-dense if they meet the criteria defined by
     647              :                 // NumDeletionsThreshold above. Tombstone-dense blocks are identified
     648              :                 // when sstables are written, and so this is effectively an option for
     649              :                 // sstable writers. The default value is 0.5.
     650              :                 DeletionSizeRatioThreshold float32
     651              : 
     652              :                 // TombstoneDenseCompactionThreshold is the minimum percent of data
     653              :                 // blocks in a table that must be tombstone-dense for that table to be
     654              :                 // eligible for a tombstone density compaction. It should be defined as a
     655              :                 // ratio out of 1. The default value is 0.10.
     656              :                 //
     657              :                 // If multiple tables are eligible for a tombstone density compaction, then
     658              :                 // tables with a higher percent of tombstone-dense blocks are still
     659              :                 // prioritized for compaction.
     660              :                 //
     661              :                 // A zero or negative value disables tombstone density compactions.
     662              :                 TombstoneDenseCompactionThreshold float64
     663              : 
     664              :                 // FileCacheShards is the number of shards per file cache.
     665              :                 // Reducing the value can reduce the number of idle goroutines per DB
     666              :                 // instance which can be useful in scenarios with a lot of DB instances
     667              :                 // and a large number of CPUs, but doing so can lead to higher contention
     668              :                 // in the file cache and reduced performance.
     669              :                 //
     670              :                 // The default value is the number of logical CPUs, which can be
     671              :                 // limited by runtime.GOMAXPROCS.
     672              :                 FileCacheShards int
     673              : 
     674              :                 // ValidateOnIngest schedules validation of sstables after they have
     675              :                 // been ingested.
     676              :                 //
     677              :                 // By default, this value is false.
     678              :                 ValidateOnIngest bool
     679              : 
     680              :                 // LevelMultiplier configures the size multiplier used to determine the
     681              :                 // desired size of each level of the LSM. Defaults to 10.
     682              :                 LevelMultiplier int
     683              : 
     684              :                 // MultiLevelCompactionHeuristic determines whether to add an additional
     685              :                 // level to a conventional two level compaction.
     686              :                 MultiLevelCompactionHeuristic func() MultiLevelHeuristic
     687              : 
     688              :                 // EnableColumnarBlocks is used to decide whether to enable writing
     689              :                 // TableFormatPebblev5 sstables. This setting is only respected by
     690              :                 // FormatColumnarBlocks. In lower format major versions, the
     691              :                 // TableFormatPebblev5 format is prohibited. If EnableColumnarBlocks is
     692              :                 // nil and the DB is at FormatColumnarBlocks, the DB defaults to not
     693              :                 // writing columnar blocks.
     694              :                 EnableColumnarBlocks func() bool
     695              : 
     696              :                 // EnableValueBlocks is used to decide whether to enable writing
     697              :                 // TableFormatPebblev3 sstables. This setting is only respected by a
     698              :                 // specific subset of format major versions: FormatSSTableValueBlocks,
     699              :                 // FormatFlushableIngest and FormatPrePebblev1MarkedCompacted. In lower
     700              :                 // format major versions, value blocks are never enabled. In higher
     701              :                 // format major versions, value blocks are always enabled.
     702              :                 EnableValueBlocks func() bool
     703              : 
     704              :                 // ShortAttributeExtractor is used iff EnableValueBlocks() returns true
     705              :                 // (else ignored). If non-nil, a ShortAttribute can be extracted from the
     706              :                 // value and stored with the key, when the value is stored elsewhere.
     707              :                 ShortAttributeExtractor ShortAttributeExtractor
     708              : 
     709              :                 // DisableIngestAsFlushable disables lazy ingestion of sstables through
     710              :                 // a WAL write and memtable rotation. Only effectual if the format
     711              :                 // major version is at least `FormatFlushableIngest`.
     712              :                 DisableIngestAsFlushable func() bool
     713              : 
     714              :                 // RemoteStorage enables use of remote storage (e.g. S3) for storing
     715              :                 // sstables. Setting this option enables use of CreateOnShared option and
     716              :                 // allows ingestion of external files.
     717              :                 RemoteStorage remote.StorageFactory
     718              : 
     719              :                 // If CreateOnShared is non-zero, new sstables are created on remote storage
     720              :                 // (using CreateOnSharedLocator and with the appropriate
     721              :                 // CreateOnSharedStrategy). These sstables can be shared between different
     722              :                 // Pebble instances; the lifecycle of such objects is managed by the
     723              :                 // remote.Storage constructed by options.RemoteStorage.
     724              :                 //
     725              :                 // Can only be used when RemoteStorage is set (and recognizes
     726              :                 // CreateOnSharedLocator).
     727              :                 CreateOnShared        remote.CreateOnSharedStrategy
     728              :                 CreateOnSharedLocator remote.Locator
     729              : 
     730              :                 // CacheSizeBytesBytes is the size of the on-disk block cache for objects
     731              :                 // on shared storage in bytes. If it is 0, no cache is used.
     732              :                 SecondaryCacheSizeBytes int64
     733              : 
     734              :                 // EnableDeleteOnlyCompactionExcises enables delete-only compactions to also
     735              :                 // apply delete-only compaction hints on sstables that partially overlap
     736              :                 // with it. This application happens through an excise, similar to
     737              :                 // the excise phase of IngestAndExcise.
     738              :                 EnableDeleteOnlyCompactionExcises func() bool
     739              : 
     740              :                 // CompactionScheduler, if set, is used to limit concurrent compactions as
     741              :                 // well as to pace compactions already chosen. If nil, a default scheduler
     742              :                 // is created and used.
     743              :                 CompactionScheduler CompactionScheduler
     744              : 
     745              :                 UserKeyCategories UserKeyCategories
     746              : 
     747              :                 // ValueSeparationPolicy controls the policy for separating values into
     748              :                 // external blob files. If nil, value separation defaults to disabled.
     749              :                 // The value separation policy is ignored if EnableColumnarBlocks() is
     750              :                 // false.
     751              :                 ValueSeparationPolicy func() ValueSeparationPolicy
     752              : 
     753              :                 // SpanPolicyFunc is used to determine the SpanPolicy for a key region.
     754              :                 SpanPolicyFunc SpanPolicyFunc
     755              :         }
     756              : 
     757              :         // Filters is a map from filter policy name to filter policy. It is used for
     758              :         // debugging tools which may be used on multiple databases configured with
     759              :         // different filter policies. It is not necessary to populate this filters
     760              :         // map during normal usage of a DB (it will be done automatically by
     761              :         // EnsureDefaults).
     762              :         Filters map[string]FilterPolicy
     763              : 
     764              :         // FlushDelayDeleteRange configures how long the database should wait before
     765              :         // forcing a flush of a memtable that contains a range deletion. Disk space
     766              :         // cannot be reclaimed until the range deletion is flushed. No automatic
     767              :         // flush occurs if zero.
     768              :         FlushDelayDeleteRange time.Duration
     769              : 
     770              :         // FlushDelayRangeKey configures how long the database should wait before
     771              :         // forcing a flush of a memtable that contains a range key. Range keys in
     772              :         // the memtable prevent lazy combined iteration, so it's desirable to flush
     773              :         // range keys promptly. No automatic flush occurs if zero.
     774              :         FlushDelayRangeKey time.Duration
     775              : 
     776              :         // FlushSplitBytes denotes the target number of bytes per sublevel in
     777              :         // each flush split interval (i.e. range between two flush split keys)
     778              :         // in L0 sstables. When set to zero, only a single sstable is generated
     779              :         // by each flush. When set to a non-zero value, flushes are split at
     780              :         // points to meet L0's TargetFileSize, any grandparent-related overlap
     781              :         // options, and at boundary keys of L0 flush split intervals (which are
     782              :         // targeted to contain around FlushSplitBytes bytes in each sublevel
     783              :         // between pairs of boundary keys). Splitting sstables during flush
     784              :         // allows increased compaction flexibility and concurrency when those
     785              :         // tables are compacted to lower levels.
     786              :         FlushSplitBytes int64
     787              : 
     788              :         // FormatMajorVersion sets the format of on-disk files. It is
     789              :         // recommended to set the format major version to an explicit
     790              :         // version, as the default may change over time.
     791              :         //
     792              :         // At Open if the existing database is formatted using a later
     793              :         // format major version that is known to this version of Pebble,
     794              :         // Pebble will continue to use the later format major version. If
     795              :         // the existing database's version is unknown, the caller may use
     796              :         // FormatMostCompatible and will be able to open the database
     797              :         // regardless of its actual version.
     798              :         //
     799              :         // If the existing database is formatted using a format major
     800              :         // version earlier than the one specified, Open will automatically
     801              :         // ratchet the database to the specified format major version.
     802              :         FormatMajorVersion FormatMajorVersion
     803              : 
     804              :         // FS provides the interface for persistent file storage.
     805              :         //
     806              :         // The default value uses the underlying operating system's file system.
     807              :         FS vfs.FS
     808              : 
     809              :         // KeySchema is the name of the key schema that should be used when writing
     810              :         // new sstables. There must be a key schema with this name defined in
     811              :         // KeySchemas. If not set, colblk.DefaultKeySchema is used to construct a
     812              :         // default key schema.
     813              :         KeySchema string
     814              : 
     815              :         // KeySchemas defines the set of known schemas of user keys. When columnar
     816              :         // blocks are in use (see FormatColumnarBlocks), the user may specify how a
     817              :         // key should be decomposed into columns. Each KeySchema must have a unique
     818              :         // name. The schema named by Options.KeySchema is used while writing
     819              :         // sstables during flushes and compactions.
     820              :         //
     821              :         // Multiple KeySchemas may be used over the lifetime of a database. Once a
     822              :         // KeySchema is used, it must be provided in KeySchemas in subsequent calls
     823              :         // to Open for perpetuity.
     824              :         KeySchemas sstable.KeySchemas
     825              : 
     826              :         // Lock, if set, must be a database lock acquired through LockDirectory for
     827              :         // the same directory passed to Open. If provided, Open will skip locking
     828              :         // the directory. Closing the database will not release the lock, and it's
     829              :         // the responsibility of the caller to release the lock after closing the
     830              :         // database.
     831              :         //
     832              :         // Open will enforce that the Lock passed locks the same directory passed to
     833              :         // Open. Concurrent calls to Open using the same Lock are detected and
     834              :         // prohibited.
     835              :         Lock *Lock
     836              : 
     837              :         // The count of L0 files necessary to trigger an L0 compaction.
     838              :         L0CompactionFileThreshold int
     839              : 
     840              :         // The amount of L0 read-amplification necessary to trigger an L0 compaction.
     841              :         L0CompactionThreshold int
     842              : 
     843              :         // Hard limit on L0 read-amplification, computed as the number of L0
     844              :         // sublevels. Writes are stopped when this threshold is reached.
     845              :         L0StopWritesThreshold int
     846              : 
     847              :         // The maximum number of bytes for LBase. The base level is the level which
     848              :         // L0 is compacted into. The base level is determined dynamically based on
     849              :         // the existing data in the LSM. The maximum number of bytes for other levels
     850              :         // is computed dynamically based on the base level's maximum size. When the
     851              :         // maximum number of bytes for a level is exceeded, compaction is requested.
     852              :         LBaseMaxBytes int64
     853              : 
     854              :         // TargetFileSizes contains the target file size for each level, ignoring
     855              :         // unpopulated levels. Specifically:
     856              :         // - TargetFileSizes[0] is the target file size for L0;
     857              :         // - TargetFileSizes[1] is the target file size for Lbase;
     858              :         // - TargetFileSizes[2] is the target file size for Lbase+1;
     859              :         // and so on.
     860              :         //
     861              :         // The default value for TargetFileSizes[0] is 2MB.
     862              :         // The default value for TargetFileSizes[i] is TargetFileSizes[i-1] * 2.
     863              :         TargetFileSizes [manifest.NumLevels]int64
     864              : 
     865              :         // Per-level options. Levels[i] contains the options for Li (regardless of
     866              :         // what Lbase is).
     867              :         Levels [manifest.NumLevels]LevelOptions
     868              : 
     869              :         // LoggerAndTracer will be used, if non-nil, else Logger will be used and
     870              :         // tracing will be a noop.
     871              : 
     872              :         // Logger used to write log messages.
     873              :         //
     874              :         // The default logger uses the Go standard library log package.
     875              :         Logger Logger
     876              :         // LoggerAndTracer is used for writing log messages and traces.
     877              :         LoggerAndTracer LoggerAndTracer
     878              : 
     879              :         // MaxManifestFileSize is the maximum size the MANIFEST file is allowed to
     880              :         // become. When the MANIFEST exceeds this size it is rolled over and a new
     881              :         // MANIFEST is created.
     882              :         MaxManifestFileSize int64
     883              : 
     884              :         // MaxOpenFiles is a soft limit on the number of open files that can be
     885              :         // used by the DB.
     886              :         //
     887              :         // The default value is 1000.
     888              :         MaxOpenFiles int
     889              : 
     890              :         // The size of a MemTable in steady state. The actual MemTable size starts at
     891              :         // min(256KB, MemTableSize) and doubles for each subsequent MemTable up to
     892              :         // MemTableSize. This reduces the memory pressure caused by MemTables for
     893              :         // short lived (test) DB instances. Note that more than one MemTable can be
     894              :         // in existence since flushing a MemTable involves creating a new one and
     895              :         // writing the contents of the old one in the
     896              :         // background. MemTableStopWritesThreshold places a hard limit on the size of
     897              :         // the queued MemTables.
     898              :         //
     899              :         // The default value is 4MB.
     900              :         MemTableSize uint64
     901              : 
     902              :         // Hard limit on the number of queued of MemTables. Writes are stopped when
     903              :         // the sum of the queued memtable sizes exceeds:
     904              :         //   MemTableStopWritesThreshold * MemTableSize.
     905              :         //
     906              :         // This value should be at least 2 or writes will stop whenever a MemTable is
     907              :         // being flushed.
     908              :         //
     909              :         // The default value is 2.
     910              :         MemTableStopWritesThreshold int
     911              : 
     912              :         // Merger defines the associative merge operation to use for merging values
     913              :         // written with {Batch,DB}.Merge.
     914              :         //
     915              :         // The default merger concatenates values.
     916              :         Merger *Merger
     917              : 
     918              :         // CompactionConcurrencyRange returns a [lower, upper] range for the number of
     919              :         // compactions Pebble runs in parallel (with the caveats below), not including
     920              :         // download compactions (which have a separate limit specified by
     921              :         // MaxConcurrentDownloads).
     922              :         //
     923              :         // The lower value is the concurrency allowed under normal circumstances.
     924              :         // Pebble can dynamically increase the concurrency based on heuristics (like
     925              :         // high read amplification or compaction debt) up to the maximum.
     926              :         //
     927              :         // The upper value is a rough upper bound since delete-only compactions (a) do
     928              :         // not use the CompactionScheduler, and (b) the CompactionScheduler may use
     929              :         // other criteria to decide on how many compactions to permit.
     930              :         //
     931              :         // Elaborating on (b), when the ConcurrencyLimitScheduler is being used, the
     932              :         // value returned by DB.GetAllowedWithoutPermission fully controls how many
     933              :         // compactions get to run. Other CompactionSchedulers may use additional
     934              :         // criteria, like resource availability.
     935              :         //
     936              :         // Elaborating on (a), we don't use the CompactionScheduler to schedule
     937              :         // delete-only compactions since they are expected to be almost free from a
     938              :         // CPU and disk usage perspective. Since the CompactionScheduler does not
     939              :         // know about their existence, the total running count can exceed this
     940              :         // value. For example, consider CompactionConcurrencyRange returns 3, and the
     941              :         // current value returned from DB.GetAllowedWithoutPermission is also 3. Say
     942              :         // 3 delete-only compactions are also running. Then the
     943              :         // ConcurrencyLimitScheduler can also start 3 other compactions, for a total
     944              :         // of 6.
     945              :         //
     946              :         // DB.GetAllowedWithoutPermission returns a value in the interval
     947              :         // [lower, upper]. A value > lower is returned:
     948              :         //  - when L0 read-amplification passes the L0CompactionConcurrency threshold;
     949              :         //  - when compaction debt passes the CompactionDebtConcurrency threshold;
     950              :         //  - when there are multiple manual compactions waiting to run.
     951              :         //
     952              :         // lower and upper must be greater than 0. If lower > upper, then upper is
     953              :         // used for both.
     954              :         //
     955              :         // The default values are 1, 1.
     956              :         CompactionConcurrencyRange func() (lower, upper int)
     957              : 
     958              :         // MaxConcurrentDownloads specifies the maximum number of download
     959              :         // compactions. These are compactions that copy an external file to the local
     960              :         // store.
     961              :         //
     962              :         // This limit is independent of CompactionConcurrencyRange; at any point in
     963              :         // time, we may be running CompactionConcurrencyRange non-download compactions
     964              :         // and MaxConcurrentDownloads download compactions.
     965              :         //
     966              :         // MaxConcurrentDownloads() must be greater than 0.
     967              :         //
     968              :         // The default value is 1.
     969              :         MaxConcurrentDownloads func() int
     970              : 
     971              :         // DisableAutomaticCompactions dictates whether automatic compactions are
     972              :         // scheduled or not. The default is false (enabled). This option is only used
     973              :         // externally when running a manual compaction, and internally for tests.
     974              :         DisableAutomaticCompactions bool
     975              : 
     976              :         // DisableConsistencyCheck disables the consistency check that is performed on
     977              :         // open. Should only be used when a database cannot be opened normally (e.g.
     978              :         // some of the tables don't exist / aren't accessible).
     979              :         DisableConsistencyCheck bool
     980              : 
     981              :         // DisableTableStats dictates whether tables should be loaded asynchronously
     982              :         // to compute statistics that inform compaction heuristics. The collection
     983              :         // of table stats improves compaction of tombstones, reclaiming disk space
     984              :         // more quickly and in some cases reducing write amplification in the
     985              :         // presence of tombstones. Disabling table stats may be useful in tests
     986              :         // that require determinism as the asynchronicity of table stats collection
     987              :         // introduces significant nondeterminism.
     988              :         DisableTableStats bool
     989              : 
     990              :         // NoSyncOnClose decides whether the Pebble instance will enforce a
     991              :         // close-time synchronization (e.g., fdatasync() or sync_file_range())
     992              :         // on files it writes to. Setting this to true removes the guarantee for a
     993              :         // sync on close. Some implementations can still issue a non-blocking sync.
     994              :         NoSyncOnClose bool
     995              : 
     996              :         // NumPrevManifest is the number of non-current or older manifests which
     997              :         // we want to keep around for debugging purposes. By default, we're going
     998              :         // to keep one older manifest.
     999              :         NumPrevManifest int
    1000              : 
    1001              :         // ReadOnly indicates that the DB should be opened in read-only mode. Writes
    1002              :         // to the DB will return an error, background compactions are disabled, and
    1003              :         // the flush that normally occurs after replaying the WAL at startup is
    1004              :         // disabled.
    1005              :         ReadOnly bool
    1006              : 
    1007              :         // FileCache is an initialized FileCache which should be set as an
    1008              :         // option if the DB needs to be initialized with a pre-existing file cache.
    1009              :         // If FileCache is nil, then a file cache which is unique to the DB instance
    1010              :         // is created. FileCache can be shared between db instances by setting it here.
    1011              :         // The FileCache set here must use the same underlying cache as Options.Cache
    1012              :         // and pebble will panic otherwise.
    1013              :         FileCache *FileCache
    1014              : 
    1015              :         // BlockPropertyCollectors is a list of BlockPropertyCollector creation
    1016              :         // functions. A new BlockPropertyCollector is created for each sstable
    1017              :         // built and lives for the lifetime of writing that table.
    1018              :         BlockPropertyCollectors []func() BlockPropertyCollector
    1019              : 
    1020              :         // WALBytesPerSync sets the number of bytes to write to a WAL before calling
    1021              :         // Sync on it in the background. Just like with BytesPerSync above, this
    1022              :         // helps smooth out disk write latencies, and avoids cases where the OS
    1023              :         // writes a lot of buffered data to disk at once. However, this is less
    1024              :         // necessary with WALs, as many write operations already pass in
    1025              :         // Sync = true.
    1026              :         //
    1027              :         // The default value is 0, i.e. no background syncing. This matches the
    1028              :         // default behaviour in RocksDB.
    1029              :         WALBytesPerSync int
    1030              : 
    1031              :         // WALDir specifies the directory to store write-ahead logs (WALs) in. If
    1032              :         // empty (the default), WALs will be stored in the same directory as sstables
    1033              :         // (i.e. the directory passed to pebble.Open).
    1034              :         WALDir string
    1035              : 
    1036              :         // WALFailover may be set to configure Pebble to monitor writes to its
    1037              :         // write-ahead log and failover to writing write-ahead log entries to a
    1038              :         // secondary location (eg, a separate physical disk). WALFailover may be
    1039              :         // used to improve write availability in the presence of transient disk
    1040              :         // unavailability.
    1041              :         WALFailover *WALFailoverOptions
    1042              : 
    1043              :         // WALRecoveryDirs is a list of additional directories that should be
    1044              :         // scanned for the existence of additional write-ahead logs. WALRecoveryDirs
    1045              :         // is expected to be used when starting Pebble with a new WALDir or a new
    1046              :         // WALFailover configuration. The directories associated with the previous
    1047              :         // configuration may still contain WALs that are required for recovery of
    1048              :         // the current database state.
    1049              :         //
    1050              :         // If a previous WAL configuration may have stored WALs elsewhere but there
    1051              :         // is not a corresponding entry in WALRecoveryDirs, Open will error.
    1052              :         WALRecoveryDirs []wal.Dir
    1053              : 
    1054              :         // WALMinSyncInterval is the minimum duration between syncs of the WAL. If
    1055              :         // WAL syncs are requested faster than this interval, they will be
    1056              :         // artificially delayed. Introducing a small artificial delay (500us) between
    1057              :         // WAL syncs can allow more operations to arrive and reduce IO operations
    1058              :         // while having a minimal impact on throughput. This option is supplied as a
    1059              :         // closure in order to allow the value to be changed dynamically. The default
    1060              :         // value is 0.
    1061              :         //
    1062              :         // TODO(peter): rather than a closure, should there be another mechanism for
    1063              :         // changing options dynamically?
    1064              :         WALMinSyncInterval func() time.Duration
    1065              : 
    1066              :         // The controls below manage deletion pacing, which slows down
    1067              :         // deletions when compactions finish or when readers close and
    1068              :         // obsolete files must be cleaned up. Rapid deletion of many
    1069              :         // files simultaneously can increase disk latency on certain
    1070              :         // SSDs, and this functionality helps protect against that.
    1071              : 
    1072              :         // TargetByteDeletionRate is the rate (in bytes per second) at which sstable file
    1073              :         // deletions are limited to (under normal circumstances).
    1074              :         //
    1075              :         // This value is only a best-effort target; the effective rate can be
    1076              :         // higher if deletions are falling behind or disk space is running low.
    1077              :         //
    1078              :         // Setting this to 0 disables deletion pacing, which is also the default.
    1079              :         TargetByteDeletionRate int
    1080              : 
    1081              :         // FreeSpaceThresholdBytes specifies the minimum amount of free disk space that Pebble
    1082              :         // attempts to maintain. If free disk space drops below this threshold, deletions
    1083              :         // are accelerated above TargetByteDeletionRate until the threshold is restored.
    1084              :         // Default is 16GB.
    1085              :         FreeSpaceThresholdBytes uint64
    1086              : 
    1087              :         // FreeSpaceTimeframe sets the duration (in seconds) within which Pebble attempts
    1088              :         // to restore the free disk space back to FreeSpaceThreshold. A lower value means
    1089              :         // more aggressive deletions. Default is 10s.
    1090              :         FreeSpaceTimeframe time.Duration
    1091              : 
    1092              :         // ObsoleteBytesMaxRatio specifies the maximum allowed ratio of obsolete files to
    1093              :         // live files. If this ratio is exceeded, Pebble speeds up deletions above the
    1094              :         // TargetByteDeletionRate until the ratio is restored. Default is 0.20.
    1095              :         ObsoleteBytesMaxRatio float64
    1096              : 
    1097              :         // ObsoleteBytesTimeframe sets the duration (in seconds) within which Pebble aims
    1098              :         // to restore the obsolete-to-live bytes ratio below ObsoleteBytesMaxRatio. A lower
    1099              :         // value means more aggressive deletions. Default is 300s.
    1100              :         ObsoleteBytesTimeframe time.Duration
    1101              : 
    1102              :         // EnableSQLRowSpillMetrics specifies whether the Pebble instance will only be used
    1103              :         // to temporarily persist data spilled to disk for row-oriented SQL query execution.
    1104              :         EnableSQLRowSpillMetrics bool
    1105              : 
    1106              :         // AllocatorSizeClasses provides a sorted list containing the supported size
    1107              :         // classes of the underlying memory allocator. This provides hints to the
    1108              :         // sstable block writer's flushing policy to select block sizes that
    1109              :         // preemptively reduce internal fragmentation when loaded into the block cache.
    1110              :         AllocatorSizeClasses []int
    1111              : 
    1112              :         // private options are only used by internal tests or are used internally
    1113              :         // for facilitating upgrade paths of unconfigurable functionality.
    1114              :         private struct {
    1115              :                 // disableDeleteOnlyCompactions prevents the scheduling of delete-only
    1116              :                 // compactions that drop sstables wholy covered by range tombstones or
    1117              :                 // range key tombstones.
    1118              :                 disableDeleteOnlyCompactions bool
    1119              : 
    1120              :                 // disableElisionOnlyCompactions prevents the scheduling of elision-only
    1121              :                 // compactions that rewrite sstables in place in order to elide obsolete
    1122              :                 // keys.
    1123              :                 disableElisionOnlyCompactions bool
    1124              : 
    1125              :                 // disableLazyCombinedIteration is a private option used by the
    1126              :                 // metamorphic tests to test equivalence between lazy-combined iteration
    1127              :                 // and constructing the range-key iterator upfront. It's a private
    1128              :                 // option to avoid littering the public interface with options that we
    1129              :                 // do not want to allow users to actually configure.
    1130              :                 disableLazyCombinedIteration bool
    1131              : 
    1132              :                 // testingAlwaysWaitForCleanup is set by some tests to force waiting for
    1133              :                 // obsolete file deletion (to make events deterministic).
    1134              :                 testingAlwaysWaitForCleanup bool
    1135              : 
    1136              :                 // fsCloser holds a closer that should be invoked after a DB using these
    1137              :                 // Options is closed. This is used to automatically stop the
    1138              :                 // long-running goroutine associated with the disk-health-checking FS.
    1139              :                 // See the initialization of FS in EnsureDefaults. Note that care has
    1140              :                 // been taken to ensure that it is still safe to continue using the FS
    1141              :                 // after this closer has been invoked. However, if write operations
    1142              :                 // against the FS are made after the DB is closed, the FS may leak a
    1143              :                 // goroutine indefinitely.
    1144              :                 fsCloser io.Closer
    1145              :         }
    1146              : }
    1147              : 
    1148              : // ValueSeparationPolicy controls the policy for separating values into
    1149              : // external blob files.
    1150              : type ValueSeparationPolicy struct {
    1151              :         // Enabled controls whether value separation is enabled.
    1152              :         Enabled bool
    1153              :         // MinimumSize imposes a lower bound on the size of values that can be
    1154              :         // separated into a blob file. Values smaller than this are always written
    1155              :         // to the sstable (but may still be written to a value block within the
    1156              :         // sstable).
    1157              :         //
    1158              :         // MinimumSize must be > 0.
    1159              :         MinimumSize int
    1160              :         // MaxBlobReferenceDepth limits the number of potentially overlapping (in
    1161              :         // the keyspace) blob files that can be referenced by a single sstable. If a
    1162              :         // compaction may produce an output sstable referencing more than this many
    1163              :         // overlapping blob files, the compaction will instead rewrite referenced
    1164              :         // values into new blob files.
    1165              :         //
    1166              :         // MaxBlobReferenceDepth must be > 0.
    1167              :         MaxBlobReferenceDepth int
    1168              :         // RewriteMinimumAge specifies how old a blob file must be in order for it
    1169              :         // to be eligible for a rewrite that reclaims disk space. Lower values
    1170              :         // reduce space amplification at the cost of write amplification
    1171              :         RewriteMinimumAge time.Duration
    1172              :         // TargetGarbageRatio is a value in the range [0, 1.0] and configures how
    1173              :         // aggressively blob files should be written in order to reduce space
    1174              :         // amplification induced by value separation. As compactions rewrite blob
    1175              :         // files, data may be duplicated.  Older blob files containing the
    1176              :         // duplicated data may need to remain because other sstables are referencing
    1177              :         // other values contained in the same file.
    1178              :         //
    1179              :         // The DB can rewrite these blob files in place in order to reduce this
    1180              :         // space amplification, but this incurs write amplification. This option
    1181              :         // configures how much garbage may accrue before the DB will attempt to
    1182              :         // rewrite blob files to reduce it. A value of 0.20 indicates that once 20%
    1183              :         // of values in blob files are unreferenced, the DB should attempt to
    1184              :         // rewrite blob files to reclaim disk space.
    1185              :         //
    1186              :         // A value of 1.0 indicates that the DB should never attempt to rewrite blob
    1187              :         // files.
    1188              :         TargetGarbageRatio float64
    1189              : }
    1190              : 
    1191              : // SpanPolicy contains policies that can vary by key range. The zero value is
    1192              : // the default value.
    1193              : type SpanPolicy struct {
    1194              :         // Prefer a faster compression algorithm for the keys in this span.
    1195              :         //
    1196              :         // This is useful for keys that are frequently read or written but which don't
    1197              :         // amount to a significant amount of space.
    1198              :         PreferFastCompression bool
    1199              : 
    1200              :         // DisableValueSeparationBySuffix disables discriminating KVs depending on
    1201              :         // suffix.
    1202              :         //
    1203              :         // Among a set of keys with the same prefix, Pebble's default heuristics
    1204              :         // optimize access to the KV with the smallest suffix. This is useful for MVCC
    1205              :         // keys (where the smallest suffix is the latest version), but should be
    1206              :         // disabled for keys where the suffix does not correspond to a version.
    1207              :         DisableValueSeparationBySuffix bool
    1208              : 
    1209              :         // ValueStoragePolicy is a hint used to determine where to store the values
    1210              :         // for KVs.
    1211              :         ValueStoragePolicy ValueStoragePolicy
    1212              : }
    1213              : 
    1214              : // String returns a string representation of the SpanPolicy.
    1215            1 : func (p SpanPolicy) String() string {
    1216            1 :         var sb strings.Builder
    1217            1 :         if p.PreferFastCompression {
    1218            0 :                 sb.WriteString("fast-compression,")
    1219            0 :         }
    1220            1 :         if p.DisableValueSeparationBySuffix {
    1221            0 :                 sb.WriteString("disable-value-separation-by-suffix,")
    1222            0 :         }
    1223            1 :         switch p.ValueStoragePolicy {
    1224            1 :         case ValueStorageLowReadLatency:
    1225            1 :                 sb.WriteString("low-read-latency,")
    1226            1 :         case ValueStorageLatencyTolerant:
    1227            1 :                 sb.WriteString("latency-tolerant,")
    1228              :         }
    1229            1 :         return strings.TrimSuffix(sb.String(), ",")
    1230              : }
    1231              : 
    1232              : // ValueStoragePolicy is a hint used to determine where to store the values for
    1233              : // KVs.
    1234              : type ValueStoragePolicy uint8
    1235              : 
    1236              : const (
    1237              :         // ValueStorageDefault is the default value; Pebble will respect global
    1238              :         // configuration for value blocks and value separation.
    1239              :         ValueStorageDefault ValueStoragePolicy = iota
    1240              : 
    1241              :         // ValueStorageLowReadLatency indicates Pebble should prefer storing values
    1242              :         // in-place.
    1243              :         ValueStorageLowReadLatency
    1244              : 
    1245              :         // ValueStorageLatencyTolerant indicates value retrieval can tolerate
    1246              :         // additional latency, so Pebble should aggressively prefer storing values
    1247              :         // separately if it can reduce write amplification.
    1248              :         //
    1249              :         // If the global Options' enable value separation, Pebble may choose to
    1250              :         // separate values under the LatencyTolerant policy even if they do not meet
    1251              :         // the minimum size threshold of the global Options' ValueSeparationPolicy.
    1252              :         ValueStorageLatencyTolerant
    1253              : )
    1254              : 
    1255              : // SpanPolicyFunc is used to determine the SpanPolicy for a key region.
    1256              : //
    1257              : // The returned policy is valid from the start key until (and not including) the
    1258              : // end key.
    1259              : //
    1260              : // A flush or compaction will call this function once for the first key to be
    1261              : // output. If the compaction reaches the end key, the current output sst is
    1262              : // finished and the function is called again.
    1263              : //
    1264              : // The end key can be empty, in which case the policy is valid for the entire
    1265              : // keyspace after startKey.
    1266              : type SpanPolicyFunc func(startKey []byte) (policy SpanPolicy, endKey []byte, err error)
    1267              : 
    1268              : // SpanAndPolicy defines a key range and the policy to apply to it.
    1269              : type SpanAndPolicy struct {
    1270              :         KeyRange KeyRange
    1271              :         Policy   SpanPolicy
    1272              : }
    1273              : 
    1274              : // MakeStaticSpanPolicyFunc returns a SpanPolicyFunc that applies a given policy
    1275              : // to the given span (and the default policy outside the span). The supplied
    1276              : // policies must be non-overlapping in key range.
    1277            1 : func MakeStaticSpanPolicyFunc(cmp base.Compare, inputPolicies ...SpanAndPolicy) SpanPolicyFunc {
    1278            1 :         // Collect all the boundaries of the input policies, sort and deduplicate them.
    1279            1 :         uniqueKeys := make([][]byte, 0, 2*len(inputPolicies))
    1280            1 :         for i := range inputPolicies {
    1281            1 :                 uniqueKeys = append(uniqueKeys, inputPolicies[i].KeyRange.Start)
    1282            1 :                 uniqueKeys = append(uniqueKeys, inputPolicies[i].KeyRange.End)
    1283            1 :         }
    1284            1 :         slices.SortFunc(uniqueKeys, cmp)
    1285            1 :         uniqueKeys = slices.CompactFunc(uniqueKeys, func(a, b []byte) bool { return cmp(a, b) == 0 })
    1286              : 
    1287              :         // Create a list of policies.
    1288            1 :         policies := make([]SpanPolicy, len(uniqueKeys)-1)
    1289            1 :         for _, p := range inputPolicies {
    1290            1 :                 idx, _ := slices.BinarySearchFunc(uniqueKeys, p.KeyRange.Start, cmp)
    1291            1 :                 policies[idx] = p.Policy
    1292            1 :         }
    1293              : 
    1294            1 :         return func(startKey []byte) (_ SpanPolicy, endKey []byte, _ error) {
    1295            1 :                 // Find the policy that applies to the start key.
    1296            1 :                 idx, eq := slices.BinarySearchFunc(uniqueKeys, startKey, cmp)
    1297            1 :                 switch idx {
    1298            1 :                 case len(uniqueKeys):
    1299            1 :                         // The start key is after the last policy.
    1300            1 :                         return SpanPolicy{}, nil, nil
    1301            1 :                 case len(uniqueKeys) - 1:
    1302            1 :                         if eq {
    1303            1 :                                 // The start key is exactly the start of the last policy.
    1304            1 :                                 return SpanPolicy{}, nil, nil
    1305            1 :                         }
    1306            1 :                 case 0:
    1307            1 :                         if !eq {
    1308            1 :                                 // The start key is before the first policy.
    1309            1 :                                 return SpanPolicy{}, uniqueKeys[0], nil
    1310            1 :                         }
    1311              :                 }
    1312            1 :                 if eq {
    1313            1 :                         // The start key is exactly the start of this policy.
    1314            1 :                         return policies[idx], uniqueKeys[idx+1], nil
    1315            1 :                 }
    1316              :                 // The start key is between two policies.
    1317            1 :                 return policies[idx-1], uniqueKeys[idx], nil
    1318              :         }
    1319              : }
    1320              : 
    1321              : // WALFailoverOptions configures the WAL failover mechanics to use during
    1322              : // transient write unavailability on the primary WAL volume.
    1323              : type WALFailoverOptions struct {
    1324              :         // Secondary indicates the secondary directory and VFS to use in the event a
    1325              :         // write to the primary WAL stalls.
    1326              :         Secondary wal.Dir
    1327              :         // FailoverOptions provides configuration of the thresholds and intervals
    1328              :         // involved in WAL failover. If any of its fields are left unspecified,
    1329              :         // reasonable defaults will be used.
    1330              :         wal.FailoverOptions
    1331              : }
    1332              : 
    1333              : // ReadaheadConfig controls the use of read-ahead.
    1334              : type ReadaheadConfig = objstorageprovider.ReadaheadConfig
    1335              : 
    1336              : // JemallocSizeClasses exports sstable.JemallocSizeClasses.
    1337              : var JemallocSizeClasses = sstable.JemallocSizeClasses
    1338              : 
    1339              : // DebugCheckLevels calls CheckLevels on the provided database.
    1340              : // It may be set in the DebugCheck field of Options to check
    1341              : // level invariants whenever a new version is installed.
    1342            1 : func DebugCheckLevels(db *DB) error {
    1343            1 :         return db.CheckLevels(nil)
    1344            1 : }
    1345              : 
    1346              : // DBCompressionSettings contains compression settings for the entire store. It
    1347              : // defines compression profiles for each LSM level.
    1348              : type DBCompressionSettings struct {
    1349              :         Name   string
    1350              :         Levels [manifest.NumLevels]*block.CompressionProfile
    1351              : }
    1352              : 
    1353              : // Predefined compression settings.
    1354              : var (
    1355              :         DBCompressionNone     = UniformDBCompressionSettings(block.NoCompression)
    1356              :         DBCompressionFastest  = UniformDBCompressionSettings(block.FastestCompression)
    1357            1 :         DBCompressionBalanced = func() DBCompressionSettings {
    1358            1 :                 cs := DBCompressionSettings{Name: "Balanced"}
    1359            1 :                 for i := 0; i < manifest.NumLevels-2; i++ {
    1360            1 :                         cs.Levels[i] = block.FastestCompression
    1361            1 :                 }
    1362            1 :                 cs.Levels[manifest.NumLevels-2] = block.FastCompression     // Zstd1 for value blocks.
    1363            1 :                 cs.Levels[manifest.NumLevels-1] = block.BalancedCompression // Zstd1 for data and value blocks.
    1364            1 :                 return cs
    1365              :         }()
    1366            1 :         DBCompressionGood = func() DBCompressionSettings {
    1367            1 :                 cs := DBCompressionSettings{Name: "Good"}
    1368            1 :                 for i := 0; i < manifest.NumLevels-2; i++ {
    1369            1 :                         cs.Levels[i] = block.FastestCompression
    1370            1 :                 }
    1371            1 :                 cs.Levels[manifest.NumLevels-2] = block.BalancedCompression // Zstd1 for data and value blocks.
    1372            1 :                 cs.Levels[manifest.NumLevels-1] = block.GoodCompression     // Zstd3 for data and value blocks.
    1373            1 :                 return cs
    1374              :         }()
    1375              : )
    1376              : 
    1377              : // UniformDBCompressionSettings returns a DBCompressionSettings which uses the
    1378              : // same compression profile on all LSM levels.
    1379            1 : func UniformDBCompressionSettings(profile *block.CompressionProfile) DBCompressionSettings {
    1380            1 :         cs := DBCompressionSettings{Name: profile.Name}
    1381            1 :         for i := range cs.Levels {
    1382            1 :                 cs.Levels[i] = profile
    1383            1 :         }
    1384            1 :         return cs
    1385              : }
    1386              : 
    1387              : // ApplyCompressionSettings sets the Compression field in each LevelOptions to
    1388              : // call the given function and return the compression profile for that level.
    1389            1 : func (o *Options) ApplyCompressionSettings(csFn func() DBCompressionSettings) {
    1390            1 :         for i := range o.Levels {
    1391            1 :                 levelIdx := i
    1392            1 :                 o.Levels[i].Compression = func() *block.CompressionProfile {
    1393            1 :                         return csFn().Levels[levelIdx]
    1394            1 :                 }
    1395              :         }
    1396              : }
    1397              : 
    1398              : // EnsureDefaults ensures that the default values for all options are set if a
    1399              : // valid value was not already specified.
    1400            1 : func (o *Options) EnsureDefaults() {
    1401            1 :         if o.Cache == nil && o.CacheSize == 0 {
    1402            1 :                 o.CacheSize = cacheDefaultSize
    1403            1 :         }
    1404            1 :         o.Comparer = o.Comparer.EnsureDefaults()
    1405            1 : 
    1406            1 :         if o.BytesPerSync <= 0 {
    1407            1 :                 o.BytesPerSync = 512 << 10 // 512 KB
    1408            1 :         }
    1409            1 :         if o.Cleaner == nil {
    1410            1 :                 o.Cleaner = DeleteCleaner{}
    1411            1 :         }
    1412              : 
    1413            1 :         if o.FreeSpaceThresholdBytes == 0 {
    1414            1 :                 o.FreeSpaceThresholdBytes = 16 << 30 // 16 GB
    1415            1 :         }
    1416              : 
    1417            1 :         if o.FreeSpaceTimeframe == 0 {
    1418            1 :                 o.FreeSpaceTimeframe = 10 * time.Second
    1419            1 :         }
    1420              : 
    1421            1 :         if o.ObsoleteBytesMaxRatio == 0 {
    1422            1 :                 o.ObsoleteBytesMaxRatio = 0.20
    1423            1 :         }
    1424              : 
    1425            1 :         if o.ObsoleteBytesTimeframe == 0 {
    1426            1 :                 o.ObsoleteBytesTimeframe = 300 * time.Second
    1427            1 :         }
    1428              : 
    1429            1 :         if o.Experimental.DisableIngestAsFlushable == nil {
    1430            1 :                 o.Experimental.DisableIngestAsFlushable = func() bool { return false }
    1431              :         }
    1432            1 :         if o.Experimental.L0CompactionConcurrency <= 0 {
    1433            1 :                 o.Experimental.L0CompactionConcurrency = 10
    1434            1 :         }
    1435            1 :         if o.Experimental.CompactionDebtConcurrency <= 0 {
    1436            1 :                 o.Experimental.CompactionDebtConcurrency = 1 << 30 // 1 GB
    1437            1 :         }
    1438            1 :         if o.Experimental.CompactionGarbageFractionForMaxConcurrency == nil {
    1439            1 :                 // When 40% of the DB is garbage, the compaction concurrency is at the
    1440            1 :                 // maximum permitted.
    1441            1 :                 o.Experimental.CompactionGarbageFractionForMaxConcurrency = func() float64 { return 0.4 }
    1442              :         }
    1443            1 :         if o.Experimental.ValueSeparationPolicy == nil {
    1444            1 :                 o.Experimental.ValueSeparationPolicy = func() ValueSeparationPolicy {
    1445            1 :                         return ValueSeparationPolicy{Enabled: false}
    1446            1 :                 }
    1447              :         }
    1448            1 :         if o.KeySchema == "" && len(o.KeySchemas) == 0 {
    1449            1 :                 ks := colblk.DefaultKeySchema(o.Comparer, 16 /* bundleSize */)
    1450            1 :                 o.KeySchema = ks.Name
    1451            1 :                 o.KeySchemas = sstable.MakeKeySchemas(&ks)
    1452            1 :         }
    1453            1 :         if o.L0CompactionThreshold <= 0 {
    1454            1 :                 o.L0CompactionThreshold = 4
    1455            1 :         }
    1456            1 :         if o.L0CompactionFileThreshold <= 0 {
    1457            1 :                 // Some justification for the default of 500:
    1458            1 :                 // Why not smaller?:
    1459            1 :                 // - The default target file size for L0 is 2MB, so 500 files is <= 1GB
    1460            1 :                 //   of data. At observed compaction speeds of > 20MB/s, L0 can be
    1461            1 :                 //   cleared of all files in < 1min, so this backlog is not huge.
    1462            1 :                 // - 500 files is low overhead for instantiating L0 sublevels from
    1463            1 :                 //   scratch.
    1464            1 :                 // - Lower values were observed to cause excessive and inefficient
    1465            1 :                 //   compactions out of L0 in a TPCC import benchmark.
    1466            1 :                 // Why not larger?:
    1467            1 :                 // - More than 1min to compact everything out of L0.
    1468            1 :                 // - CockroachDB's admission control system uses a threshold of 1000
    1469            1 :                 //   files to start throttling writes to Pebble. Using 500 here gives
    1470            1 :                 //   us headroom between when Pebble should start compacting L0 and
    1471            1 :                 //   when the admission control threshold is reached.
    1472            1 :                 //
    1473            1 :                 // We can revisit this default in the future based on better
    1474            1 :                 // experimental understanding.
    1475            1 :                 //
    1476            1 :                 // TODO(jackson): Experiment with slightly lower thresholds [or higher
    1477            1 :                 // admission control thresholds] to see whether a higher L0 score at the
    1478            1 :                 // threshold (currently 2.0) is necessary for some workloads to avoid
    1479            1 :                 // starving L0 in favor of lower-level compactions.
    1480            1 :                 o.L0CompactionFileThreshold = 500
    1481            1 :         }
    1482            1 :         if o.L0StopWritesThreshold <= 0 {
    1483            1 :                 o.L0StopWritesThreshold = 12
    1484            1 :         }
    1485            1 :         if o.LBaseMaxBytes <= 0 {
    1486            1 :                 o.LBaseMaxBytes = 64 << 20 // 64 MB
    1487            1 :         }
    1488            1 :         if o.TargetFileSizes[0] <= 0 {
    1489            1 :                 o.TargetFileSizes[0] = 2 << 20 // 2 MB
    1490            1 :         }
    1491            1 :         for i := 1; i < len(o.TargetFileSizes); i++ {
    1492            1 :                 if o.TargetFileSizes[i] <= 0 {
    1493            1 :                         o.TargetFileSizes[i] = o.TargetFileSizes[i-1] * 2
    1494            1 :                 }
    1495              :         }
    1496            1 :         o.Levels[0].EnsureL0Defaults()
    1497            1 :         for i := 1; i < len(o.Levels); i++ {
    1498            1 :                 o.Levels[i].EnsureL1PlusDefaults(&o.Levels[i-1])
    1499            1 :         }
    1500            1 :         if o.Logger == nil {
    1501            1 :                 o.Logger = DefaultLogger
    1502            1 :         }
    1503            1 :         if o.EventListener == nil {
    1504            1 :                 o.EventListener = &EventListener{}
    1505            1 :         }
    1506            1 :         o.EventListener.EnsureDefaults(o.Logger)
    1507            1 :         if o.MaxManifestFileSize == 0 {
    1508            1 :                 o.MaxManifestFileSize = 128 << 20 // 128 MB
    1509            1 :         }
    1510            1 :         if o.MaxOpenFiles == 0 {
    1511            1 :                 o.MaxOpenFiles = 1000
    1512            1 :         }
    1513            1 :         if o.MemTableSize <= 0 {
    1514            1 :                 o.MemTableSize = 4 << 20 // 4 MB
    1515            1 :         }
    1516            1 :         if o.MemTableStopWritesThreshold <= 0 {
    1517            1 :                 o.MemTableStopWritesThreshold = 2
    1518            1 :         }
    1519            1 :         if o.Merger == nil {
    1520            1 :                 o.Merger = DefaultMerger
    1521            1 :         }
    1522            1 :         if o.CompactionConcurrencyRange == nil {
    1523            1 :                 o.CompactionConcurrencyRange = func() (int, int) { return 1, 1 }
    1524              :         }
    1525            1 :         if o.MaxConcurrentDownloads == nil {
    1526            1 :                 o.MaxConcurrentDownloads = func() int { return 1 }
    1527              :         }
    1528            1 :         if o.NumPrevManifest <= 0 {
    1529            1 :                 o.NumPrevManifest = 1
    1530            1 :         }
    1531              : 
    1532            1 :         if o.FormatMajorVersion == FormatDefault {
    1533            1 :                 o.FormatMajorVersion = FormatMinSupported
    1534            1 :                 if o.Experimental.CreateOnShared != remote.CreateOnSharedNone {
    1535            1 :                         o.FormatMajorVersion = FormatMinForSharedObjects
    1536            1 :                 }
    1537              :         }
    1538              : 
    1539            1 :         if o.FS == nil {
    1540            1 :                 o.WithFSDefaults()
    1541            1 :         }
    1542            1 :         if o.FlushSplitBytes <= 0 {
    1543            1 :                 o.FlushSplitBytes = 2 * o.TargetFileSizes[0]
    1544            1 :         }
    1545            1 :         if o.WALFailover != nil {
    1546            1 :                 o.WALFailover.FailoverOptions.EnsureDefaults()
    1547            1 :         }
    1548            1 :         if o.Experimental.LevelMultiplier <= 0 {
    1549            1 :                 o.Experimental.LevelMultiplier = defaultLevelMultiplier
    1550            1 :         }
    1551            1 :         if o.Experimental.ReadCompactionRate == 0 {
    1552            1 :                 o.Experimental.ReadCompactionRate = 16000
    1553            1 :         }
    1554            1 :         if o.Experimental.ReadSamplingMultiplier == 0 {
    1555            1 :                 o.Experimental.ReadSamplingMultiplier = 1 << 4
    1556            1 :         }
    1557            1 :         if o.Experimental.NumDeletionsThreshold == 0 {
    1558            1 :                 o.Experimental.NumDeletionsThreshold = sstable.DefaultNumDeletionsThreshold
    1559            1 :         }
    1560            1 :         if o.Experimental.DeletionSizeRatioThreshold == 0 {
    1561            1 :                 o.Experimental.DeletionSizeRatioThreshold = sstable.DefaultDeletionSizeRatioThreshold
    1562            1 :         }
    1563            1 :         if o.Experimental.EnableColumnarBlocks == nil {
    1564            1 :                 o.Experimental.EnableColumnarBlocks = func() bool { return true }
    1565              :         }
    1566            1 :         if o.Experimental.TombstoneDenseCompactionThreshold == 0 {
    1567            1 :                 o.Experimental.TombstoneDenseCompactionThreshold = 0.10
    1568            1 :         }
    1569            1 :         if o.Experimental.FileCacheShards <= 0 {
    1570            1 :                 o.Experimental.FileCacheShards = runtime.GOMAXPROCS(0)
    1571            1 :         }
    1572            1 :         if o.Experimental.MultiLevelCompactionHeuristic == nil {
    1573            1 :                 o.Experimental.MultiLevelCompactionHeuristic = OptionWriteAmpHeuristic
    1574            1 :         }
    1575            1 :         if o.Experimental.SpanPolicyFunc == nil {
    1576            1 :                 o.Experimental.SpanPolicyFunc = func(startKey []byte) (SpanPolicy, []byte, error) { return SpanPolicy{}, nil, nil }
    1577              :         }
    1578              :         // TODO(jackson): Enable value separation by default once we have confidence
    1579              :         // in a default policy.
    1580              : 
    1581            1 :         o.initMaps()
    1582              : }
    1583              : 
    1584              : // TargetFileSize computes the target file size for the given output level.
    1585            1 : func (o *Options) TargetFileSize(outputLevel int, baseLevel int) int64 {
    1586            1 :         if outputLevel == 0 {
    1587            1 :                 return o.TargetFileSizes[0]
    1588            1 :         }
    1589            1 :         if baseLevel > outputLevel {
    1590            0 :                 panic(fmt.Sprintf("invalid base level %d (output level %d)", baseLevel, outputLevel))
    1591              :         }
    1592            1 :         return o.TargetFileSizes[outputLevel-baseLevel+1]
    1593              : }
    1594              : 
    1595              : // DefaultOptions returns a new Options object with the default values set.
    1596            1 : func DefaultOptions() *Options {
    1597            1 :         o := &Options{}
    1598            1 :         o.EnsureDefaults()
    1599            1 :         return o
    1600            1 : }
    1601              : 
    1602              : // WithFSDefaults configures the Options to wrap the configured filesystem with
    1603              : // the default virtual file system middleware, like disk-health checking.
    1604            1 : func (o *Options) WithFSDefaults() {
    1605            1 :         if o.FS == nil {
    1606            1 :                 o.FS = vfs.Default
    1607            1 :         }
    1608            1 :         o.FS, o.private.fsCloser = vfs.WithDiskHealthChecks(o.FS, 5*time.Second, nil,
    1609            1 :                 func(info vfs.DiskSlowInfo) {
    1610            0 :                         o.EventListener.DiskSlow(info)
    1611            0 :                 })
    1612              : }
    1613              : 
    1614              : // AddEventListener adds the provided event listener to the Options, in addition
    1615              : // to any existing event listener.
    1616            1 : func (o *Options) AddEventListener(l EventListener) {
    1617            1 :         if o.EventListener != nil {
    1618            1 :                 l = TeeEventListener(l, *o.EventListener)
    1619            1 :         }
    1620            1 :         o.EventListener = &l
    1621              : }
    1622              : 
    1623              : // initMaps initializes the Comparers, Filters, and Mergers maps.
    1624            1 : func (o *Options) initMaps() {
    1625            1 :         for i := range o.Levels {
    1626            1 :                 l := &o.Levels[i]
    1627            1 :                 if l.FilterPolicy != NoFilterPolicy {
    1628            1 :                         if o.Filters == nil {
    1629            1 :                                 o.Filters = make(map[string]FilterPolicy)
    1630            1 :                         }
    1631            1 :                         name := l.FilterPolicy.Name()
    1632            1 :                         if _, ok := o.Filters[name]; !ok {
    1633            1 :                                 o.Filters[name] = l.FilterPolicy
    1634            1 :                         }
    1635              :                 }
    1636              :         }
    1637              : }
    1638              : 
    1639              : // Clone creates a shallow-copy of the supplied options.
    1640            1 : func (o *Options) Clone() *Options {
    1641            1 :         if o == nil {
    1642            1 :                 return &Options{}
    1643            1 :         }
    1644            1 :         n := *o
    1645            1 :         if o.WALFailover != nil {
    1646            1 :                 c := *o.WALFailover
    1647            1 :                 n.WALFailover = &c
    1648            1 :         }
    1649            1 :         return &n
    1650              : }
    1651              : 
    1652            1 : func (o *Options) String() string {
    1653            1 :         var buf bytes.Buffer
    1654            1 : 
    1655            1 :         cacheSize := o.CacheSize
    1656            1 :         if o.Cache != nil {
    1657            1 :                 cacheSize = o.Cache.MaxSize()
    1658            1 :         }
    1659              : 
    1660            1 :         fmt.Fprintf(&buf, "[Version]\n")
    1661            1 :         fmt.Fprintf(&buf, "  pebble_version=0.1\n")
    1662            1 :         fmt.Fprintf(&buf, "\n")
    1663            1 :         fmt.Fprintf(&buf, "[Options]\n")
    1664            1 :         fmt.Fprintf(&buf, "  bytes_per_sync=%d\n", o.BytesPerSync)
    1665            1 :         fmt.Fprintf(&buf, "  cache_size=%d\n", cacheSize)
    1666            1 :         fmt.Fprintf(&buf, "  cleaner=%s\n", o.Cleaner)
    1667            1 :         fmt.Fprintf(&buf, "  compaction_debt_concurrency=%d\n", o.Experimental.CompactionDebtConcurrency)
    1668            1 :         fmt.Fprintf(&buf, "  compaction_garbage_fraction_for_max_concurrency=%.2f\n",
    1669            1 :                 o.Experimental.CompactionGarbageFractionForMaxConcurrency())
    1670            1 :         fmt.Fprintf(&buf, "  comparer=%s\n", o.Comparer.Name)
    1671            1 :         fmt.Fprintf(&buf, "  disable_wal=%t\n", o.DisableWAL)
    1672            1 :         if o.Experimental.DisableIngestAsFlushable != nil && o.Experimental.DisableIngestAsFlushable() {
    1673            1 :                 fmt.Fprintf(&buf, "  disable_ingest_as_flushable=%t\n", true)
    1674            1 :         }
    1675            1 :         if o.Experimental.EnableColumnarBlocks != nil && o.Experimental.EnableColumnarBlocks() {
    1676            1 :                 fmt.Fprintf(&buf, "  enable_columnar_blocks=%t\n", true)
    1677            1 :         }
    1678            1 :         fmt.Fprintf(&buf, "  flush_delay_delete_range=%s\n", o.FlushDelayDeleteRange)
    1679            1 :         fmt.Fprintf(&buf, "  flush_delay_range_key=%s\n", o.FlushDelayRangeKey)
    1680            1 :         fmt.Fprintf(&buf, "  flush_split_bytes=%d\n", o.FlushSplitBytes)
    1681            1 :         fmt.Fprintf(&buf, "  format_major_version=%d\n", o.FormatMajorVersion)
    1682            1 :         fmt.Fprintf(&buf, "  key_schema=%s\n", o.KeySchema)
    1683            1 :         fmt.Fprintf(&buf, "  l0_compaction_concurrency=%d\n", o.Experimental.L0CompactionConcurrency)
    1684            1 :         fmt.Fprintf(&buf, "  l0_compaction_file_threshold=%d\n", o.L0CompactionFileThreshold)
    1685            1 :         fmt.Fprintf(&buf, "  l0_compaction_threshold=%d\n", o.L0CompactionThreshold)
    1686            1 :         fmt.Fprintf(&buf, "  l0_stop_writes_threshold=%d\n", o.L0StopWritesThreshold)
    1687            1 :         fmt.Fprintf(&buf, "  lbase_max_bytes=%d\n", o.LBaseMaxBytes)
    1688            1 :         if o.Experimental.LevelMultiplier != defaultLevelMultiplier {
    1689            1 :                 fmt.Fprintf(&buf, "  level_multiplier=%d\n", o.Experimental.LevelMultiplier)
    1690            1 :         }
    1691            1 :         lower, upper := o.CompactionConcurrencyRange()
    1692            1 :         fmt.Fprintf(&buf, "  concurrent_compactions=%d\n", lower)
    1693            1 :         fmt.Fprintf(&buf, "  max_concurrent_compactions=%d\n", upper)
    1694            1 :         fmt.Fprintf(&buf, "  max_concurrent_downloads=%d\n", o.MaxConcurrentDownloads())
    1695            1 :         fmt.Fprintf(&buf, "  max_manifest_file_size=%d\n", o.MaxManifestFileSize)
    1696            1 :         fmt.Fprintf(&buf, "  max_open_files=%d\n", o.MaxOpenFiles)
    1697            1 :         fmt.Fprintf(&buf, "  mem_table_size=%d\n", o.MemTableSize)
    1698            1 :         fmt.Fprintf(&buf, "  mem_table_stop_writes_threshold=%d\n", o.MemTableStopWritesThreshold)
    1699            1 :         fmt.Fprintf(&buf, "  min_deletion_rate=%d\n", o.TargetByteDeletionRate)
    1700            1 :         fmt.Fprintf(&buf, "  free_space_threshold_bytes=%d\n", o.FreeSpaceThresholdBytes)
    1701            1 :         fmt.Fprintf(&buf, "  free_space_timeframe=%s\n", o.FreeSpaceTimeframe.String())
    1702            1 :         fmt.Fprintf(&buf, "  obsolete_bytes_max_ratio=%f\n", o.ObsoleteBytesMaxRatio)
    1703            1 :         fmt.Fprintf(&buf, "  obsolete_bytes_timeframe=%s\n", o.ObsoleteBytesTimeframe.String())
    1704            1 :         fmt.Fprintf(&buf, "  merger=%s\n", o.Merger.Name)
    1705            1 :         if o.Experimental.MultiLevelCompactionHeuristic != nil {
    1706            1 :                 fmt.Fprintf(&buf, "  multilevel_compaction_heuristic=%s\n", o.Experimental.MultiLevelCompactionHeuristic().String())
    1707            1 :         }
    1708            1 :         fmt.Fprintf(&buf, "  read_compaction_rate=%d\n", o.Experimental.ReadCompactionRate)
    1709            1 :         fmt.Fprintf(&buf, "  read_sampling_multiplier=%d\n", o.Experimental.ReadSamplingMultiplier)
    1710            1 :         fmt.Fprintf(&buf, "  num_deletions_threshold=%d\n", o.Experimental.NumDeletionsThreshold)
    1711            1 :         fmt.Fprintf(&buf, "  deletion_size_ratio_threshold=%f\n", o.Experimental.DeletionSizeRatioThreshold)
    1712            1 :         fmt.Fprintf(&buf, "  tombstone_dense_compaction_threshold=%f\n", o.Experimental.TombstoneDenseCompactionThreshold)
    1713            1 :         // We no longer care about strict_wal_tail, but set it to true in case an
    1714            1 :         // older version reads the options.
    1715            1 :         fmt.Fprintf(&buf, "  strict_wal_tail=%t\n", true)
    1716            1 :         fmt.Fprintf(&buf, "  table_cache_shards=%d\n", o.Experimental.FileCacheShards)
    1717            1 :         fmt.Fprintf(&buf, "  validate_on_ingest=%t\n", o.Experimental.ValidateOnIngest)
    1718            1 :         fmt.Fprintf(&buf, "  wal_dir=%s\n", o.WALDir)
    1719            1 :         fmt.Fprintf(&buf, "  wal_bytes_per_sync=%d\n", o.WALBytesPerSync)
    1720            1 :         fmt.Fprintf(&buf, "  secondary_cache_size_bytes=%d\n", o.Experimental.SecondaryCacheSizeBytes)
    1721            1 :         fmt.Fprintf(&buf, "  create_on_shared=%d\n", o.Experimental.CreateOnShared)
    1722            1 : 
    1723            1 :         // Private options.
    1724            1 :         //
    1725            1 :         // These options are only encoded if true, because we do not want them to
    1726            1 :         // appear in production serialized Options files, since they're testing-only
    1727            1 :         // options. They're only serialized when true, which still ensures that the
    1728            1 :         // metamorphic tests may propagate them to subprocesses.
    1729            1 :         if o.private.disableDeleteOnlyCompactions {
    1730            1 :                 fmt.Fprintln(&buf, "  disable_delete_only_compactions=true")
    1731            1 :         }
    1732            1 :         if o.private.disableElisionOnlyCompactions {
    1733            1 :                 fmt.Fprintln(&buf, "  disable_elision_only_compactions=true")
    1734            1 :         }
    1735            1 :         if o.private.disableLazyCombinedIteration {
    1736            1 :                 fmt.Fprintln(&buf, "  disable_lazy_combined_iteration=true")
    1737            1 :         }
    1738              : 
    1739            1 :         if o.Experimental.ValueSeparationPolicy != nil {
    1740            1 :                 policy := o.Experimental.ValueSeparationPolicy()
    1741            1 :                 if policy.Enabled {
    1742            1 :                         fmt.Fprintln(&buf)
    1743            1 :                         fmt.Fprintln(&buf, "[Value Separation]")
    1744            1 :                         fmt.Fprintf(&buf, "  enabled=%t\n", policy.Enabled)
    1745            1 :                         fmt.Fprintf(&buf, "  minimum_size=%d\n", policy.MinimumSize)
    1746            1 :                         fmt.Fprintf(&buf, "  max_blob_reference_depth=%d\n", policy.MaxBlobReferenceDepth)
    1747            1 :                         fmt.Fprintf(&buf, "  rewrite_minimum_age=%s\n", policy.RewriteMinimumAge)
    1748            1 :                         fmt.Fprintf(&buf, "  target_garbage_ratio=%.2f\n", policy.TargetGarbageRatio)
    1749            1 :                 }
    1750              :         }
    1751              : 
    1752            1 :         if o.WALFailover != nil {
    1753            1 :                 unhealthyThreshold, _ := o.WALFailover.FailoverOptions.UnhealthyOperationLatencyThreshold()
    1754            1 :                 fmt.Fprintf(&buf, "\n")
    1755            1 :                 fmt.Fprintf(&buf, "[WAL Failover]\n")
    1756            1 :                 fmt.Fprintf(&buf, "  secondary_dir=%s\n", o.WALFailover.Secondary.Dirname)
    1757            1 :                 fmt.Fprintf(&buf, "  primary_dir_probe_interval=%s\n", o.WALFailover.FailoverOptions.PrimaryDirProbeInterval)
    1758            1 :                 fmt.Fprintf(&buf, "  healthy_probe_latency_threshold=%s\n", o.WALFailover.FailoverOptions.HealthyProbeLatencyThreshold)
    1759            1 :                 fmt.Fprintf(&buf, "  healthy_interval=%s\n", o.WALFailover.FailoverOptions.HealthyInterval)
    1760            1 :                 fmt.Fprintf(&buf, "  unhealthy_sampling_interval=%s\n", o.WALFailover.FailoverOptions.UnhealthySamplingInterval)
    1761            1 :                 fmt.Fprintf(&buf, "  unhealthy_operation_latency_threshold=%s\n", unhealthyThreshold)
    1762            1 :                 fmt.Fprintf(&buf, "  elevated_write_stall_threshold_lag=%s\n", o.WALFailover.FailoverOptions.ElevatedWriteStallThresholdLag)
    1763            1 :         }
    1764              : 
    1765            1 :         for i := range o.Levels {
    1766            1 :                 l := &o.Levels[i]
    1767            1 :                 fmt.Fprintf(&buf, "\n")
    1768            1 :                 fmt.Fprintf(&buf, "[Level \"%d\"]\n", i)
    1769            1 :                 fmt.Fprintf(&buf, "  block_restart_interval=%d\n", l.BlockRestartInterval)
    1770            1 :                 fmt.Fprintf(&buf, "  block_size=%d\n", l.BlockSize)
    1771            1 :                 fmt.Fprintf(&buf, "  block_size_threshold=%d\n", l.BlockSizeThreshold)
    1772            1 :                 fmt.Fprintf(&buf, "  compression=%s\n", l.Compression().Name)
    1773            1 :                 fmt.Fprintf(&buf, "  filter_policy=%s\n", l.FilterPolicy.Name())
    1774            1 :                 fmt.Fprintf(&buf, "  filter_type=%s\n", l.FilterType)
    1775            1 :                 fmt.Fprintf(&buf, "  index_block_size=%d\n", l.IndexBlockSize)
    1776            1 :                 fmt.Fprintf(&buf, "  target_file_size=%d\n", o.TargetFileSizes[i])
    1777            1 :         }
    1778              : 
    1779            1 :         return buf.String()
    1780              : }
    1781              : 
    1782              : type parseOptionsFuncs struct {
    1783              :         visitNewSection          func(i, j int, section string) error
    1784              :         visitKeyValue            func(i, j int, section, key, value string) error
    1785              :         visitCommentOrWhitespace func(i, j int, whitespace string) error
    1786              : }
    1787              : 
    1788              : // parseOptions takes options serialized by Options.String() and parses them
    1789              : // into keys and values. It calls fns.visitNewSection for the beginning of each
    1790              : // new section, fns.visitKeyValue for each key-value pair, and
    1791              : // visitCommentOrWhitespace for comments and whitespace between key-value pairs.
    1792            1 : func parseOptions(s string, fns parseOptionsFuncs) error {
    1793            1 :         var section, mappedSection string
    1794            1 :         i := 0
    1795            1 :         for i < len(s) {
    1796            1 :                 rem := s[i:]
    1797            1 :                 j := strings.IndexByte(rem, '\n')
    1798            1 :                 if j < 0 {
    1799            1 :                         j = len(rem)
    1800            1 :                 } else {
    1801            1 :                         j += 1 // Include the newline.
    1802            1 :                 }
    1803            1 :                 line := strings.TrimSpace(s[i : i+j])
    1804            1 :                 startOff, endOff := i, i+j
    1805            1 :                 i += j
    1806            1 : 
    1807            1 :                 if len(line) == 0 || line[0] == ';' || line[0] == '#' {
    1808            1 :                         // Skip blank lines and comments.
    1809            1 :                         if fns.visitCommentOrWhitespace != nil {
    1810            1 :                                 if err := fns.visitCommentOrWhitespace(startOff, endOff, line); err != nil {
    1811            0 :                                         return err
    1812            0 :                                 }
    1813              :                         }
    1814            1 :                         continue
    1815              :                 }
    1816            1 :                 n := len(line)
    1817            1 :                 if line[0] == '[' && line[n-1] == ']' {
    1818            1 :                         // Parse section.
    1819            1 :                         section = line[1 : n-1]
    1820            1 :                         // RocksDB uses a similar (INI-style) syntax for the OPTIONS file, but
    1821            1 :                         // different section names and keys. The "CFOptions ..." paths are the
    1822            1 :                         // RocksDB versions which we map to the Pebble paths.
    1823            1 :                         mappedSection = section
    1824            1 :                         if section == `CFOptions "default"` {
    1825            1 :                                 mappedSection = "Options"
    1826            1 :                         }
    1827            1 :                         if fns.visitNewSection != nil {
    1828            1 :                                 if err := fns.visitNewSection(startOff, endOff, mappedSection); err != nil {
    1829            0 :                                         return err
    1830            0 :                                 }
    1831              :                         }
    1832            1 :                         continue
    1833              :                 }
    1834              : 
    1835            1 :                 pos := strings.Index(line, "=")
    1836            1 :                 if pos < 0 {
    1837            1 :                         const maxLen = 50
    1838            1 :                         if len(line) > maxLen {
    1839            0 :                                 line = line[:maxLen-3] + "..."
    1840            0 :                         }
    1841            1 :                         return base.CorruptionErrorf("invalid key=value syntax: %q", errors.Safe(line))
    1842              :                 }
    1843              : 
    1844            1 :                 key := strings.TrimSpace(line[:pos])
    1845            1 :                 value := strings.TrimSpace(line[pos+1:])
    1846            1 : 
    1847            1 :                 if section == `CFOptions "default"` {
    1848            1 :                         switch key {
    1849            1 :                         case "comparator":
    1850            1 :                                 key = "comparer"
    1851            1 :                         case "merge_operator":
    1852            1 :                                 key = "merger"
    1853              :                         }
    1854              :                 }
    1855            1 :                 if fns.visitKeyValue != nil {
    1856            1 :                         if err := fns.visitKeyValue(startOff, endOff, mappedSection, key, value); err != nil {
    1857            1 :                                 return err
    1858            1 :                         }
    1859              :                 }
    1860              :         }
    1861            1 :         return nil
    1862              : }
    1863              : 
    1864              : // ParseHooks contains callbacks to create options fields which can have
    1865              : // user-defined implementations.
    1866              : type ParseHooks struct {
    1867              :         NewCleaner      func(name string) (Cleaner, error)
    1868              :         NewComparer     func(name string) (*Comparer, error)
    1869              :         NewFilterPolicy func(name string) (FilterPolicy, error)
    1870              :         NewKeySchema    func(name string) (KeySchema, error)
    1871              :         NewMerger       func(name string) (*Merger, error)
    1872              :         SkipUnknown     func(name, value string) bool
    1873              : }
    1874              : 
    1875              : // Parse parses the options from the specified string. Note that certain
    1876              : // options cannot be parsed into populated fields. For example, comparer and
    1877              : // merger.
    1878            1 : func (o *Options) Parse(s string, hooks *ParseHooks) error {
    1879            1 :         var valSepPolicy ValueSeparationPolicy
    1880            1 :         var concurrencyLimit struct {
    1881            1 :                 lower    int
    1882            1 :                 lowerSet bool
    1883            1 :                 upper    int
    1884            1 :                 upperSet bool
    1885            1 :         }
    1886            1 : 
    1887            1 :         visitKeyValue := func(i, j int, section, key, value string) error {
    1888            1 :                 // WARNING: DO NOT remove entries from the switches below because doing so
    1889            1 :                 // causes a key previously written to the OPTIONS file to be considered unknown,
    1890            1 :                 // a backwards incompatible change. Instead, leave in support for parsing the
    1891            1 :                 // key but simply don't parse the value.
    1892            1 : 
    1893            1 :                 parseComparer := func(name string) (*Comparer, error) {
    1894            1 :                         switch name {
    1895            1 :                         case DefaultComparer.Name:
    1896            1 :                                 return DefaultComparer, nil
    1897            1 :                         case testkeys.Comparer.Name:
    1898            1 :                                 return testkeys.Comparer, nil
    1899            1 :                         default:
    1900            1 :                                 if hooks != nil && hooks.NewComparer != nil {
    1901            1 :                                         return hooks.NewComparer(name)
    1902            1 :                                 }
    1903            1 :                                 return nil, nil
    1904              :                         }
    1905              :                 }
    1906              : 
    1907            1 :                 switch {
    1908            1 :                 case section == "Version":
    1909            1 :                         switch key {
    1910            1 :                         case "pebble_version":
    1911            0 :                         default:
    1912            0 :                                 if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
    1913            0 :                                         return nil
    1914            0 :                                 }
    1915            0 :                                 return errors.Errorf("pebble: unknown option: %s.%s",
    1916            0 :                                         errors.Safe(section), errors.Safe(key))
    1917              :                         }
    1918            1 :                         return nil
    1919              : 
    1920            1 :                 case section == "Options":
    1921            1 :                         var err error
    1922            1 :                         switch key {
    1923            1 :                         case "bytes_per_sync":
    1924            1 :                                 o.BytesPerSync, err = strconv.Atoi(value)
    1925            1 :                         case "cache_size":
    1926            1 :                                 o.CacheSize, err = strconv.ParseInt(value, 10, 64)
    1927            1 :                         case "cleaner":
    1928            1 :                                 switch value {
    1929            1 :                                 case "archive":
    1930            1 :                                         o.Cleaner = ArchiveCleaner{}
    1931            1 :                                 case "delete":
    1932            1 :                                         o.Cleaner = DeleteCleaner{}
    1933            0 :                                 default:
    1934            0 :                                         if hooks != nil && hooks.NewCleaner != nil {
    1935            0 :                                                 o.Cleaner, err = hooks.NewCleaner(value)
    1936            0 :                                         }
    1937              :                                 }
    1938            1 :                         case "comparer":
    1939            1 :                                 var comparer *Comparer
    1940            1 :                                 comparer, err = parseComparer(value)
    1941            1 :                                 if comparer != nil {
    1942            1 :                                         o.Comparer = comparer
    1943            1 :                                 }
    1944            1 :                         case "compaction_debt_concurrency":
    1945            1 :                                 o.Experimental.CompactionDebtConcurrency, err = strconv.ParseUint(value, 10, 64)
    1946            1 :                         case "compaction_garbage_fraction_for_max_concurrency":
    1947            1 :                                 var frac float64
    1948            1 :                                 frac, err = strconv.ParseFloat(value, 64)
    1949            1 :                                 if err == nil {
    1950            1 :                                         o.Experimental.CompactionGarbageFractionForMaxConcurrency =
    1951            1 :                                                 func() float64 { return frac }
    1952              :                                 }
    1953            0 :                         case "delete_range_flush_delay":
    1954            0 :                                 // NB: This is a deprecated serialization of the
    1955            0 :                                 // `flush_delay_delete_range`.
    1956            0 :                                 o.FlushDelayDeleteRange, err = time.ParseDuration(value)
    1957            1 :                         case "disable_delete_only_compactions":
    1958            1 :                                 o.private.disableDeleteOnlyCompactions, err = strconv.ParseBool(value)
    1959            1 :                         case "disable_elision_only_compactions":
    1960            1 :                                 o.private.disableElisionOnlyCompactions, err = strconv.ParseBool(value)
    1961            1 :                         case "disable_ingest_as_flushable":
    1962            1 :                                 var v bool
    1963            1 :                                 v, err = strconv.ParseBool(value)
    1964            1 :                                 if err == nil {
    1965            1 :                                         o.Experimental.DisableIngestAsFlushable = func() bool { return v }
    1966              :                                 }
    1967            1 :                         case "disable_lazy_combined_iteration":
    1968            1 :                                 o.private.disableLazyCombinedIteration, err = strconv.ParseBool(value)
    1969            1 :                         case "disable_wal":
    1970            1 :                                 o.DisableWAL, err = strconv.ParseBool(value)
    1971            1 :                         case "enable_columnar_blocks":
    1972            1 :                                 var v bool
    1973            1 :                                 if v, err = strconv.ParseBool(value); err == nil {
    1974            1 :                                         o.Experimental.EnableColumnarBlocks = func() bool { return v }
    1975              :                                 }
    1976            1 :                         case "flush_delay_delete_range":
    1977            1 :                                 o.FlushDelayDeleteRange, err = time.ParseDuration(value)
    1978            1 :                         case "flush_delay_range_key":
    1979            1 :                                 o.FlushDelayRangeKey, err = time.ParseDuration(value)
    1980            1 :                         case "flush_split_bytes":
    1981            1 :                                 o.FlushSplitBytes, err = strconv.ParseInt(value, 10, 64)
    1982            1 :                         case "format_major_version":
    1983            1 :                                 // NB: The version written here may be stale. Open does
    1984            1 :                                 // not use the format major version encoded in the
    1985            1 :                                 // OPTIONS file other than to validate that the encoded
    1986            1 :                                 // version is valid right here.
    1987            1 :                                 var v uint64
    1988            1 :                                 v, err = strconv.ParseUint(value, 10, 64)
    1989            1 :                                 if vers := FormatMajorVersion(v); vers > internalFormatNewest || vers == FormatDefault {
    1990            0 :                                         err = errors.Newf("unsupported format major version %d", o.FormatMajorVersion)
    1991            0 :                                 }
    1992            1 :                                 if err == nil {
    1993            1 :                                         o.FormatMajorVersion = FormatMajorVersion(v)
    1994            1 :                                 }
    1995            1 :                         case "key_schema":
    1996            1 :                                 o.KeySchema = value
    1997            1 :                                 if o.KeySchemas == nil {
    1998            1 :                                         o.KeySchemas = make(map[string]*KeySchema)
    1999            1 :                                 }
    2000            1 :                                 if _, ok := o.KeySchemas[o.KeySchema]; !ok {
    2001            1 :                                         if strings.HasPrefix(value, "DefaultKeySchema(") && strings.HasSuffix(value, ")") {
    2002            1 :                                                 argsStr := strings.TrimSuffix(strings.TrimPrefix(value, "DefaultKeySchema("), ")")
    2003            1 :                                                 args := strings.FieldsFunc(argsStr, func(r rune) bool {
    2004            1 :                                                         return unicode.IsSpace(r) || r == ','
    2005            1 :                                                 })
    2006            1 :                                                 var comparer *base.Comparer
    2007            1 :                                                 var bundleSize int
    2008            1 :                                                 comparer, err = parseComparer(args[0])
    2009            1 :                                                 if err == nil {
    2010            1 :                                                         bundleSize, err = strconv.Atoi(args[1])
    2011            1 :                                                 }
    2012            1 :                                                 if err == nil {
    2013            1 :                                                         schema := colblk.DefaultKeySchema(comparer, bundleSize)
    2014            1 :                                                         o.KeySchema = schema.Name
    2015            1 :                                                         o.KeySchemas[o.KeySchema] = &schema
    2016            1 :                                                 }
    2017            1 :                                         } else if hooks != nil && hooks.NewKeySchema != nil {
    2018            0 :                                                 var schema KeySchema
    2019            0 :                                                 schema, err = hooks.NewKeySchema(value)
    2020            0 :                                                 if err == nil {
    2021            0 :                                                         o.KeySchemas[value] = &schema
    2022            0 :                                                 }
    2023              :                                         }
    2024              :                                 }
    2025            1 :                         case "l0_compaction_concurrency":
    2026            1 :                                 o.Experimental.L0CompactionConcurrency, err = strconv.Atoi(value)
    2027            1 :                         case "l0_compaction_file_threshold":
    2028            1 :                                 o.L0CompactionFileThreshold, err = strconv.Atoi(value)
    2029            1 :                         case "l0_compaction_threshold":
    2030            1 :                                 o.L0CompactionThreshold, err = strconv.Atoi(value)
    2031            1 :                         case "l0_stop_writes_threshold":
    2032            1 :                                 o.L0StopWritesThreshold, err = strconv.Atoi(value)
    2033            0 :                         case "l0_sublevel_compactions":
    2034              :                                 // Do nothing; option existed in older versions of pebble.
    2035            1 :                         case "lbase_max_bytes":
    2036            1 :                                 o.LBaseMaxBytes, err = strconv.ParseInt(value, 10, 64)
    2037            1 :                         case "level_multiplier":
    2038            1 :                                 o.Experimental.LevelMultiplier, err = strconv.Atoi(value)
    2039            1 :                         case "concurrent_compactions":
    2040            1 :                                 concurrencyLimit.lowerSet = true
    2041            1 :                                 concurrencyLimit.lower, err = strconv.Atoi(value)
    2042            1 :                         case "max_concurrent_compactions":
    2043            1 :                                 concurrencyLimit.upperSet = true
    2044            1 :                                 concurrencyLimit.upper, err = strconv.Atoi(value)
    2045            1 :                         case "max_concurrent_downloads":
    2046            1 :                                 var concurrentDownloads int
    2047            1 :                                 concurrentDownloads, err = strconv.Atoi(value)
    2048            1 :                                 if concurrentDownloads <= 0 {
    2049            0 :                                         err = errors.New("max_concurrent_compactions cannot be <= 0")
    2050            1 :                                 } else {
    2051            1 :                                         o.MaxConcurrentDownloads = func() int { return concurrentDownloads }
    2052              :                                 }
    2053            1 :                         case "max_manifest_file_size":
    2054            1 :                                 o.MaxManifestFileSize, err = strconv.ParseInt(value, 10, 64)
    2055            1 :                         case "max_open_files":
    2056            1 :                                 o.MaxOpenFiles, err = strconv.Atoi(value)
    2057            1 :                         case "mem_table_size":
    2058            1 :                                 o.MemTableSize, err = strconv.ParseUint(value, 10, 64)
    2059            1 :                         case "mem_table_stop_writes_threshold":
    2060            1 :                                 o.MemTableStopWritesThreshold, err = strconv.Atoi(value)
    2061            0 :                         case "min_compaction_rate":
    2062              :                                 // Do nothing; option existed in older versions of pebble, and
    2063              :                                 // may be meaningful again eventually.
    2064            1 :                         case "min_deletion_rate":
    2065            1 :                                 o.TargetByteDeletionRate, err = strconv.Atoi(value)
    2066            1 :                         case "free_space_threshold_bytes":
    2067            1 :                                 o.FreeSpaceThresholdBytes, err = strconv.ParseUint(value, 10, 64)
    2068            1 :                         case "free_space_timeframe":
    2069            1 :                                 o.FreeSpaceTimeframe, err = time.ParseDuration(value)
    2070            1 :                         case "obsolete_bytes_max_ratio":
    2071            1 :                                 o.ObsoleteBytesMaxRatio, err = strconv.ParseFloat(value, 64)
    2072            1 :                         case "obsolete_bytes_timeframe":
    2073            1 :                                 o.ObsoleteBytesTimeframe, err = time.ParseDuration(value)
    2074            0 :                         case "min_flush_rate":
    2075              :                                 // Do nothing; option existed in older versions of pebble, and
    2076              :                                 // may be meaningful again eventually.
    2077            1 :                         case "multilevel_compaction_heuristic":
    2078            1 :                                 switch {
    2079            1 :                                 case value == "none":
    2080            1 :                                         o.Experimental.MultiLevelCompactionHeuristic = OptionNoMultiLevel
    2081            1 :                                 case strings.HasPrefix(value, "wamp"):
    2082            1 :                                         o.Experimental.MultiLevelCompactionHeuristic = OptionWriteAmpHeuristic
    2083            1 :                                         fields := strings.FieldsFunc(strings.TrimPrefix(value, "wamp"), func(r rune) bool {
    2084            1 :                                                 return unicode.IsSpace(r) || r == ',' || r == '(' || r == ')'
    2085            1 :                                         })
    2086            1 :                                         if len(fields) != 2 {
    2087            0 :                                                 err = errors.Newf("require 2 arguments")
    2088            0 :                                         }
    2089            1 :                                         var h WriteAmpHeuristic
    2090            1 :                                         if err == nil {
    2091            1 :                                                 h.AddPropensity, err = strconv.ParseFloat(fields[0], 64)
    2092            1 :                                         }
    2093            1 :                                         if err == nil {
    2094            1 :                                                 h.AllowL0, err = strconv.ParseBool(fields[1])
    2095            1 :                                         }
    2096              : 
    2097            1 :                                         if err == nil {
    2098            1 :                                                 if h.AllowL0 || h.AddPropensity != 0 {
    2099            1 :                                                         o.Experimental.MultiLevelCompactionHeuristic = func() MultiLevelHeuristic {
    2100            1 :                                                                 return &h
    2101            1 :                                                         }
    2102              :                                                 }
    2103            0 :                                         } else {
    2104            0 :                                                 err = errors.Wrapf(err, "unexpected wamp heuristic arguments: %s", value)
    2105            0 :                                         }
    2106            0 :                                 default:
    2107            0 :                                         err = errors.Newf("unrecognized multilevel compaction heuristic: %s", value)
    2108              :                                 }
    2109            0 :                         case "point_tombstone_weight":
    2110              :                                 // Do nothing; deprecated.
    2111            1 :                         case "strict_wal_tail":
    2112            1 :                                 var strictWALTail bool
    2113            1 :                                 strictWALTail, err = strconv.ParseBool(value)
    2114            1 :                                 if err == nil && !strictWALTail {
    2115            0 :                                         err = errors.Newf("reading from versions with strict_wal_tail=false no longer supported")
    2116            0 :                                 }
    2117            1 :                         case "merger":
    2118            1 :                                 switch value {
    2119            0 :                                 case "nullptr":
    2120            0 :                                         o.Merger = nil
    2121            1 :                                 case "pebble.concatenate":
    2122            1 :                                         o.Merger = DefaultMerger
    2123            1 :                                 default:
    2124            1 :                                         if hooks != nil && hooks.NewMerger != nil {
    2125            1 :                                                 o.Merger, err = hooks.NewMerger(value)
    2126            1 :                                         }
    2127              :                                 }
    2128            1 :                         case "read_compaction_rate":
    2129            1 :                                 o.Experimental.ReadCompactionRate, err = strconv.ParseInt(value, 10, 64)
    2130            1 :                         case "read_sampling_multiplier":
    2131            1 :                                 o.Experimental.ReadSamplingMultiplier, err = strconv.ParseInt(value, 10, 64)
    2132            1 :                         case "num_deletions_threshold":
    2133            1 :                                 o.Experimental.NumDeletionsThreshold, err = strconv.Atoi(value)
    2134            1 :                         case "deletion_size_ratio_threshold":
    2135            1 :                                 val, parseErr := strconv.ParseFloat(value, 32)
    2136            1 :                                 o.Experimental.DeletionSizeRatioThreshold = float32(val)
    2137            1 :                                 err = parseErr
    2138            1 :                         case "tombstone_dense_compaction_threshold":
    2139            1 :                                 o.Experimental.TombstoneDenseCompactionThreshold, err = strconv.ParseFloat(value, 64)
    2140            1 :                         case "table_cache_shards":
    2141            1 :                                 o.Experimental.FileCacheShards, err = strconv.Atoi(value)
    2142            0 :                         case "table_format":
    2143            0 :                                 switch value {
    2144            0 :                                 case "leveldb":
    2145            0 :                                 case "rocksdbv2":
    2146            0 :                                 default:
    2147            0 :                                         return errors.Errorf("pebble: unknown table format: %q", errors.Safe(value))
    2148              :                                 }
    2149            1 :                         case "table_property_collectors":
    2150              :                                 // No longer implemented; ignore.
    2151            1 :                         case "validate_on_ingest":
    2152            1 :                                 o.Experimental.ValidateOnIngest, err = strconv.ParseBool(value)
    2153            1 :                         case "wal_dir":
    2154            1 :                                 o.WALDir = value
    2155            1 :                         case "wal_bytes_per_sync":
    2156            1 :                                 o.WALBytesPerSync, err = strconv.Atoi(value)
    2157            1 :                         case "max_writer_concurrency":
    2158              :                                 // No longer implemented; ignore.
    2159            1 :                         case "force_writer_parallelism":
    2160              :                                 // No longer implemented; ignore.
    2161            1 :                         case "secondary_cache_size_bytes":
    2162            1 :                                 o.Experimental.SecondaryCacheSizeBytes, err = strconv.ParseInt(value, 10, 64)
    2163            1 :                         case "create_on_shared":
    2164            1 :                                 var createOnSharedInt int64
    2165            1 :                                 createOnSharedInt, err = strconv.ParseInt(value, 10, 64)
    2166            1 :                                 o.Experimental.CreateOnShared = remote.CreateOnSharedStrategy(createOnSharedInt)
    2167            0 :                         default:
    2168            0 :                                 if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
    2169            0 :                                         return nil
    2170            0 :                                 }
    2171            0 :                                 return errors.Errorf("pebble: unknown option: %s.%s",
    2172            0 :                                         errors.Safe(section), errors.Safe(key))
    2173              :                         }
    2174            1 :                         return err
    2175              : 
    2176            1 :                 case section == "Value Separation":
    2177            1 :                         var err error
    2178            1 :                         switch key {
    2179            1 :                         case "enabled":
    2180            1 :                                 valSepPolicy.Enabled, err = strconv.ParseBool(value)
    2181            1 :                         case "minimum_size":
    2182            1 :                                 var minimumSize int
    2183            1 :                                 minimumSize, err = strconv.Atoi(value)
    2184            1 :                                 valSepPolicy.MinimumSize = minimumSize
    2185            1 :                         case "max_blob_reference_depth":
    2186            1 :                                 valSepPolicy.MaxBlobReferenceDepth, err = strconv.Atoi(value)
    2187            1 :                         case "rewrite_minimum_age":
    2188            1 :                                 valSepPolicy.RewriteMinimumAge, err = time.ParseDuration(value)
    2189            1 :                         case "target_garbage_ratio":
    2190            1 :                                 valSepPolicy.TargetGarbageRatio, err = strconv.ParseFloat(value, 64)
    2191            0 :                         default:
    2192            0 :                                 if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
    2193            0 :                                         return nil
    2194            0 :                                 }
    2195            0 :                                 return errors.Errorf("pebble: unknown option: %s.%s", errors.Safe(section), errors.Safe(key))
    2196              :                         }
    2197            1 :                         return err
    2198              : 
    2199            1 :                 case section == "WAL Failover":
    2200            1 :                         if o.WALFailover == nil {
    2201            1 :                                 o.WALFailover = new(WALFailoverOptions)
    2202            1 :                         }
    2203            1 :                         var err error
    2204            1 :                         switch key {
    2205            1 :                         case "secondary_dir":
    2206            1 :                                 o.WALFailover.Secondary = wal.Dir{Dirname: value, FS: vfs.Default}
    2207            1 :                         case "primary_dir_probe_interval":
    2208            1 :                                 o.WALFailover.PrimaryDirProbeInterval, err = time.ParseDuration(value)
    2209            1 :                         case "healthy_probe_latency_threshold":
    2210            1 :                                 o.WALFailover.HealthyProbeLatencyThreshold, err = time.ParseDuration(value)
    2211            1 :                         case "healthy_interval":
    2212            1 :                                 o.WALFailover.HealthyInterval, err = time.ParseDuration(value)
    2213            1 :                         case "unhealthy_sampling_interval":
    2214            1 :                                 o.WALFailover.UnhealthySamplingInterval, err = time.ParseDuration(value)
    2215            1 :                         case "unhealthy_operation_latency_threshold":
    2216            1 :                                 var threshold time.Duration
    2217            1 :                                 threshold, err = time.ParseDuration(value)
    2218            1 :                                 o.WALFailover.UnhealthyOperationLatencyThreshold = func() (time.Duration, bool) {
    2219            1 :                                         return threshold, true
    2220            1 :                                 }
    2221            1 :                         case "elevated_write_stall_threshold_lag":
    2222            1 :                                 o.WALFailover.ElevatedWriteStallThresholdLag, err = time.ParseDuration(value)
    2223            0 :                         default:
    2224            0 :                                 if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
    2225            0 :                                         return nil
    2226            0 :                                 }
    2227            0 :                                 return errors.Errorf("pebble: unknown option: %s.%s",
    2228            0 :                                         errors.Safe(section), errors.Safe(key))
    2229              :                         }
    2230            1 :                         return err
    2231              : 
    2232            1 :                 case strings.HasPrefix(section, "Level "):
    2233            1 :                         m := regexp.MustCompile(`Level\s*"?(\d+)"?\s*$`).FindStringSubmatch(section)
    2234            1 :                         if m == nil {
    2235            0 :                                 return errors.Errorf("pebble: unknown section: %q", errors.Safe(section))
    2236            0 :                         }
    2237            1 :                         index, _ := strconv.Atoi(m[1])
    2238            1 : 
    2239            1 :                         l := &o.Levels[index]
    2240            1 : 
    2241            1 :                         var err error
    2242            1 :                         switch key {
    2243            1 :                         case "block_restart_interval":
    2244            1 :                                 l.BlockRestartInterval, err = strconv.Atoi(value)
    2245            1 :                         case "block_size":
    2246            1 :                                 l.BlockSize, err = strconv.Atoi(value)
    2247            1 :                         case "block_size_threshold":
    2248            1 :                                 l.BlockSizeThreshold, err = strconv.Atoi(value)
    2249            1 :                         case "compression":
    2250            1 :                                 profile := block.CompressionProfileByName(value)
    2251            1 :                                 if profile == nil {
    2252            0 :                                         return errors.Errorf("pebble: unknown compression: %q", errors.Safe(value))
    2253            0 :                                 }
    2254            1 :                                 l.Compression = func() *sstable.CompressionProfile { return profile }
    2255            1 :                         case "filter_policy":
    2256            1 :                                 if hooks != nil && hooks.NewFilterPolicy != nil {
    2257            1 :                                         l.FilterPolicy, err = hooks.NewFilterPolicy(value)
    2258            1 :                                 } else {
    2259            1 :                                         l.FilterPolicy = NoFilterPolicy
    2260            1 :                                 }
    2261            1 :                         case "filter_type":
    2262            1 :                                 switch value {
    2263            1 :                                 case "table":
    2264            1 :                                         l.FilterType = TableFilter
    2265            0 :                                 default:
    2266            0 :                                         return errors.Errorf("pebble: unknown filter type: %q", errors.Safe(value))
    2267              :                                 }
    2268            1 :                         case "index_block_size":
    2269            1 :                                 l.IndexBlockSize, err = strconv.Atoi(value)
    2270            1 :                         case "target_file_size":
    2271            1 :                                 o.TargetFileSizes[index], err = strconv.ParseInt(value, 10, 64)
    2272            0 :                         default:
    2273            0 :                                 if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
    2274            0 :                                         return nil
    2275            0 :                                 }
    2276            0 :                                 return errors.Errorf("pebble: unknown option: %s.%s", errors.Safe(section), errors.Safe(key))
    2277              :                         }
    2278            1 :                         return err
    2279              :                 }
    2280            1 :                 if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
    2281            1 :                         return nil
    2282            1 :                 }
    2283            0 :                 return errors.Errorf("pebble: unknown section %q or key %q", errors.Safe(section), errors.Safe(key))
    2284              :         }
    2285            1 :         err := parseOptions(s, parseOptionsFuncs{
    2286            1 :                 visitKeyValue: visitKeyValue,
    2287            1 :         })
    2288            1 :         if err != nil {
    2289            1 :                 return err
    2290            1 :         }
    2291            1 :         o.Experimental.ValueSeparationPolicy = func() ValueSeparationPolicy { return valSepPolicy }
    2292            1 :         if concurrencyLimit.lowerSet || concurrencyLimit.upperSet {
    2293            1 :                 if !concurrencyLimit.lowerSet {
    2294            1 :                         concurrencyLimit.lower = 1
    2295            1 :                 } else if concurrencyLimit.lower < 1 {
    2296            0 :                         return errors.New("baseline_concurrent_compactions cannot be <= 0")
    2297            0 :                 }
    2298            1 :                 if !concurrencyLimit.upperSet {
    2299            1 :                         concurrencyLimit.upper = concurrencyLimit.lower
    2300            1 :                 } else if concurrencyLimit.upper < concurrencyLimit.lower {
    2301            0 :                         return errors.Newf("max_concurrent_compactions cannot be < %d", concurrencyLimit.lower)
    2302            0 :                 }
    2303            1 :                 o.CompactionConcurrencyRange = func() (int, int) {
    2304            1 :                         return concurrencyLimit.lower, concurrencyLimit.upper
    2305            1 :                 }
    2306              :         }
    2307            1 :         return nil
    2308              : }
    2309              : 
    2310              : // ErrMissingWALRecoveryDir is an error returned when a database is attempted to be
    2311              : // opened without supplying a Options.WALRecoveryDir entry for a directory that
    2312              : // may contain WALs required to recover a consistent database state.
    2313              : type ErrMissingWALRecoveryDir struct {
    2314              :         Dir       string
    2315              :         ExtraInfo string
    2316              : }
    2317              : 
    2318              : // Error implements error.
    2319            1 : func (e ErrMissingWALRecoveryDir) Error() string {
    2320            1 :         return fmt.Sprintf("directory %q may contain relevant WALs but is not in WALRecoveryDirs%s", e.Dir, e.ExtraInfo)
    2321            1 : }
    2322              : 
    2323              : // CheckCompatibility verifies the options are compatible with the previous options
    2324              : // serialized by Options.String(). For example, the Comparer and Merger must be
    2325              : // the same, or data will not be able to be properly read from the DB.
    2326              : //
    2327              : // This function only looks at specific keys and does not error out if the
    2328              : // options are newer and contain unknown keys.
    2329            1 : func (o *Options) CheckCompatibility(storeDir string, previousOptions string) error {
    2330            1 :         previousWALDir := ""
    2331            1 : 
    2332            1 :         visitKeyValue := func(i, j int, section, key, value string) error {
    2333            1 :                 switch section + "." + key {
    2334            1 :                 case "Options.comparer":
    2335            1 :                         if value != o.Comparer.Name {
    2336            1 :                                 return errors.Errorf("pebble: comparer name from file %q != comparer name from options %q",
    2337            1 :                                         errors.Safe(value), errors.Safe(o.Comparer.Name))
    2338            1 :                         }
    2339            1 :                 case "Options.merger":
    2340            1 :                         // RocksDB allows the merge operator to be unspecified, in which case it
    2341            1 :                         // shows up as "nullptr".
    2342            1 :                         if value != "nullptr" && value != o.Merger.Name {
    2343            1 :                                 return errors.Errorf("pebble: merger name from file %q != merger name from options %q",
    2344            1 :                                         errors.Safe(value), errors.Safe(o.Merger.Name))
    2345            1 :                         }
    2346            1 :                 case "Options.wal_dir":
    2347            1 :                         previousWALDir = value
    2348            1 :                 case "WAL Failover.secondary_dir":
    2349            1 :                         previousWALSecondaryDir := value
    2350            1 :                         if err := o.checkWALDir(storeDir, previousWALSecondaryDir, "WALFailover.Secondary changed from previous options"); err != nil {
    2351            1 :                                 return err
    2352            1 :                         }
    2353              :                 }
    2354            1 :                 return nil
    2355              :         }
    2356            1 :         if err := parseOptions(previousOptions, parseOptionsFuncs{visitKeyValue: visitKeyValue}); err != nil {
    2357            1 :                 return err
    2358            1 :         }
    2359            1 :         if err := o.checkWALDir(storeDir, previousWALDir, "WALDir changed from previous options"); err != nil {
    2360            1 :                 return err
    2361            1 :         }
    2362            1 :         return nil
    2363              : }
    2364              : 
    2365              : // checkWALDir verifies that walDir is among o.WALDir, o.WALFailover.Secondary,
    2366              : // or o.WALRecoveryDirs. An empty "walDir" maps to the storeDir.
    2367            1 : func (o *Options) checkWALDir(storeDir, walDir, errContext string) error {
    2368            1 :         walPath := resolveStorePath(storeDir, walDir)
    2369            1 :         if walDir == "" {
    2370            1 :                 walPath = storeDir
    2371            1 :         }
    2372              : 
    2373            1 :         if o.WALDir == "" {
    2374            1 :                 if walPath == storeDir {
    2375            1 :                         return nil
    2376            1 :                 }
    2377            1 :         } else {
    2378            1 :                 if walPath == resolveStorePath(storeDir, o.WALDir) {
    2379            1 :                         return nil
    2380            1 :                 }
    2381              :         }
    2382              : 
    2383            1 :         if o.WALFailover != nil && walPath == resolveStorePath(storeDir, o.WALFailover.Secondary.Dirname) {
    2384            1 :                 return nil
    2385            1 :         }
    2386              : 
    2387            1 :         for _, d := range o.WALRecoveryDirs {
    2388            1 :                 // TODO(radu): should we also check that d.FS is the same as walDir's FS?
    2389            1 :                 if walPath == resolveStorePath(storeDir, d.Dirname) {
    2390            1 :                         return nil
    2391            1 :                 }
    2392              :         }
    2393              : 
    2394            1 :         var buf bytes.Buffer
    2395            1 :         fmt.Fprintf(&buf, "\n  %s\n", errContext)
    2396            1 :         fmt.Fprintf(&buf, "  o.WALDir: %q\n", o.WALDir)
    2397            1 :         if o.WALFailover != nil {
    2398            0 :                 fmt.Fprintf(&buf, "  o.WALFailover.Secondary.Dirname: %q\n", o.WALFailover.Secondary.Dirname)
    2399            0 :         }
    2400            1 :         fmt.Fprintf(&buf, "  o.WALRecoveryDirs: %d", len(o.WALRecoveryDirs))
    2401            1 :         for _, d := range o.WALRecoveryDirs {
    2402            0 :                 fmt.Fprintf(&buf, "\n    %q", d.Dirname)
    2403            0 :         }
    2404            1 :         return ErrMissingWALRecoveryDir{Dir: walPath, ExtraInfo: buf.String()}
    2405              : }
    2406              : 
    2407              : // Validate verifies that the options are mutually consistent. For example,
    2408              : // L0StopWritesThreshold must be >= L0CompactionThreshold, otherwise a write
    2409              : // stall would persist indefinitely.
    2410            1 : func (o *Options) Validate() error {
    2411            1 :         // Note that we can presume Options.EnsureDefaults has been called, so there
    2412            1 :         // is no need to check for zero values.
    2413            1 : 
    2414            1 :         var buf strings.Builder
    2415            1 :         if o.Experimental.L0CompactionConcurrency < 1 {
    2416            1 :                 fmt.Fprintf(&buf, "L0CompactionConcurrency (%d) must be >= 1\n",
    2417            1 :                         o.Experimental.L0CompactionConcurrency)
    2418            1 :         }
    2419            1 :         if o.L0StopWritesThreshold < o.L0CompactionThreshold {
    2420            1 :                 fmt.Fprintf(&buf, "L0StopWritesThreshold (%d) must be >= L0CompactionThreshold (%d)\n",
    2421            1 :                         o.L0StopWritesThreshold, o.L0CompactionThreshold)
    2422            1 :         }
    2423            1 :         if uint64(o.MemTableSize) >= maxMemTableSize {
    2424            1 :                 fmt.Fprintf(&buf, "MemTableSize (%s) must be < %s\n",
    2425            1 :                         humanize.Bytes.Uint64(uint64(o.MemTableSize)), humanize.Bytes.Uint64(maxMemTableSize))
    2426            1 :         }
    2427            1 :         if o.MemTableStopWritesThreshold < 2 {
    2428            1 :                 fmt.Fprintf(&buf, "MemTableStopWritesThreshold (%d) must be >= 2\n",
    2429            1 :                         o.MemTableStopWritesThreshold)
    2430            1 :         }
    2431            1 :         if o.FormatMajorVersion < FormatMinSupported || o.FormatMajorVersion > internalFormatNewest {
    2432            0 :                 fmt.Fprintf(&buf, "FormatMajorVersion (%d) must be between %d and %d\n",
    2433            0 :                         o.FormatMajorVersion, FormatMinSupported, internalFormatNewest)
    2434            0 :         }
    2435            1 :         if o.Experimental.CreateOnShared != remote.CreateOnSharedNone && o.FormatMajorVersion < FormatMinForSharedObjects {
    2436            0 :                 fmt.Fprintf(&buf, "FormatMajorVersion (%d) when CreateOnShared is set must be at least %d\n",
    2437            0 :                         o.FormatMajorVersion, FormatMinForSharedObjects)
    2438            0 :         }
    2439            1 :         if len(o.KeySchemas) > 0 {
    2440            1 :                 if o.KeySchema == "" {
    2441            0 :                         fmt.Fprintf(&buf, "KeySchemas is set but KeySchema is not\n")
    2442            0 :                 }
    2443            1 :                 if _, ok := o.KeySchemas[o.KeySchema]; !ok {
    2444            0 :                         fmt.Fprintf(&buf, "KeySchema %q not found in KeySchemas\n", o.KeySchema)
    2445            0 :                 }
    2446              :         }
    2447            1 :         if policy := o.Experimental.ValueSeparationPolicy(); policy.Enabled {
    2448            1 :                 if policy.MinimumSize <= 0 {
    2449            0 :                         fmt.Fprintf(&buf, "ValueSeparationPolicy.MinimumSize (%d) must be > 0\n", policy.MinimumSize)
    2450            0 :                 }
    2451            1 :                 if policy.MaxBlobReferenceDepth <= 0 {
    2452            0 :                         fmt.Fprintf(&buf, "ValueSeparationPolicy.MaxBlobReferenceDepth (%d) must be > 0\n", policy.MaxBlobReferenceDepth)
    2453            0 :                 }
    2454              :         }
    2455              : 
    2456            1 :         if buf.Len() == 0 {
    2457            1 :                 return nil
    2458            1 :         }
    2459            1 :         return errors.New(buf.String())
    2460              : }
    2461              : 
    2462              : // MakeReaderOptions constructs sstable.ReaderOptions from the corresponding
    2463              : // options in the receiver.
    2464            1 : func (o *Options) MakeReaderOptions() sstable.ReaderOptions {
    2465            1 :         var readerOpts sstable.ReaderOptions
    2466            1 :         if o != nil {
    2467            1 :                 readerOpts.Comparer = o.Comparer
    2468            1 :                 readerOpts.Filters = o.Filters
    2469            1 :                 readerOpts.KeySchemas = o.KeySchemas
    2470            1 :                 readerOpts.LoadBlockSema = o.LoadBlockSema
    2471            1 :                 readerOpts.LoggerAndTracer = o.LoggerAndTracer
    2472            1 :                 readerOpts.Merger = o.Merger
    2473            1 :         }
    2474            1 :         return readerOpts
    2475              : }
    2476              : 
    2477              : // MakeWriterOptions constructs sstable.WriterOptions for the specified level
    2478              : // from the corresponding options in the receiver.
    2479            1 : func (o *Options) MakeWriterOptions(level int, format sstable.TableFormat) sstable.WriterOptions {
    2480            1 :         var writerOpts sstable.WriterOptions
    2481            1 :         writerOpts.TableFormat = format
    2482            1 :         if o != nil {
    2483            1 :                 writerOpts.Comparer = o.Comparer
    2484            1 :                 if o.Merger != nil {
    2485            1 :                         writerOpts.MergerName = o.Merger.Name
    2486            1 :                 }
    2487            1 :                 writerOpts.BlockPropertyCollectors = o.BlockPropertyCollectors
    2488              :         }
    2489            1 :         if format >= sstable.TableFormatPebblev3 {
    2490            1 :                 writerOpts.ShortAttributeExtractor = o.Experimental.ShortAttributeExtractor
    2491            1 :                 if format >= sstable.TableFormatPebblev4 && level == numLevels-1 {
    2492            1 :                         writerOpts.WritingToLowestLevel = true
    2493            1 :                 }
    2494              :         }
    2495            1 :         levelOpts := o.Levels[level]
    2496            1 :         writerOpts.BlockRestartInterval = levelOpts.BlockRestartInterval
    2497            1 :         writerOpts.BlockSize = levelOpts.BlockSize
    2498            1 :         writerOpts.BlockSizeThreshold = levelOpts.BlockSizeThreshold
    2499            1 :         writerOpts.Compression = levelOpts.Compression()
    2500            1 :         writerOpts.FilterPolicy = levelOpts.FilterPolicy
    2501            1 :         writerOpts.FilterType = levelOpts.FilterType
    2502            1 :         writerOpts.IndexBlockSize = levelOpts.IndexBlockSize
    2503            1 :         if o.KeySchema != "" {
    2504            1 :                 var ok bool
    2505            1 :                 writerOpts.KeySchema, ok = o.KeySchemas[o.KeySchema]
    2506            1 :                 if !ok {
    2507            0 :                         panic(fmt.Sprintf("invalid schema %q", redact.Safe(o.KeySchema)))
    2508              :                 }
    2509              :         }
    2510            1 :         writerOpts.AllocatorSizeClasses = o.AllocatorSizeClasses
    2511            1 :         writerOpts.NumDeletionsThreshold = o.Experimental.NumDeletionsThreshold
    2512            1 :         writerOpts.DeletionSizeRatioThreshold = o.Experimental.DeletionSizeRatioThreshold
    2513            1 :         return writerOpts
    2514              : }
    2515              : 
    2516              : // MakeBlobWriterOptions constructs blob.FileWriterOptions from the corresponding
    2517              : // options in the receiver.
    2518            1 : func (o *Options) MakeBlobWriterOptions(level int) blob.FileWriterOptions {
    2519            1 :         lo := o.Levels[level]
    2520            1 :         return blob.FileWriterOptions{
    2521            1 :                 Compression:  lo.Compression(),
    2522            1 :                 ChecksumType: block.ChecksumTypeCRC32c,
    2523            1 :                 FlushGovernor: block.MakeFlushGovernor(
    2524            1 :                         lo.BlockSize,
    2525            1 :                         lo.BlockSizeThreshold,
    2526            1 :                         base.SizeClassAwareBlockSizeThreshold,
    2527            1 :                         o.AllocatorSizeClasses,
    2528            1 :                 ),
    2529            1 :         }
    2530            1 : }
    2531              : 
    2532            1 : func (o *Options) MakeObjStorageProviderSettings(dirname string) objstorageprovider.Settings {
    2533            1 :         s := objstorageprovider.Settings{
    2534            1 :                 Logger:        o.Logger,
    2535            1 :                 FS:            o.FS,
    2536            1 :                 FSDirName:     dirname,
    2537            1 :                 FSCleaner:     o.Cleaner,
    2538            1 :                 NoSyncOnClose: o.NoSyncOnClose,
    2539            1 :                 BytesPerSync:  o.BytesPerSync,
    2540            1 :         }
    2541            1 :         s.Local.ReadaheadConfig = o.Local.ReadaheadConfig
    2542            1 :         s.Remote.StorageFactory = o.Experimental.RemoteStorage
    2543            1 :         s.Remote.CreateOnShared = o.Experimental.CreateOnShared
    2544            1 :         s.Remote.CreateOnSharedLocator = o.Experimental.CreateOnSharedLocator
    2545            1 :         s.Remote.CacheSizeBytes = o.Experimental.SecondaryCacheSizeBytes
    2546            1 :         return s
    2547            1 : }
    2548              : 
    2549              : // UserKeyCategories describes a partitioning of the user key space. Each
    2550              : // partition is a category with a name. The categories are used for informative
    2551              : // purposes only (like pprof labels). Pebble does not treat keys differently
    2552              : // based on the UserKeyCategories.
    2553              : //
    2554              : // The partitions are defined by their upper bounds. The last partition is
    2555              : // assumed to go until the end of keyspace; its UpperBound is ignored. The rest
    2556              : // of the partitions are ordered by their UpperBound.
    2557              : type UserKeyCategories struct {
    2558              :         categories []UserKeyCategory
    2559              :         cmp        base.Compare
    2560              :         // rangeNames[i][j] contains the string referring to the categories in the
    2561              :         // range [i, j], with j > i.
    2562              :         rangeNames [][]string
    2563              : }
    2564              : 
    2565              : // UserKeyCategory describes a partition of the user key space.
    2566              : //
    2567              : // User keys >= the previous category's UpperBound and < this category's
    2568              : // UpperBound are part of this category.
    2569              : type UserKeyCategory struct {
    2570              :         Name string
    2571              :         // UpperBound is the exclusive upper bound of the category. All user keys >= the
    2572              :         // previous category's UpperBound and < this UpperBound are part of this
    2573              :         // category.
    2574              :         UpperBound []byte
    2575              : }
    2576              : 
    2577              : // MakeUserKeyCategories creates a UserKeyCategories object with the given
    2578              : // categories. The object is immutable and can be reused across different
    2579              : // stores.
    2580            1 : func MakeUserKeyCategories(cmp base.Compare, categories ...UserKeyCategory) UserKeyCategories {
    2581            1 :         n := len(categories)
    2582            1 :         if n == 0 {
    2583            0 :                 return UserKeyCategories{}
    2584            0 :         }
    2585            1 :         if categories[n-1].UpperBound != nil {
    2586            0 :                 panic("last category UpperBound must be nil")
    2587              :         }
    2588              :         // Verify that the partitions are ordered as expected.
    2589            1 :         for i := 1; i < n-1; i++ {
    2590            1 :                 if cmp(categories[i-1].UpperBound, categories[i].UpperBound) >= 0 {
    2591            0 :                         panic("invalid UserKeyCategories: key prefixes must be sorted")
    2592              :                 }
    2593              :         }
    2594              : 
    2595              :         // Precalculate a table of range names to avoid allocations in the
    2596              :         // categorization path.
    2597            1 :         rangeNamesBuf := make([]string, n*n)
    2598            1 :         rangeNames := make([][]string, n)
    2599            1 :         for i := range rangeNames {
    2600            1 :                 rangeNames[i] = rangeNamesBuf[:n]
    2601            1 :                 rangeNamesBuf = rangeNamesBuf[n:]
    2602            1 :                 for j := i + 1; j < n; j++ {
    2603            1 :                         rangeNames[i][j] = categories[i].Name + "-" + categories[j].Name
    2604            1 :                 }
    2605              :         }
    2606            1 :         return UserKeyCategories{
    2607            1 :                 categories: categories,
    2608            1 :                 cmp:        cmp,
    2609            1 :                 rangeNames: rangeNames,
    2610            1 :         }
    2611              : }
    2612              : 
    2613              : // Len returns the number of categories defined.
    2614            1 : func (kc *UserKeyCategories) Len() int {
    2615            1 :         return len(kc.categories)
    2616            1 : }
    2617              : 
    2618              : // CategorizeKey returns the name of the category containing the key.
    2619            1 : func (kc *UserKeyCategories) CategorizeKey(userKey []byte) string {
    2620            1 :         idx := sort.Search(len(kc.categories)-1, func(i int) bool {
    2621            1 :                 return kc.cmp(userKey, kc.categories[i].UpperBound) < 0
    2622            1 :         })
    2623            1 :         return kc.categories[idx].Name
    2624              : }
    2625              : 
    2626              : // CategorizeKeyRange returns the name of the category containing the key range.
    2627              : // If the key range spans multiple categories, the result shows the first and
    2628              : // last category separated by a dash, e.g. `cat1-cat5`.
    2629            1 : func (kc *UserKeyCategories) CategorizeKeyRange(startUserKey, endUserKey []byte) string {
    2630            1 :         n := len(kc.categories)
    2631            1 :         p := sort.Search(n-1, func(i int) bool {
    2632            1 :                 return kc.cmp(startUserKey, kc.categories[i].UpperBound) < 0
    2633            1 :         })
    2634            1 :         if p == n-1 || kc.cmp(endUserKey, kc.categories[p].UpperBound) < 0 {
    2635            1 :                 // Fast path for a single category.
    2636            1 :                 return kc.categories[p].Name
    2637            1 :         }
    2638              :         // Binary search among the remaining categories.
    2639            1 :         q := p + 1 + sort.Search(n-2-p, func(i int) bool {
    2640            1 :                 return kc.cmp(endUserKey, kc.categories[p+1+i].UpperBound) < 0
    2641            1 :         })
    2642            1 :         return kc.rangeNames[p][q]
    2643              : }
    2644              : 
    2645              : const storePathIdentifier = "{store_path}"
    2646              : 
    2647              : // MakeStoreRelativePath takes a path that is relative to the store directory
    2648              : // and creates a path that can be used for Options.WALDir and wal.Dir.Dirname.
    2649              : //
    2650              : // This is used in metamorphic tests, so that the test run directory can be
    2651              : // copied or moved.
    2652            1 : func MakeStoreRelativePath(fs vfs.FS, relativePath string) string {
    2653            1 :         if relativePath == "" {
    2654            0 :                 return storePathIdentifier
    2655            0 :         }
    2656            1 :         return fs.PathJoin(storePathIdentifier, relativePath)
    2657              : }
    2658              : 
    2659              : // resolveStorePath is the inverse of MakeStoreRelativePath(). It replaces any
    2660              : // storePathIdentifier prefix with the store dir.
    2661            1 : func resolveStorePath(storeDir, path string) string {
    2662            1 :         if remainder, ok := strings.CutPrefix(path, storePathIdentifier); ok {
    2663            1 :                 return storeDir + remainder
    2664            1 :         }
    2665            1 :         return path
    2666              : }
        

Generated by: LCOV version 2.0-1