github.com/cockroachdb/pebble@v1.1.2/options.go (about)

     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  	"runtime"
    12  	"strconv"
    13  	"strings"
    14  	"time"
    15  
    16  	"github.com/cockroachdb/errors"
    17  	"github.com/cockroachdb/fifo"
    18  	"github.com/cockroachdb/pebble/internal/base"
    19  	"github.com/cockroachdb/pebble/internal/cache"
    20  	"github.com/cockroachdb/pebble/internal/humanize"
    21  	"github.com/cockroachdb/pebble/internal/keyspan"
    22  	"github.com/cockroachdb/pebble/internal/manifest"
    23  	"github.com/cockroachdb/pebble/objstorage/objstorageprovider"
    24  	"github.com/cockroachdb/pebble/objstorage/remote"
    25  	"github.com/cockroachdb/pebble/rangekey"
    26  	"github.com/cockroachdb/pebble/sstable"
    27  	"github.com/cockroachdb/pebble/vfs"
    28  )
    29  
    30  const (
    31  	cacheDefaultSize       = 8 << 20 // 8 MB
    32  	defaultLevelMultiplier = 10
    33  )
    34  
    35  // Compression exports the base.Compression type.
    36  type Compression = sstable.Compression
    37  
    38  // Exported Compression constants.
    39  const (
    40  	DefaultCompression = sstable.DefaultCompression
    41  	NoCompression      = sstable.NoCompression
    42  	SnappyCompression  = sstable.SnappyCompression
    43  	ZstdCompression    = sstable.ZstdCompression
    44  )
    45  
    46  // FilterType exports the base.FilterType type.
    47  type FilterType = base.FilterType
    48  
    49  // Exported TableFilter constants.
    50  const (
    51  	TableFilter = base.TableFilter
    52  )
    53  
    54  // FilterWriter exports the base.FilterWriter type.
    55  type FilterWriter = base.FilterWriter
    56  
    57  // FilterPolicy exports the base.FilterPolicy type.
    58  type FilterPolicy = base.FilterPolicy
    59  
    60  // TablePropertyCollector exports the sstable.TablePropertyCollector type.
    61  type TablePropertyCollector = sstable.TablePropertyCollector
    62  
    63  // BlockPropertyCollector exports the sstable.BlockPropertyCollector type.
    64  type BlockPropertyCollector = sstable.BlockPropertyCollector
    65  
    66  // BlockPropertyFilter exports the sstable.BlockPropertyFilter type.
    67  type BlockPropertyFilter = base.BlockPropertyFilter
    68  
    69  // ShortAttributeExtractor exports the base.ShortAttributeExtractor type.
    70  type ShortAttributeExtractor = base.ShortAttributeExtractor
    71  
    72  // UserKeyPrefixBound exports the sstable.UserKeyPrefixBound type.
    73  type UserKeyPrefixBound = sstable.UserKeyPrefixBound
    74  
    75  // IterKeyType configures which types of keys an iterator should surface.
    76  type IterKeyType int8
    77  
    78  const (
    79  	// IterKeyTypePointsOnly configures an iterator to iterate over point keys
    80  	// only.
    81  	IterKeyTypePointsOnly IterKeyType = iota
    82  	// IterKeyTypeRangesOnly configures an iterator to iterate over range keys
    83  	// only.
    84  	IterKeyTypeRangesOnly
    85  	// IterKeyTypePointsAndRanges configures an iterator iterate over both point
    86  	// keys and range keys simultaneously.
    87  	IterKeyTypePointsAndRanges
    88  )
    89  
    90  // String implements fmt.Stringer.
    91  func (t IterKeyType) String() string {
    92  	switch t {
    93  	case IterKeyTypePointsOnly:
    94  		return "points-only"
    95  	case IterKeyTypeRangesOnly:
    96  		return "ranges-only"
    97  	case IterKeyTypePointsAndRanges:
    98  		return "points-and-ranges"
    99  	default:
   100  		panic(fmt.Sprintf("unknown key type %d", t))
   101  	}
   102  }
   103  
   104  // IterOptions hold the optional per-query parameters for NewIter.
   105  //
   106  // Like Options, a nil *IterOptions is valid and means to use the default
   107  // values.
   108  type IterOptions struct {
   109  	// LowerBound specifies the smallest key (inclusive) that the iterator will
   110  	// return during iteration. If the iterator is seeked or iterated past this
   111  	// boundary the iterator will return Valid()==false. Setting LowerBound
   112  	// effectively truncates the key space visible to the iterator.
   113  	LowerBound []byte
   114  	// UpperBound specifies the largest key (exclusive) that the iterator will
   115  	// return during iteration. If the iterator is seeked or iterated past this
   116  	// boundary the iterator will return Valid()==false. Setting UpperBound
   117  	// effectively truncates the key space visible to the iterator.
   118  	UpperBound []byte
   119  	// TableFilter can be used to filter the tables that are scanned during
   120  	// iteration based on the user properties. Return true to scan the table and
   121  	// false to skip scanning. This function must be thread-safe since the same
   122  	// function can be used by multiple iterators, if the iterator is cloned.
   123  	TableFilter func(userProps map[string]string) bool
   124  	// SkipPoint may be used to skip over point keys that don't match an
   125  	// arbitrary predicate during iteration. If set, the Iterator invokes
   126  	// SkipPoint for keys encountered. If SkipPoint returns true, the iterator
   127  	// will skip the key without yielding it to the iterator operation in
   128  	// progress.
   129  	//
   130  	// SkipPoint must be a pure function and always return the same result when
   131  	// provided the same arguments. The iterator may call SkipPoint multiple
   132  	// times for the same user key.
   133  	SkipPoint func(userKey []byte) bool
   134  	// PointKeyFilters can be used to avoid scanning tables and blocks in tables
   135  	// when iterating over point keys. This slice represents an intersection
   136  	// across all filters, i.e., all filters must indicate that the block is
   137  	// relevant.
   138  	//
   139  	// Performance note: When len(PointKeyFilters) > 0, the caller should ensure
   140  	// that cap(PointKeyFilters) is at least len(PointKeyFilters)+1. This helps
   141  	// avoid allocations in Pebble internal code that mutates the slice.
   142  	PointKeyFilters []BlockPropertyFilter
   143  	// RangeKeyFilters can be usefd to avoid scanning tables and blocks in tables
   144  	// when iterating over range keys. The same requirements that apply to
   145  	// PointKeyFilters apply here too.
   146  	RangeKeyFilters []BlockPropertyFilter
   147  	// KeyTypes configures which types of keys to iterate over: point keys,
   148  	// range keys, or both.
   149  	KeyTypes IterKeyType
   150  	// RangeKeyMasking can be used to enable automatic masking of point keys by
   151  	// range keys. Range key masking is only supported during combined range key
   152  	// and point key iteration mode (IterKeyTypePointsAndRanges).
   153  	RangeKeyMasking RangeKeyMasking
   154  
   155  	// OnlyReadGuaranteedDurable is an advanced option that is only supported by
   156  	// the Reader implemented by DB. When set to true, only the guaranteed to be
   157  	// durable state is visible in the iterator.
   158  	// - This definition is made under the assumption that the FS implementation
   159  	//   is providing a durability guarantee when data is synced.
   160  	// - The visible state represents a consistent point in the history of the
   161  	//   DB.
   162  	// - The implementation is free to choose a conservative definition of what
   163  	//   is guaranteed durable. For simplicity, the current implementation
   164  	//   ignores memtables. A more sophisticated implementation could track the
   165  	//   highest seqnum that is synced to the WAL and published and use that as
   166  	//   the visible seqnum for an iterator. Note that the latter approach is
   167  	//   not strictly better than the former since we can have DBs that are (a)
   168  	//   synced more rarely than memtable flushes, (b) have no WAL. (a) is
   169  	//   likely to be true in a future CockroachDB context where the DB
   170  	//   containing the state machine may be rarely synced.
   171  	// NB: this current implementation relies on the fact that memtables are
   172  	// flushed in seqnum order, and any ingested sstables that happen to have a
   173  	// lower seqnum than a non-flushed memtable don't have any overlapping keys.
   174  	// This is the fundamental level invariant used in other code too, like when
   175  	// merging iterators.
   176  	//
   177  	// Semantically, using this option provides the caller a "snapshot" as of
   178  	// the time the most recent memtable was flushed. An alternate interface
   179  	// would be to add a NewSnapshot variant. Creating a snapshot is heavier
   180  	// weight than creating an iterator, so we have opted to support this
   181  	// iterator option.
   182  	OnlyReadGuaranteedDurable bool
   183  	// UseL6Filters allows the caller to opt into reading filter blocks for L6
   184  	// sstables. Helpful if a lot of SeekPrefixGEs are expected in quick
   185  	// succession, that are also likely to not yield a single key. Filter blocks in
   186  	// L6 can be relatively large, often larger than data blocks, so the benefit of
   187  	// loading them in the cache is minimized if the probability of the key
   188  	// existing is not low or if we just expect a one-time Seek (where loading the
   189  	// data block directly is better).
   190  	UseL6Filters bool
   191  
   192  	// Internal options.
   193  
   194  	logger Logger
   195  	// Level corresponding to this file. Only passed in if constructed by a
   196  	// levelIter.
   197  	level manifest.Level
   198  	// disableLazyCombinedIteration is an internal testing option.
   199  	disableLazyCombinedIteration bool
   200  	// snapshotForHideObsoletePoints is specified for/by levelIter when opening
   201  	// files and is used to decide whether to hide obsolete points. A value of 0
   202  	// implies obsolete points should not be hidden.
   203  	snapshotForHideObsoletePoints uint64
   204  
   205  	// NB: If adding new Options, you must account for them in iterator
   206  	// construction and Iterator.SetOptions.
   207  }
   208  
   209  // GetLowerBound returns the LowerBound or nil if the receiver is nil.
   210  func (o *IterOptions) GetLowerBound() []byte {
   211  	if o == nil {
   212  		return nil
   213  	}
   214  	return o.LowerBound
   215  }
   216  
   217  // GetUpperBound returns the UpperBound or nil if the receiver is nil.
   218  func (o *IterOptions) GetUpperBound() []byte {
   219  	if o == nil {
   220  		return nil
   221  	}
   222  	return o.UpperBound
   223  }
   224  
   225  func (o *IterOptions) pointKeys() bool {
   226  	if o == nil {
   227  		return true
   228  	}
   229  	return o.KeyTypes == IterKeyTypePointsOnly || o.KeyTypes == IterKeyTypePointsAndRanges
   230  }
   231  
   232  func (o *IterOptions) rangeKeys() bool {
   233  	if o == nil {
   234  		return false
   235  	}
   236  	return o.KeyTypes == IterKeyTypeRangesOnly || o.KeyTypes == IterKeyTypePointsAndRanges
   237  }
   238  
   239  func (o *IterOptions) getLogger() Logger {
   240  	if o == nil || o.logger == nil {
   241  		return DefaultLogger
   242  	}
   243  	return o.logger
   244  }
   245  
   246  // SpanIterOptions creates a SpanIterOptions from this IterOptions.
   247  func (o *IterOptions) SpanIterOptions() keyspan.SpanIterOptions {
   248  	if o == nil {
   249  		return keyspan.SpanIterOptions{}
   250  	}
   251  	return keyspan.SpanIterOptions{
   252  		RangeKeyFilters: o.RangeKeyFilters,
   253  	}
   254  }
   255  
   256  // scanInternalOptions is similar to IterOptions, meant for use with
   257  // scanInternalIterator.
   258  type scanInternalOptions struct {
   259  	IterOptions
   260  
   261  	visitPointKey   func(key *InternalKey, value LazyValue, iterInfo IteratorLevel) error
   262  	visitRangeDel   func(start, end []byte, seqNum uint64) error
   263  	visitRangeKey   func(start, end []byte, keys []rangekey.Key) error
   264  	visitSharedFile func(sst *SharedSSTMeta) error
   265  
   266  	// skipSharedLevels skips levels that are shareable (level >=
   267  	// sharedLevelStart).
   268  	skipSharedLevels bool
   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  func (o *WriteOptions) GetSync() bool {
   379  	return o == nil || o.Sync
   380  }
   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.
   388  	BlockRestartInterval int
   389  
   390  	// BlockSize is the target uncompressed size in bytes of each table block.
   391  	//
   392  	// The default value is 4096.
   393  	BlockSize int
   394  
   395  	// BlockSizeThreshold finishes a block if the block size is larger than the
   396  	// specified percentage of the target block size and adding the next entry
   397  	// would cause the block to be larger than the target block size.
   398  	//
   399  	// The default value is 90
   400  	BlockSizeThreshold int
   401  
   402  	// Compression defines the per-block compression to use.
   403  	//
   404  	// The default value (DefaultCompression) uses snappy compression.
   405  	Compression Compression
   406  
   407  	// FilterPolicy defines a filter algorithm (such as a Bloom filter) that can
   408  	// reduce disk reads for Get calls.
   409  	//
   410  	// One such implementation is bloom.FilterPolicy(10) from the pebble/bloom
   411  	// package.
   412  	//
   413  	// The default value means to use no filter.
   414  	FilterPolicy FilterPolicy
   415  
   416  	// FilterType defines whether an existing filter policy is applied at a
   417  	// block-level or table-level. Block-level filters use less memory to create,
   418  	// but are slower to access as a check for the key in the index must first be
   419  	// performed to locate the filter block. A table-level filter will require
   420  	// memory proportional to the number of keys in an sstable to create, but
   421  	// avoids the index lookup when determining if a key is present. Table-level
   422  	// filters should be preferred except under constrained memory situations.
   423  	FilterType FilterType
   424  
   425  	// IndexBlockSize is the target uncompressed size in bytes of each index
   426  	// block. When the index block size is larger than this target, two-level
   427  	// indexes are automatically enabled. Setting this option to a large value
   428  	// (such as math.MaxInt32) disables the automatic creation of two-level
   429  	// indexes.
   430  	//
   431  	// The default value is the value of BlockSize.
   432  	IndexBlockSize int
   433  
   434  	// The target file size for the level.
   435  	TargetFileSize int64
   436  }
   437  
   438  // EnsureDefaults ensures that the default values for all of the options have
   439  // been initialized. It is valid to call EnsureDefaults on a nil receiver. A
   440  // non-nil result will always be returned.
   441  func (o *LevelOptions) EnsureDefaults() *LevelOptions {
   442  	if o == nil {
   443  		o = &LevelOptions{}
   444  	}
   445  	if o.BlockRestartInterval <= 0 {
   446  		o.BlockRestartInterval = base.DefaultBlockRestartInterval
   447  	}
   448  	if o.BlockSize <= 0 {
   449  		o.BlockSize = base.DefaultBlockSize
   450  	} else if o.BlockSize > sstable.MaximumBlockSize {
   451  		panic(errors.Errorf("BlockSize %d exceeds MaximumBlockSize", o.BlockSize))
   452  	}
   453  	if o.BlockSizeThreshold <= 0 {
   454  		o.BlockSizeThreshold = base.DefaultBlockSizeThreshold
   455  	}
   456  	if o.Compression <= DefaultCompression || o.Compression >= sstable.NCompression {
   457  		o.Compression = SnappyCompression
   458  	}
   459  	if o.IndexBlockSize <= 0 {
   460  		o.IndexBlockSize = o.BlockSize
   461  	}
   462  	if o.TargetFileSize <= 0 {
   463  		o.TargetFileSize = 2 << 20 // 2 MB
   464  	}
   465  	return o
   466  }
   467  
   468  // Options holds the optional parameters for configuring pebble. These options
   469  // apply to the DB at large; per-query options are defined by the IterOptions
   470  // and WriteOptions types.
   471  type Options struct {
   472  	// Sync sstables periodically in order to smooth out writes to disk. This
   473  	// option does not provide any persistency guarantee, but is used to avoid
   474  	// latency spikes if the OS automatically decides to write out a large chunk
   475  	// of dirty filesystem buffers. This option only controls SSTable syncs; WAL
   476  	// syncs are controlled by WALBytesPerSync.
   477  	//
   478  	// The default value is 512KB.
   479  	BytesPerSync int
   480  
   481  	// Cache is used to cache uncompressed blocks from sstables.
   482  	//
   483  	// The default cache size is 8 MB.
   484  	Cache *cache.Cache
   485  
   486  	// LoadBlockSema, if set, is used to limit the number of blocks that can be
   487  	// loaded (i.e. read from the filesystem) in parallel. Each load acquires one
   488  	// unit from the semaphore for the duration of the read.
   489  	LoadBlockSema *fifo.Semaphore
   490  
   491  	// Cleaner cleans obsolete files.
   492  	//
   493  	// The default cleaner uses the DeleteCleaner.
   494  	Cleaner Cleaner
   495  
   496  	// Local contains option that pertain to files stored on the local filesystem.
   497  	Local struct {
   498  		// ReadaheadConfigFn is a function used to retrieve the current readahead
   499  		// mode. This function is consulted when a table enters the table cache.
   500  		ReadaheadConfigFn func() ReadaheadConfig
   501  
   502  		// TODO(radu): move BytesPerSync, LoadBlockSema, Cleaner here.
   503  	}
   504  
   505  	// Comparer defines a total ordering over the space of []byte keys: a 'less
   506  	// than' relationship. The same comparison algorithm must be used for reads
   507  	// and writes over the lifetime of the DB.
   508  	//
   509  	// The default value uses the same ordering as bytes.Compare.
   510  	Comparer *Comparer
   511  
   512  	// DebugCheck is invoked, if non-nil, whenever a new version is being
   513  	// installed. Typically, this is set to pebble.DebugCheckLevels in tests
   514  	// or tools only, to check invariants over all the data in the database.
   515  	DebugCheck func(*DB) error
   516  
   517  	// Disable the write-ahead log (WAL). Disabling the write-ahead log prohibits
   518  	// crash recovery, but can improve performance if crash recovery is not
   519  	// needed (e.g. when only temporary state is being stored in the database).
   520  	//
   521  	// TODO(peter): untested
   522  	DisableWAL bool
   523  
   524  	// ErrorIfExists causes an error on Open if the database already exists.
   525  	// The error can be checked with errors.Is(err, ErrDBAlreadyExists).
   526  	//
   527  	// The default value is false.
   528  	ErrorIfExists bool
   529  
   530  	// ErrorIfNotExists causes an error on Open if the database does not already
   531  	// exist. The error can be checked with errors.Is(err, ErrDBDoesNotExist).
   532  	//
   533  	// The default value is false which will cause a database to be created if it
   534  	// does not already exist.
   535  	ErrorIfNotExists bool
   536  
   537  	// ErrorIfNotPristine causes an error on Open if the database already exists
   538  	// and any operations have been performed on the database. The error can be
   539  	// checked with errors.Is(err, ErrDBNotPristine).
   540  	//
   541  	// Note that a database that contained keys that were all subsequently deleted
   542  	// may or may not trigger the error. Currently, we check if there are any live
   543  	// SSTs or log records to replay.
   544  	ErrorIfNotPristine bool
   545  
   546  	// EventListener provides hooks to listening to significant DB events such as
   547  	// flushes, compactions, and table deletion.
   548  	EventListener *EventListener
   549  
   550  	// Experimental contains experimental options which are off by default.
   551  	// These options are temporary and will eventually either be deleted, moved
   552  	// out of the experimental group, or made the non-adjustable default. These
   553  	// options may change at any time, so do not rely on them.
   554  	Experimental struct {
   555  		// The threshold of L0 read-amplification at which compaction concurrency
   556  		// is enabled (if CompactionDebtConcurrency was not already exceeded).
   557  		// Every multiple of this value enables another concurrent
   558  		// compaction up to MaxConcurrentCompactions.
   559  		L0CompactionConcurrency int
   560  
   561  		// CompactionDebtConcurrency controls the threshold of compaction debt
   562  		// at which additional compaction concurrency slots are added. For every
   563  		// multiple of this value in compaction debt bytes, an additional
   564  		// concurrent compaction is added. This works "on top" of
   565  		// L0CompactionConcurrency, so the higher of the count of compaction
   566  		// concurrency slots as determined by the two options is chosen.
   567  		CompactionDebtConcurrency uint64
   568  
   569  		// IngestSplit, if it returns true, allows for ingest-time splitting of
   570  		// existing sstables into two virtual sstables to allow ingestion sstables to
   571  		// slot into a lower level than they otherwise would have.
   572  		IngestSplit func() bool
   573  
   574  		// ReadCompactionRate controls the frequency of read triggered
   575  		// compactions by adjusting `AllowedSeeks` in manifest.FileMetadata:
   576  		//
   577  		// AllowedSeeks = FileSize / ReadCompactionRate
   578  		//
   579  		// From LevelDB:
   580  		// ```
   581  		// We arrange to automatically compact this file after
   582  		// a certain number of seeks. Let's assume:
   583  		//   (1) One seek costs 10ms
   584  		//   (2) Writing or reading 1MB costs 10ms (100MB/s)
   585  		//   (3) A compaction of 1MB does 25MB of IO:
   586  		//         1MB read from this level
   587  		//         10-12MB read from next level (boundaries may be misaligned)
   588  		//         10-12MB written to next level
   589  		// This implies that 25 seeks cost the same as the compaction
   590  		// of 1MB of data.  I.e., one seek costs approximately the
   591  		// same as the compaction of 40KB of data.  We are a little
   592  		// conservative and allow approximately one seek for every 16KB
   593  		// of data before triggering a compaction.
   594  		// ```
   595  		ReadCompactionRate int64
   596  
   597  		// ReadSamplingMultiplier is a multiplier for the readSamplingPeriod in
   598  		// iterator.maybeSampleRead() to control the frequency of read sampling
   599  		// to trigger a read triggered compaction. A value of -1 prevents sampling
   600  		// and disables read triggered compactions. The default is 1 << 4. which
   601  		// gets multiplied with a constant of 1 << 16 to yield 1 << 20 (1MB).
   602  		ReadSamplingMultiplier int64
   603  
   604  		// TableCacheShards is the number of shards per table cache.
   605  		// Reducing the value can reduce the number of idle goroutines per DB
   606  		// instance which can be useful in scenarios with a lot of DB instances
   607  		// and a large number of CPUs, but doing so can lead to higher contention
   608  		// in the table cache and reduced performance.
   609  		//
   610  		// The default value is the number of logical CPUs, which can be
   611  		// limited by runtime.GOMAXPROCS.
   612  		TableCacheShards int
   613  
   614  		// KeyValidationFunc is a function to validate a user key in an SSTable.
   615  		//
   616  		// Currently, this function is used to validate the smallest and largest
   617  		// keys in an SSTable undergoing compaction. In this case, returning an
   618  		// error from the validation function will result in a panic at runtime,
   619  		// given that there is rarely any way of recovering from malformed keys
   620  		// present in compacted files. By default, validation is not performed.
   621  		//
   622  		// Additional use-cases may be added in the future.
   623  		//
   624  		// NOTE: callers should take care to not mutate the key being validated.
   625  		KeyValidationFunc func(userKey []byte) error
   626  
   627  		// ValidateOnIngest schedules validation of sstables after they have
   628  		// been ingested.
   629  		//
   630  		// By default, this value is false.
   631  		ValidateOnIngest bool
   632  
   633  		// LevelMultiplier configures the size multiplier used to determine the
   634  		// desired size of each level of the LSM. Defaults to 10.
   635  		LevelMultiplier int
   636  
   637  		// MultiLevelCompactionHeuristic determines whether to add an additional
   638  		// level to a conventional two level compaction. If nil, a multilevel
   639  		// compaction will never get triggered.
   640  		MultiLevelCompactionHeuristic MultiLevelHeuristic
   641  
   642  		// MaxWriterConcurrency is used to indicate the maximum number of
   643  		// compression workers the compression queue is allowed to use. If
   644  		// MaxWriterConcurrency > 0, then the Writer will use parallelism, to
   645  		// compress and write blocks to disk. Otherwise, the writer will
   646  		// compress and write blocks to disk synchronously.
   647  		MaxWriterConcurrency int
   648  
   649  		// ForceWriterParallelism is used to force parallelism in the sstable
   650  		// Writer for the metamorphic tests. Even with the MaxWriterConcurrency
   651  		// option set, we only enable parallelism in the sstable Writer if there
   652  		// is enough CPU available, and this option bypasses that.
   653  		ForceWriterParallelism bool
   654  
   655  		// CPUWorkPermissionGranter should be set if Pebble should be given the
   656  		// ability to optionally schedule additional CPU. See the documentation
   657  		// for CPUWorkPermissionGranter for more details.
   658  		CPUWorkPermissionGranter CPUWorkPermissionGranter
   659  
   660  		// EnableValueBlocks is used to decide whether to enable writing
   661  		// TableFormatPebblev3 sstables. This setting is only respected by a
   662  		// specific subset of format major versions: FormatSSTableValueBlocks,
   663  		// FormatFlushableIngest and FormatPrePebblev1MarkedCompacted. In lower
   664  		// format major versions, value blocks are never enabled. In higher
   665  		// format major versions, value blocks are always enabled.
   666  		EnableValueBlocks func() bool
   667  
   668  		// ShortAttributeExtractor is used iff EnableValueBlocks() returns true
   669  		// (else ignored). If non-nil, a ShortAttribute can be extracted from the
   670  		// value and stored with the key, when the value is stored elsewhere.
   671  		ShortAttributeExtractor ShortAttributeExtractor
   672  
   673  		// RequiredInPlaceValueBound specifies an optional span of user key
   674  		// prefixes that are not-MVCC, but have a suffix. For these the values
   675  		// must be stored with the key, since the concept of "older versions" is
   676  		// not defined. It is also useful for statically known exclusions to value
   677  		// separation. In CockroachDB, this will be used for the lock table key
   678  		// space that has non-empty suffixes, but those locks don't represent
   679  		// actual MVCC versions (the suffix ordering is arbitrary). We will also
   680  		// need to add support for dynamically configured exclusions (we want the
   681  		// default to be to allow Pebble to decide whether to separate the value
   682  		// or not, hence this is structured as exclusions), for example, for users
   683  		// of CockroachDB to dynamically exclude certain tables.
   684  		//
   685  		// Any change in exclusion behavior takes effect only on future written
   686  		// sstables, and does not start rewriting existing sstables.
   687  		//
   688  		// Even ignoring changes in this setting, exclusions are interpreted as a
   689  		// guidance by Pebble, and not necessarily honored. Specifically, user
   690  		// keys with multiple Pebble-versions *may* have the older versions stored
   691  		// in value blocks.
   692  		RequiredInPlaceValueBound UserKeyPrefixBound
   693  
   694  		// DisableIngestAsFlushable disables lazy ingestion of sstables through
   695  		// a WAL write and memtable rotation. Only effectual if the the format
   696  		// major version is at least `FormatFlushableIngest`.
   697  		DisableIngestAsFlushable func() bool
   698  
   699  		// RemoteStorage enables use of remote storage (e.g. S3) for storing
   700  		// sstables. Setting this option enables use of CreateOnShared option and
   701  		// allows ingestion of external files.
   702  		RemoteStorage remote.StorageFactory
   703  
   704  		// If CreateOnShared is non-zero, new sstables are created on remote storage
   705  		// (using CreateOnSharedLocator and with the appropriate
   706  		// CreateOnSharedStrategy). These sstables can be shared between different
   707  		// Pebble instances; the lifecycle of such objects is managed by the
   708  		// remote.Storage constructed by options.RemoteStorage.
   709  		//
   710  		// Can only be used when RemoteStorage is set (and recognizes
   711  		// CreateOnSharedLocator).
   712  		CreateOnShared        remote.CreateOnSharedStrategy
   713  		CreateOnSharedLocator remote.Locator
   714  
   715  		// CacheSizeBytesBytes is the size of the on-disk block cache for objects
   716  		// on shared storage in bytes. If it is 0, no cache is used.
   717  		SecondaryCacheSizeBytes int64
   718  
   719  		// IneffectualPointDeleteCallback is called in compactions/flushes if any
   720  		// single delete is being elided without deleting a point set/merge.
   721  		IneffectualSingleDeleteCallback func(userKey []byte)
   722  
   723  		// SingleDeleteInvariantViolationCallback is called in compactions/flushes if any
   724  		// single delete has consumed a Set/Merge, and there is another immediately older
   725  		// Set/SetWithDelete/Merge. The user of Pebble has violated the invariant under
   726  		// which SingleDelete can be used correctly.
   727  		//
   728  		// Consider the sequence SingleDelete#3, Set#2, Set#1. There are three
   729  		// ways some of these keys can first meet in a compaction.
   730  		//
   731  		// - All 3 keys in the same compaction: this callback will detect the
   732  		//   violation.
   733  		//
   734  		// - SingleDelete#3, Set#2 meet in a compaction first: Both keys will
   735  		//   disappear. The violation will not be detected, and the DB will have
   736  		//   Set#1 which is likely incorrect (from the user's perspective).
   737  		//
   738  		// - Set#2, Set#1 meet in a compaction first: The output will be Set#2,
   739  		//   which will later be consumed by SingleDelete#3. The violation will
   740  		//   not be detected and the DB will be correct.
   741  		SingleDeleteInvariantViolationCallback func(userKey []byte)
   742  	}
   743  
   744  	// Filters is a map from filter policy name to filter policy. It is used for
   745  	// debugging tools which may be used on multiple databases configured with
   746  	// different filter policies. It is not necessary to populate this filters
   747  	// map during normal usage of a DB.
   748  	Filters map[string]FilterPolicy
   749  
   750  	// FlushDelayDeleteRange configures how long the database should wait before
   751  	// forcing a flush of a memtable that contains a range deletion. Disk space
   752  	// cannot be reclaimed until the range deletion is flushed. No automatic
   753  	// flush occurs if zero.
   754  	FlushDelayDeleteRange time.Duration
   755  
   756  	// FlushDelayRangeKey configures how long the database should wait before
   757  	// forcing a flush of a memtable that contains a range key. Range keys in
   758  	// the memtable prevent lazy combined iteration, so it's desirable to flush
   759  	// range keys promptly. No automatic flush occurs if zero.
   760  	FlushDelayRangeKey time.Duration
   761  
   762  	// FlushSplitBytes denotes the target number of bytes per sublevel in
   763  	// each flush split interval (i.e. range between two flush split keys)
   764  	// in L0 sstables. When set to zero, only a single sstable is generated
   765  	// by each flush. When set to a non-zero value, flushes are split at
   766  	// points to meet L0's TargetFileSize, any grandparent-related overlap
   767  	// options, and at boundary keys of L0 flush split intervals (which are
   768  	// targeted to contain around FlushSplitBytes bytes in each sublevel
   769  	// between pairs of boundary keys). Splitting sstables during flush
   770  	// allows increased compaction flexibility and concurrency when those
   771  	// tables are compacted to lower levels.
   772  	FlushSplitBytes int64
   773  
   774  	// FormatMajorVersion sets the format of on-disk files. It is
   775  	// recommended to set the format major version to an explicit
   776  	// version, as the default may change over time.
   777  	//
   778  	// At Open if the existing database is formatted using a later
   779  	// format major version that is known to this version of Pebble,
   780  	// Pebble will continue to use the later format major version. If
   781  	// the existing database's version is unknown, the caller may use
   782  	// FormatMostCompatible and will be able to open the database
   783  	// regardless of its actual version.
   784  	//
   785  	// If the existing database is formatted using a format major
   786  	// version earlier than the one specified, Open will automatically
   787  	// ratchet the database to the specified format major version.
   788  	FormatMajorVersion FormatMajorVersion
   789  
   790  	// FS provides the interface for persistent file storage.
   791  	//
   792  	// The default value uses the underlying operating system's file system.
   793  	FS vfs.FS
   794  
   795  	// Lock, if set, must be a database lock acquired through LockDirectory for
   796  	// the same directory passed to Open. If provided, Open will skip locking
   797  	// the directory. Closing the database will not release the lock, and it's
   798  	// the responsibility of the caller to release the lock after closing the
   799  	// database.
   800  	//
   801  	// Open will enforce that the Lock passed locks the same directory passed to
   802  	// Open. Concurrent calls to Open using the same Lock are detected and
   803  	// prohibited.
   804  	Lock *Lock
   805  
   806  	// The count of L0 files necessary to trigger an L0 compaction.
   807  	L0CompactionFileThreshold int
   808  
   809  	// The amount of L0 read-amplification necessary to trigger an L0 compaction.
   810  	L0CompactionThreshold int
   811  
   812  	// Hard limit on L0 read-amplification, computed as the number of L0
   813  	// sublevels. Writes are stopped when this threshold is reached.
   814  	L0StopWritesThreshold int
   815  
   816  	// The maximum number of bytes for LBase. The base level is the level which
   817  	// L0 is compacted into. The base level is determined dynamically based on
   818  	// the existing data in the LSM. The maximum number of bytes for other levels
   819  	// is computed dynamically based on the base level's maximum size. When the
   820  	// maximum number of bytes for a level is exceeded, compaction is requested.
   821  	LBaseMaxBytes int64
   822  
   823  	// Per-level options. Options for at least one level must be specified. The
   824  	// options for the last level are used for all subsequent levels.
   825  	Levels []LevelOptions
   826  
   827  	// LoggerAndTracer will be used, if non-nil, else Logger will be used and
   828  	// tracing will be a noop.
   829  
   830  	// Logger used to write log messages.
   831  	//
   832  	// The default logger uses the Go standard library log package.
   833  	Logger Logger
   834  	// LoggerAndTracer is used for writing log messages and traces.
   835  	LoggerAndTracer LoggerAndTracer
   836  
   837  	// MaxManifestFileSize is the maximum size the MANIFEST file is allowed to
   838  	// become. When the MANIFEST exceeds this size it is rolled over and a new
   839  	// MANIFEST is created.
   840  	MaxManifestFileSize int64
   841  
   842  	// MaxOpenFiles is a soft limit on the number of open files that can be
   843  	// used by the DB.
   844  	//
   845  	// The default value is 1000.
   846  	MaxOpenFiles int
   847  
   848  	// The size of a MemTable in steady state. The actual MemTable size starts at
   849  	// min(256KB, MemTableSize) and doubles for each subsequent MemTable up to
   850  	// MemTableSize. This reduces the memory pressure caused by MemTables for
   851  	// short lived (test) DB instances. Note that more than one MemTable can be
   852  	// in existence since flushing a MemTable involves creating a new one and
   853  	// writing the contents of the old one in the
   854  	// background. MemTableStopWritesThreshold places a hard limit on the size of
   855  	// the queued MemTables.
   856  	//
   857  	// The default value is 4MB.
   858  	MemTableSize uint64
   859  
   860  	// Hard limit on the number of queued of MemTables. Writes are stopped when
   861  	// the sum of the queued memtable sizes exceeds:
   862  	//   MemTableStopWritesThreshold * MemTableSize.
   863  	//
   864  	// This value should be at least 2 or writes will stop whenever a MemTable is
   865  	// being flushed.
   866  	//
   867  	// The default value is 2.
   868  	MemTableStopWritesThreshold int
   869  
   870  	// Merger defines the associative merge operation to use for merging values
   871  	// written with {Batch,DB}.Merge.
   872  	//
   873  	// The default merger concatenates values.
   874  	Merger *Merger
   875  
   876  	// MaxConcurrentCompactions specifies the maximum number of concurrent
   877  	// compactions. The default is 1. Concurrent compactions are performed
   878  	// - when L0 read-amplification passes the L0CompactionConcurrency threshold
   879  	// - for automatic background compactions
   880  	// - when a manual compaction for a level is split and parallelized
   881  	// MaxConcurrentCompactions must be greater than 0.
   882  	MaxConcurrentCompactions func() int
   883  
   884  	// DisableAutomaticCompactions dictates whether automatic compactions are
   885  	// scheduled or not. The default is false (enabled). This option is only used
   886  	// externally when running a manual compaction, and internally for tests.
   887  	DisableAutomaticCompactions bool
   888  
   889  	// NoSyncOnClose decides whether the Pebble instance will enforce a
   890  	// close-time synchronization (e.g., fdatasync() or sync_file_range())
   891  	// on files it writes to. Setting this to true removes the guarantee for a
   892  	// sync on close. Some implementations can still issue a non-blocking sync.
   893  	NoSyncOnClose bool
   894  
   895  	// NumPrevManifest is the number of non-current or older manifests which
   896  	// we want to keep around for debugging purposes. By default, we're going
   897  	// to keep one older manifest.
   898  	NumPrevManifest int
   899  
   900  	// ReadOnly indicates that the DB should be opened in read-only mode. Writes
   901  	// to the DB will return an error, background compactions are disabled, and
   902  	// the flush that normally occurs after replaying the WAL at startup is
   903  	// disabled.
   904  	ReadOnly bool
   905  
   906  	// TableCache is an initialized TableCache which should be set as an
   907  	// option if the DB needs to be initialized with a pre-existing table cache.
   908  	// If TableCache is nil, then a table cache which is unique to the DB instance
   909  	// is created. TableCache can be shared between db instances by setting it here.
   910  	// The TableCache set here must use the same underlying cache as Options.Cache
   911  	// and pebble will panic otherwise.
   912  	TableCache *TableCache
   913  
   914  	// TablePropertyCollectors is a list of TablePropertyCollector creation
   915  	// functions. A new TablePropertyCollector is created for each sstable built
   916  	// and lives for the lifetime of the table.
   917  	TablePropertyCollectors []func() TablePropertyCollector
   918  
   919  	// BlockPropertyCollectors is a list of BlockPropertyCollector creation
   920  	// functions. A new BlockPropertyCollector is created for each sstable
   921  	// built and lives for the lifetime of writing that table.
   922  	BlockPropertyCollectors []func() BlockPropertyCollector
   923  
   924  	// WALBytesPerSync sets the number of bytes to write to a WAL before calling
   925  	// Sync on it in the background. Just like with BytesPerSync above, this
   926  	// helps smooth out disk write latencies, and avoids cases where the OS
   927  	// writes a lot of buffered data to disk at once. However, this is less
   928  	// necessary with WALs, as many write operations already pass in
   929  	// Sync = true.
   930  	//
   931  	// The default value is 0, i.e. no background syncing. This matches the
   932  	// default behaviour in RocksDB.
   933  	WALBytesPerSync int
   934  
   935  	// WALDir specifies the directory to store write-ahead logs (WALs) in. If
   936  	// empty (the default), WALs will be stored in the same directory as sstables
   937  	// (i.e. the directory passed to pebble.Open).
   938  	WALDir string
   939  
   940  	// WALMinSyncInterval is the minimum duration between syncs of the WAL. If
   941  	// WAL syncs are requested faster than this interval, they will be
   942  	// artificially delayed. Introducing a small artificial delay (500us) between
   943  	// WAL syncs can allow more operations to arrive and reduce IO operations
   944  	// while having a minimal impact on throughput. This option is supplied as a
   945  	// closure in order to allow the value to be changed dynamically. The default
   946  	// value is 0.
   947  	//
   948  	// TODO(peter): rather than a closure, should there be another mechanism for
   949  	// changing options dynamically?
   950  	WALMinSyncInterval func() time.Duration
   951  
   952  	// TargetByteDeletionRate is the rate (in bytes per second) at which sstable file
   953  	// deletions are limited to (under normal circumstances).
   954  	//
   955  	// Deletion pacing is used to slow down deletions when compactions finish up
   956  	// or readers close and newly-obsolete files need cleaning up. Deleting lots
   957  	// of files at once can cause disk latency to go up on some SSDs, which this
   958  	// functionality guards against.
   959  	//
   960  	// This value is only a best-effort target; the effective rate can be
   961  	// higher if deletions are falling behind or disk space is running low.
   962  	//
   963  	// Setting this to 0 disables deletion pacing, which is also the default.
   964  	TargetByteDeletionRate int
   965  
   966  	// private options are only used by internal tests or are used internally
   967  	// for facilitating upgrade paths of unconfigurable functionality.
   968  	private struct {
   969  		// strictWALTail configures whether or not a database's WALs created
   970  		// prior to the most recent one should be interpreted strictly,
   971  		// requiring a clean EOF. RocksDB 6.2.1 and the version of Pebble
   972  		// included in CockroachDB 20.1 do not guarantee that closed WALs end
   973  		// cleanly. If this option is set within an OPTIONS file, Pebble
   974  		// interprets previous WALs strictly, requiring a clean EOF.
   975  		// Otherwise, it interprets them permissively in the same manner as
   976  		// RocksDB 6.2.1.
   977  		strictWALTail bool
   978  
   979  		// disableDeleteOnlyCompactions prevents the scheduling of delete-only
   980  		// compactions that drop sstables wholy covered by range tombstones or
   981  		// range key tombstones.
   982  		disableDeleteOnlyCompactions bool
   983  
   984  		// disableElisionOnlyCompactions prevents the scheduling of elision-only
   985  		// compactions that rewrite sstables in place in order to elide obsolete
   986  		// keys.
   987  		disableElisionOnlyCompactions bool
   988  
   989  		// disableLazyCombinedIteration is a private option used by the
   990  		// metamorphic tests to test equivalence between lazy-combined iteration
   991  		// and constructing the range-key iterator upfront. It's a private
   992  		// option to avoid littering the public interface with options that we
   993  		// do not want to allow users to actually configure.
   994  		disableLazyCombinedIteration bool
   995  
   996  		// A private option to disable stats collection.
   997  		disableTableStats bool
   998  
   999  		// testingAlwaysWaitForCleanup is set by some tests to force waiting for
  1000  		// obsolete file deletion (to make events deterministic).
  1001  		testingAlwaysWaitForCleanup bool
  1002  
  1003  		// fsCloser holds a closer that should be invoked after a DB using these
  1004  		// Options is closed. This is used to automatically stop the
  1005  		// long-running goroutine associated with the disk-health-checking FS.
  1006  		// See the initialization of FS in EnsureDefaults. Note that care has
  1007  		// been taken to ensure that it is still safe to continue using the FS
  1008  		// after this closer has been invoked. However, if write operations
  1009  		// against the FS are made after the DB is closed, the FS may leak a
  1010  		// goroutine indefinitely.
  1011  		fsCloser io.Closer
  1012  	}
  1013  }
  1014  
  1015  // ReadaheadConfig controls the use of read-ahead.
  1016  type ReadaheadConfig = objstorageprovider.ReadaheadConfig
  1017  
  1018  // DebugCheckLevels calls CheckLevels on the provided database.
  1019  // It may be set in the DebugCheck field of Options to check
  1020  // level invariants whenever a new version is installed.
  1021  func DebugCheckLevels(db *DB) error {
  1022  	return db.CheckLevels(nil)
  1023  }
  1024  
  1025  // EnsureDefaults ensures that the default values for all options are set if a
  1026  // valid value was not already specified. Returns the new options.
  1027  func (o *Options) EnsureDefaults() *Options {
  1028  	if o == nil {
  1029  		o = &Options{}
  1030  	}
  1031  	if o.BytesPerSync <= 0 {
  1032  		o.BytesPerSync = 512 << 10 // 512 KB
  1033  	}
  1034  	if o.Cleaner == nil {
  1035  		o.Cleaner = DeleteCleaner{}
  1036  	}
  1037  	if o.Comparer == nil {
  1038  		o.Comparer = DefaultComparer
  1039  	}
  1040  	if o.Experimental.DisableIngestAsFlushable == nil {
  1041  		o.Experimental.DisableIngestAsFlushable = func() bool { return false }
  1042  	}
  1043  	if o.Experimental.L0CompactionConcurrency <= 0 {
  1044  		o.Experimental.L0CompactionConcurrency = 10
  1045  	}
  1046  	if o.Experimental.CompactionDebtConcurrency <= 0 {
  1047  		o.Experimental.CompactionDebtConcurrency = 1 << 30 // 1 GB
  1048  	}
  1049  	if o.Experimental.KeyValidationFunc == nil {
  1050  		o.Experimental.KeyValidationFunc = func([]byte) error { return nil }
  1051  	}
  1052  	if o.L0CompactionThreshold <= 0 {
  1053  		o.L0CompactionThreshold = 4
  1054  	}
  1055  	if o.L0CompactionFileThreshold <= 0 {
  1056  		// Some justification for the default of 500:
  1057  		// Why not smaller?:
  1058  		// - The default target file size for L0 is 2MB, so 500 files is <= 1GB
  1059  		//   of data. At observed compaction speeds of > 20MB/s, L0 can be
  1060  		//   cleared of all files in < 1min, so this backlog is not huge.
  1061  		// - 500 files is low overhead for instantiating L0 sublevels from
  1062  		//   scratch.
  1063  		// - Lower values were observed to cause excessive and inefficient
  1064  		//   compactions out of L0 in a TPCC import benchmark.
  1065  		// Why not larger?:
  1066  		// - More than 1min to compact everything out of L0.
  1067  		// - CockroachDB's admission control system uses a threshold of 1000
  1068  		//   files to start throttling writes to Pebble. Using 500 here gives
  1069  		//   us headroom between when Pebble should start compacting L0 and
  1070  		//   when the admission control threshold is reached.
  1071  		//
  1072  		// We can revisit this default in the future based on better
  1073  		// experimental understanding.
  1074  		//
  1075  		// TODO(jackson): Experiment with slightly lower thresholds [or higher
  1076  		// admission control thresholds] to see whether a higher L0 score at the
  1077  		// threshold (currently 2.0) is necessary for some workloads to avoid
  1078  		// starving L0 in favor of lower-level compactions.
  1079  		o.L0CompactionFileThreshold = 500
  1080  	}
  1081  	if o.L0StopWritesThreshold <= 0 {
  1082  		o.L0StopWritesThreshold = 12
  1083  	}
  1084  	if o.LBaseMaxBytes <= 0 {
  1085  		o.LBaseMaxBytes = 64 << 20 // 64 MB
  1086  	}
  1087  	if o.Levels == nil {
  1088  		o.Levels = make([]LevelOptions, 1)
  1089  		for i := range o.Levels {
  1090  			if i > 0 {
  1091  				l := &o.Levels[i]
  1092  				if l.TargetFileSize <= 0 {
  1093  					l.TargetFileSize = o.Levels[i-1].TargetFileSize * 2
  1094  				}
  1095  			}
  1096  			o.Levels[i].EnsureDefaults()
  1097  		}
  1098  	} else {
  1099  		for i := range o.Levels {
  1100  			o.Levels[i].EnsureDefaults()
  1101  		}
  1102  	}
  1103  	if o.Logger == nil {
  1104  		o.Logger = DefaultLogger
  1105  	}
  1106  	if o.EventListener == nil {
  1107  		o.EventListener = &EventListener{}
  1108  	}
  1109  	o.EventListener.EnsureDefaults(o.Logger)
  1110  	if o.MaxManifestFileSize == 0 {
  1111  		o.MaxManifestFileSize = 128 << 20 // 128 MB
  1112  	}
  1113  	if o.MaxOpenFiles == 0 {
  1114  		o.MaxOpenFiles = 1000
  1115  	}
  1116  	if o.MemTableSize <= 0 {
  1117  		o.MemTableSize = 4 << 20 // 4 MB
  1118  	}
  1119  	if o.MemTableStopWritesThreshold <= 0 {
  1120  		o.MemTableStopWritesThreshold = 2
  1121  	}
  1122  	if o.Merger == nil {
  1123  		o.Merger = DefaultMerger
  1124  	}
  1125  	o.private.strictWALTail = true
  1126  	if o.MaxConcurrentCompactions == nil {
  1127  		o.MaxConcurrentCompactions = func() int { return 1 }
  1128  	}
  1129  	if o.NumPrevManifest <= 0 {
  1130  		o.NumPrevManifest = 1
  1131  	}
  1132  
  1133  	if o.FormatMajorVersion == FormatDefault {
  1134  		o.FormatMajorVersion = FormatMostCompatible
  1135  	}
  1136  
  1137  	if o.FS == nil {
  1138  		o.WithFSDefaults()
  1139  	}
  1140  	if o.FlushSplitBytes <= 0 {
  1141  		o.FlushSplitBytes = 2 * o.Levels[0].TargetFileSize
  1142  	}
  1143  	if o.Experimental.LevelMultiplier <= 0 {
  1144  		o.Experimental.LevelMultiplier = defaultLevelMultiplier
  1145  	}
  1146  	if o.Experimental.ReadCompactionRate == 0 {
  1147  		o.Experimental.ReadCompactionRate = 16000
  1148  	}
  1149  	if o.Experimental.ReadSamplingMultiplier == 0 {
  1150  		o.Experimental.ReadSamplingMultiplier = 1 << 4
  1151  	}
  1152  	if o.Experimental.TableCacheShards <= 0 {
  1153  		o.Experimental.TableCacheShards = runtime.GOMAXPROCS(0)
  1154  	}
  1155  	if o.Experimental.CPUWorkPermissionGranter == nil {
  1156  		o.Experimental.CPUWorkPermissionGranter = defaultCPUWorkGranter{}
  1157  	}
  1158  	if o.Experimental.MultiLevelCompactionHeuristic == nil {
  1159  		o.Experimental.MultiLevelCompactionHeuristic = WriteAmpHeuristic{}
  1160  	}
  1161  
  1162  	o.initMaps()
  1163  	return o
  1164  }
  1165  
  1166  // WithFSDefaults configures the Options to wrap the configured filesystem with
  1167  // the default virtual file system middleware, like disk-health checking.
  1168  func (o *Options) WithFSDefaults() *Options {
  1169  	if o.FS == nil {
  1170  		o.FS = vfs.Default
  1171  	}
  1172  	o.FS, o.private.fsCloser = vfs.WithDiskHealthChecks(o.FS, 5*time.Second,
  1173  		func(info vfs.DiskSlowInfo) {
  1174  			o.EventListener.DiskSlow(info)
  1175  		})
  1176  	return o
  1177  }
  1178  
  1179  // AddEventListener adds the provided event listener to the Options, in addition
  1180  // to any existing event listener.
  1181  func (o *Options) AddEventListener(l EventListener) {
  1182  	if o.EventListener != nil {
  1183  		l = TeeEventListener(l, *o.EventListener)
  1184  	}
  1185  	o.EventListener = &l
  1186  }
  1187  
  1188  func (o *Options) equal() Equal {
  1189  	if o.Comparer.Equal == nil {
  1190  		return bytes.Equal
  1191  	}
  1192  	return o.Comparer.Equal
  1193  }
  1194  
  1195  // initMaps initializes the Comparers, Filters, and Mergers maps.
  1196  func (o *Options) initMaps() {
  1197  	for i := range o.Levels {
  1198  		l := &o.Levels[i]
  1199  		if l.FilterPolicy != nil {
  1200  			if o.Filters == nil {
  1201  				o.Filters = make(map[string]FilterPolicy)
  1202  			}
  1203  			name := l.FilterPolicy.Name()
  1204  			if _, ok := o.Filters[name]; !ok {
  1205  				o.Filters[name] = l.FilterPolicy
  1206  			}
  1207  		}
  1208  	}
  1209  }
  1210  
  1211  // Level returns the LevelOptions for the specified level.
  1212  func (o *Options) Level(level int) LevelOptions {
  1213  	if level < len(o.Levels) {
  1214  		return o.Levels[level]
  1215  	}
  1216  	n := len(o.Levels) - 1
  1217  	l := o.Levels[n]
  1218  	for i := n; i < level; i++ {
  1219  		l.TargetFileSize *= 2
  1220  	}
  1221  	return l
  1222  }
  1223  
  1224  // Clone creates a shallow-copy of the supplied options.
  1225  func (o *Options) Clone() *Options {
  1226  	n := &Options{}
  1227  	if o != nil {
  1228  		*n = *o
  1229  	}
  1230  	return n
  1231  }
  1232  
  1233  func filterPolicyName(p FilterPolicy) string {
  1234  	if p == nil {
  1235  		return "none"
  1236  	}
  1237  	return p.Name()
  1238  }
  1239  
  1240  func (o *Options) String() string {
  1241  	var buf bytes.Buffer
  1242  
  1243  	cacheSize := int64(cacheDefaultSize)
  1244  	if o.Cache != nil {
  1245  		cacheSize = o.Cache.MaxSize()
  1246  	}
  1247  
  1248  	fmt.Fprintf(&buf, "[Version]\n")
  1249  	fmt.Fprintf(&buf, "  pebble_version=0.1\n")
  1250  	fmt.Fprintf(&buf, "\n")
  1251  	fmt.Fprintf(&buf, "[Options]\n")
  1252  	fmt.Fprintf(&buf, "  bytes_per_sync=%d\n", o.BytesPerSync)
  1253  	fmt.Fprintf(&buf, "  cache_size=%d\n", cacheSize)
  1254  	fmt.Fprintf(&buf, "  cleaner=%s\n", o.Cleaner)
  1255  	fmt.Fprintf(&buf, "  compaction_debt_concurrency=%d\n", o.Experimental.CompactionDebtConcurrency)
  1256  	fmt.Fprintf(&buf, "  comparer=%s\n", o.Comparer.Name)
  1257  	fmt.Fprintf(&buf, "  disable_wal=%t\n", o.DisableWAL)
  1258  	if o.Experimental.DisableIngestAsFlushable != nil && o.Experimental.DisableIngestAsFlushable() {
  1259  		fmt.Fprintf(&buf, "  disable_ingest_as_flushable=%t\n", true)
  1260  	}
  1261  	fmt.Fprintf(&buf, "  flush_delay_delete_range=%s\n", o.FlushDelayDeleteRange)
  1262  	fmt.Fprintf(&buf, "  flush_delay_range_key=%s\n", o.FlushDelayRangeKey)
  1263  	fmt.Fprintf(&buf, "  flush_split_bytes=%d\n", o.FlushSplitBytes)
  1264  	fmt.Fprintf(&buf, "  format_major_version=%d\n", o.FormatMajorVersion)
  1265  	fmt.Fprintf(&buf, "  l0_compaction_concurrency=%d\n", o.Experimental.L0CompactionConcurrency)
  1266  	fmt.Fprintf(&buf, "  l0_compaction_file_threshold=%d\n", o.L0CompactionFileThreshold)
  1267  	fmt.Fprintf(&buf, "  l0_compaction_threshold=%d\n", o.L0CompactionThreshold)
  1268  	fmt.Fprintf(&buf, "  l0_stop_writes_threshold=%d\n", o.L0StopWritesThreshold)
  1269  	fmt.Fprintf(&buf, "  lbase_max_bytes=%d\n", o.LBaseMaxBytes)
  1270  	if o.Experimental.LevelMultiplier != defaultLevelMultiplier {
  1271  		fmt.Fprintf(&buf, "  level_multiplier=%d\n", o.Experimental.LevelMultiplier)
  1272  	}
  1273  	fmt.Fprintf(&buf, "  max_concurrent_compactions=%d\n", o.MaxConcurrentCompactions())
  1274  	fmt.Fprintf(&buf, "  max_manifest_file_size=%d\n", o.MaxManifestFileSize)
  1275  	fmt.Fprintf(&buf, "  max_open_files=%d\n", o.MaxOpenFiles)
  1276  	fmt.Fprintf(&buf, "  mem_table_size=%d\n", o.MemTableSize)
  1277  	fmt.Fprintf(&buf, "  mem_table_stop_writes_threshold=%d\n", o.MemTableStopWritesThreshold)
  1278  	fmt.Fprintf(&buf, "  min_deletion_rate=%d\n", o.TargetByteDeletionRate)
  1279  	fmt.Fprintf(&buf, "  merger=%s\n", o.Merger.Name)
  1280  	fmt.Fprintf(&buf, "  read_compaction_rate=%d\n", o.Experimental.ReadCompactionRate)
  1281  	fmt.Fprintf(&buf, "  read_sampling_multiplier=%d\n", o.Experimental.ReadSamplingMultiplier)
  1282  	fmt.Fprintf(&buf, "  strict_wal_tail=%t\n", o.private.strictWALTail)
  1283  	fmt.Fprintf(&buf, "  table_cache_shards=%d\n", o.Experimental.TableCacheShards)
  1284  	fmt.Fprintf(&buf, "  table_property_collectors=[")
  1285  	for i := range o.TablePropertyCollectors {
  1286  		if i > 0 {
  1287  			fmt.Fprintf(&buf, ",")
  1288  		}
  1289  		// NB: This creates a new TablePropertyCollector, but Options.String() is
  1290  		// called rarely so the overhead of doing so is not consequential.
  1291  		fmt.Fprintf(&buf, "%s", o.TablePropertyCollectors[i]().Name())
  1292  	}
  1293  	fmt.Fprintf(&buf, "]\n")
  1294  	fmt.Fprintf(&buf, "  validate_on_ingest=%t\n", o.Experimental.ValidateOnIngest)
  1295  	fmt.Fprintf(&buf, "  wal_dir=%s\n", o.WALDir)
  1296  	fmt.Fprintf(&buf, "  wal_bytes_per_sync=%d\n", o.WALBytesPerSync)
  1297  	fmt.Fprintf(&buf, "  max_writer_concurrency=%d\n", o.Experimental.MaxWriterConcurrency)
  1298  	fmt.Fprintf(&buf, "  force_writer_parallelism=%t\n", o.Experimental.ForceWriterParallelism)
  1299  	fmt.Fprintf(&buf, "  secondary_cache_size_bytes=%d\n", o.Experimental.SecondaryCacheSizeBytes)
  1300  	fmt.Fprintf(&buf, "  create_on_shared=%d\n", o.Experimental.CreateOnShared)
  1301  
  1302  	// Private options.
  1303  	//
  1304  	// These options are only encoded if true, because we do not want them to
  1305  	// appear in production serialized Options files, since they're testing-only
  1306  	// options. They're only serialized when true, which still ensures that the
  1307  	// metamorphic tests may propagate them to subprocesses.
  1308  	if o.private.disableDeleteOnlyCompactions {
  1309  		fmt.Fprintln(&buf, "  disable_delete_only_compactions=true")
  1310  	}
  1311  	if o.private.disableElisionOnlyCompactions {
  1312  		fmt.Fprintln(&buf, "  disable_elision_only_compactions=true")
  1313  	}
  1314  	if o.private.disableLazyCombinedIteration {
  1315  		fmt.Fprintln(&buf, "  disable_lazy_combined_iteration=true")
  1316  	}
  1317  
  1318  	for i := range o.Levels {
  1319  		l := &o.Levels[i]
  1320  		fmt.Fprintf(&buf, "\n")
  1321  		fmt.Fprintf(&buf, "[Level \"%d\"]\n", i)
  1322  		fmt.Fprintf(&buf, "  block_restart_interval=%d\n", l.BlockRestartInterval)
  1323  		fmt.Fprintf(&buf, "  block_size=%d\n", l.BlockSize)
  1324  		fmt.Fprintf(&buf, "  block_size_threshold=%d\n", l.BlockSizeThreshold)
  1325  		fmt.Fprintf(&buf, "  compression=%s\n", l.Compression)
  1326  		fmt.Fprintf(&buf, "  filter_policy=%s\n", filterPolicyName(l.FilterPolicy))
  1327  		fmt.Fprintf(&buf, "  filter_type=%s\n", l.FilterType)
  1328  		fmt.Fprintf(&buf, "  index_block_size=%d\n", l.IndexBlockSize)
  1329  		fmt.Fprintf(&buf, "  target_file_size=%d\n", l.TargetFileSize)
  1330  	}
  1331  
  1332  	return buf.String()
  1333  }
  1334  
  1335  func parseOptions(s string, fn func(section, key, value string) error) error {
  1336  	var section string
  1337  	for _, line := range strings.Split(s, "\n") {
  1338  		line = strings.TrimSpace(line)
  1339  		if len(line) == 0 {
  1340  			// Skip blank lines.
  1341  			continue
  1342  		}
  1343  		if line[0] == ';' || line[0] == '#' {
  1344  			// Skip comments.
  1345  			continue
  1346  		}
  1347  		n := len(line)
  1348  		if line[0] == '[' && line[n-1] == ']' {
  1349  			// Parse section.
  1350  			section = line[1 : n-1]
  1351  			continue
  1352  		}
  1353  
  1354  		pos := strings.Index(line, "=")
  1355  		if pos < 0 {
  1356  			const maxLen = 50
  1357  			if len(line) > maxLen {
  1358  				line = line[:maxLen-3] + "..."
  1359  			}
  1360  			return base.CorruptionErrorf("invalid key=value syntax: %q", errors.Safe(line))
  1361  		}
  1362  
  1363  		key := strings.TrimSpace(line[:pos])
  1364  		value := strings.TrimSpace(line[pos+1:])
  1365  
  1366  		// RocksDB uses a similar (INI-style) syntax for the OPTIONS file, but
  1367  		// different section names and keys. The "CFOptions ..." paths are the
  1368  		// RocksDB versions which we map to the Pebble paths.
  1369  		mappedSection := section
  1370  		if section == `CFOptions "default"` {
  1371  			mappedSection = "Options"
  1372  			switch key {
  1373  			case "comparator":
  1374  				key = "comparer"
  1375  			case "merge_operator":
  1376  				key = "merger"
  1377  			}
  1378  		}
  1379  
  1380  		if err := fn(mappedSection, key, value); err != nil {
  1381  			return err
  1382  		}
  1383  	}
  1384  	return nil
  1385  }
  1386  
  1387  // ParseHooks contains callbacks to create options fields which can have
  1388  // user-defined implementations.
  1389  type ParseHooks struct {
  1390  	NewCache        func(size int64) *Cache
  1391  	NewCleaner      func(name string) (Cleaner, error)
  1392  	NewComparer     func(name string) (*Comparer, error)
  1393  	NewFilterPolicy func(name string) (FilterPolicy, error)
  1394  	NewMerger       func(name string) (*Merger, error)
  1395  	SkipUnknown     func(name, value string) bool
  1396  }
  1397  
  1398  // Parse parses the options from the specified string. Note that certain
  1399  // options cannot be parsed into populated fields. For example, comparer and
  1400  // merger.
  1401  func (o *Options) Parse(s string, hooks *ParseHooks) error {
  1402  	return parseOptions(s, func(section, key, value string) error {
  1403  		// WARNING: DO NOT remove entries from the switches below because doing so
  1404  		// causes a key previously written to the OPTIONS file to be considered unknown,
  1405  		// a backwards incompatible change. Instead, leave in support for parsing the
  1406  		// key but simply don't parse the value.
  1407  
  1408  		switch {
  1409  		case section == "Version":
  1410  			switch key {
  1411  			case "pebble_version":
  1412  			default:
  1413  				if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
  1414  					return nil
  1415  				}
  1416  				return errors.Errorf("pebble: unknown option: %s.%s",
  1417  					errors.Safe(section), errors.Safe(key))
  1418  			}
  1419  			return nil
  1420  
  1421  		case section == "Options":
  1422  			var err error
  1423  			switch key {
  1424  			case "bytes_per_sync":
  1425  				o.BytesPerSync, err = strconv.Atoi(value)
  1426  			case "cache_size":
  1427  				var n int64
  1428  				n, err = strconv.ParseInt(value, 10, 64)
  1429  				if err == nil && hooks != nil && hooks.NewCache != nil {
  1430  					if o.Cache != nil {
  1431  						o.Cache.Unref()
  1432  					}
  1433  					o.Cache = hooks.NewCache(n)
  1434  				}
  1435  				// We avoid calling cache.New in parsing because it makes it
  1436  				// too easy to leak a cache.
  1437  			case "cleaner":
  1438  				switch value {
  1439  				case "archive":
  1440  					o.Cleaner = ArchiveCleaner{}
  1441  				case "delete":
  1442  					o.Cleaner = DeleteCleaner{}
  1443  				default:
  1444  					if hooks != nil && hooks.NewCleaner != nil {
  1445  						o.Cleaner, err = hooks.NewCleaner(value)
  1446  					}
  1447  				}
  1448  			case "comparer":
  1449  				switch value {
  1450  				case "leveldb.BytewiseComparator":
  1451  					o.Comparer = DefaultComparer
  1452  				default:
  1453  					if hooks != nil && hooks.NewComparer != nil {
  1454  						o.Comparer, err = hooks.NewComparer(value)
  1455  					}
  1456  				}
  1457  			case "compaction_debt_concurrency":
  1458  				o.Experimental.CompactionDebtConcurrency, err = strconv.ParseUint(value, 10, 64)
  1459  			case "delete_range_flush_delay":
  1460  				// NB: This is a deprecated serialization of the
  1461  				// `flush_delay_delete_range`.
  1462  				o.FlushDelayDeleteRange, err = time.ParseDuration(value)
  1463  			case "disable_delete_only_compactions":
  1464  				o.private.disableDeleteOnlyCompactions, err = strconv.ParseBool(value)
  1465  			case "disable_elision_only_compactions":
  1466  				o.private.disableElisionOnlyCompactions, err = strconv.ParseBool(value)
  1467  			case "disable_ingest_as_flushable":
  1468  				var v bool
  1469  				v, err = strconv.ParseBool(value)
  1470  				if err == nil {
  1471  					o.Experimental.DisableIngestAsFlushable = func() bool { return v }
  1472  				}
  1473  			case "disable_lazy_combined_iteration":
  1474  				o.private.disableLazyCombinedIteration, err = strconv.ParseBool(value)
  1475  			case "disable_wal":
  1476  				o.DisableWAL, err = strconv.ParseBool(value)
  1477  			case "flush_delay_delete_range":
  1478  				o.FlushDelayDeleteRange, err = time.ParseDuration(value)
  1479  			case "flush_delay_range_key":
  1480  				o.FlushDelayRangeKey, err = time.ParseDuration(value)
  1481  			case "flush_split_bytes":
  1482  				o.FlushSplitBytes, err = strconv.ParseInt(value, 10, 64)
  1483  			case "format_major_version":
  1484  				// NB: The version written here may be stale. Open does
  1485  				// not use the format major version encoded in the
  1486  				// OPTIONS file other than to validate that the encoded
  1487  				// version is valid right here.
  1488  				var v uint64
  1489  				v, err = strconv.ParseUint(value, 10, 64)
  1490  				if vers := FormatMajorVersion(v); vers > internalFormatNewest || vers == FormatDefault {
  1491  					err = errors.Newf("unknown format major version %d", o.FormatMajorVersion)
  1492  				}
  1493  				if err == nil {
  1494  					o.FormatMajorVersion = FormatMajorVersion(v)
  1495  				}
  1496  			case "l0_compaction_concurrency":
  1497  				o.Experimental.L0CompactionConcurrency, err = strconv.Atoi(value)
  1498  			case "l0_compaction_file_threshold":
  1499  				o.L0CompactionFileThreshold, err = strconv.Atoi(value)
  1500  			case "l0_compaction_threshold":
  1501  				o.L0CompactionThreshold, err = strconv.Atoi(value)
  1502  			case "l0_stop_writes_threshold":
  1503  				o.L0StopWritesThreshold, err = strconv.Atoi(value)
  1504  			case "l0_sublevel_compactions":
  1505  				// Do nothing; option existed in older versions of pebble.
  1506  			case "lbase_max_bytes":
  1507  				o.LBaseMaxBytes, err = strconv.ParseInt(value, 10, 64)
  1508  			case "level_multiplier":
  1509  				o.Experimental.LevelMultiplier, err = strconv.Atoi(value)
  1510  			case "max_concurrent_compactions":
  1511  				var concurrentCompactions int
  1512  				concurrentCompactions, err = strconv.Atoi(value)
  1513  				if concurrentCompactions <= 0 {
  1514  					err = errors.New("max_concurrent_compactions cannot be <= 0")
  1515  				} else {
  1516  					o.MaxConcurrentCompactions = func() int { return concurrentCompactions }
  1517  				}
  1518  			case "max_manifest_file_size":
  1519  				o.MaxManifestFileSize, err = strconv.ParseInt(value, 10, 64)
  1520  			case "max_open_files":
  1521  				o.MaxOpenFiles, err = strconv.Atoi(value)
  1522  			case "mem_table_size":
  1523  				o.MemTableSize, err = strconv.ParseUint(value, 10, 64)
  1524  			case "mem_table_stop_writes_threshold":
  1525  				o.MemTableStopWritesThreshold, err = strconv.Atoi(value)
  1526  			case "min_compaction_rate":
  1527  				// Do nothing; option existed in older versions of pebble, and
  1528  				// may be meaningful again eventually.
  1529  			case "min_deletion_rate":
  1530  				o.TargetByteDeletionRate, err = strconv.Atoi(value)
  1531  			case "min_flush_rate":
  1532  				// Do nothing; option existed in older versions of pebble, and
  1533  				// may be meaningful again eventually.
  1534  			case "point_tombstone_weight":
  1535  				// Do nothing; deprecated.
  1536  			case "strict_wal_tail":
  1537  				o.private.strictWALTail, err = strconv.ParseBool(value)
  1538  			case "merger":
  1539  				switch value {
  1540  				case "nullptr":
  1541  					o.Merger = nil
  1542  				case "pebble.concatenate":
  1543  					o.Merger = DefaultMerger
  1544  				default:
  1545  					if hooks != nil && hooks.NewMerger != nil {
  1546  						o.Merger, err = hooks.NewMerger(value)
  1547  					}
  1548  				}
  1549  			case "read_compaction_rate":
  1550  				o.Experimental.ReadCompactionRate, err = strconv.ParseInt(value, 10, 64)
  1551  			case "read_sampling_multiplier":
  1552  				o.Experimental.ReadSamplingMultiplier, err = strconv.ParseInt(value, 10, 64)
  1553  			case "table_cache_shards":
  1554  				o.Experimental.TableCacheShards, err = strconv.Atoi(value)
  1555  			case "table_format":
  1556  				switch value {
  1557  				case "leveldb":
  1558  				case "rocksdbv2":
  1559  				default:
  1560  					return errors.Errorf("pebble: unknown table format: %q", errors.Safe(value))
  1561  				}
  1562  			case "table_property_collectors":
  1563  				// TODO(peter): set o.TablePropertyCollectors
  1564  			case "validate_on_ingest":
  1565  				o.Experimental.ValidateOnIngest, err = strconv.ParseBool(value)
  1566  			case "wal_dir":
  1567  				o.WALDir = value
  1568  			case "wal_bytes_per_sync":
  1569  				o.WALBytesPerSync, err = strconv.Atoi(value)
  1570  			case "max_writer_concurrency":
  1571  				o.Experimental.MaxWriterConcurrency, err = strconv.Atoi(value)
  1572  			case "force_writer_parallelism":
  1573  				o.Experimental.ForceWriterParallelism, err = strconv.ParseBool(value)
  1574  			case "secondary_cache_size_bytes":
  1575  				o.Experimental.SecondaryCacheSizeBytes, err = strconv.ParseInt(value, 10, 64)
  1576  			case "create_on_shared":
  1577  				var createOnSharedInt int64
  1578  				createOnSharedInt, err = strconv.ParseInt(value, 10, 64)
  1579  				o.Experimental.CreateOnShared = remote.CreateOnSharedStrategy(createOnSharedInt)
  1580  			default:
  1581  				if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
  1582  					return nil
  1583  				}
  1584  				return errors.Errorf("pebble: unknown option: %s.%s",
  1585  					errors.Safe(section), errors.Safe(key))
  1586  			}
  1587  			return err
  1588  
  1589  		case strings.HasPrefix(section, "Level "):
  1590  			var index int
  1591  			if n, err := fmt.Sscanf(section, `Level "%d"`, &index); err != nil {
  1592  				return err
  1593  			} else if n != 1 {
  1594  				if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section, value) {
  1595  					return nil
  1596  				}
  1597  				return errors.Errorf("pebble: unknown section: %q", errors.Safe(section))
  1598  			}
  1599  
  1600  			if len(o.Levels) <= index {
  1601  				newLevels := make([]LevelOptions, index+1)
  1602  				copy(newLevels, o.Levels)
  1603  				o.Levels = newLevels
  1604  			}
  1605  			l := &o.Levels[index]
  1606  
  1607  			var err error
  1608  			switch key {
  1609  			case "block_restart_interval":
  1610  				l.BlockRestartInterval, err = strconv.Atoi(value)
  1611  			case "block_size":
  1612  				l.BlockSize, err = strconv.Atoi(value)
  1613  			case "block_size_threshold":
  1614  				l.BlockSizeThreshold, err = strconv.Atoi(value)
  1615  			case "compression":
  1616  				switch value {
  1617  				case "Default":
  1618  					l.Compression = DefaultCompression
  1619  				case "NoCompression":
  1620  					l.Compression = NoCompression
  1621  				case "Snappy":
  1622  					l.Compression = SnappyCompression
  1623  				case "ZSTD":
  1624  					l.Compression = ZstdCompression
  1625  				default:
  1626  					return errors.Errorf("pebble: unknown compression: %q", errors.Safe(value))
  1627  				}
  1628  			case "filter_policy":
  1629  				if hooks != nil && hooks.NewFilterPolicy != nil {
  1630  					l.FilterPolicy, err = hooks.NewFilterPolicy(value)
  1631  				}
  1632  			case "filter_type":
  1633  				switch value {
  1634  				case "table":
  1635  					l.FilterType = TableFilter
  1636  				default:
  1637  					return errors.Errorf("pebble: unknown filter type: %q", errors.Safe(value))
  1638  				}
  1639  			case "index_block_size":
  1640  				l.IndexBlockSize, err = strconv.Atoi(value)
  1641  			case "target_file_size":
  1642  				l.TargetFileSize, err = strconv.ParseInt(value, 10, 64)
  1643  			default:
  1644  				if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
  1645  					return nil
  1646  				}
  1647  				return errors.Errorf("pebble: unknown option: %s.%s", errors.Safe(section), errors.Safe(key))
  1648  			}
  1649  			return err
  1650  		}
  1651  		if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
  1652  			return nil
  1653  		}
  1654  		return errors.Errorf("pebble: unknown section: %q", errors.Safe(section))
  1655  	})
  1656  }
  1657  
  1658  func (o *Options) checkOptions(s string) (strictWALTail bool, err error) {
  1659  	// TODO(jackson): Refactor to avoid awkwardness of the strictWALTail return value.
  1660  	return strictWALTail, parseOptions(s, func(section, key, value string) error {
  1661  		switch section + "." + key {
  1662  		case "Options.comparer":
  1663  			if value != o.Comparer.Name {
  1664  				return errors.Errorf("pebble: comparer name from file %q != comparer name from options %q",
  1665  					errors.Safe(value), errors.Safe(o.Comparer.Name))
  1666  			}
  1667  		case "Options.merger":
  1668  			// RocksDB allows the merge operator to be unspecified, in which case it
  1669  			// shows up as "nullptr".
  1670  			if value != "nullptr" && value != o.Merger.Name {
  1671  				return errors.Errorf("pebble: merger name from file %q != merger name from options %q",
  1672  					errors.Safe(value), errors.Safe(o.Merger.Name))
  1673  			}
  1674  		case "Options.strict_wal_tail":
  1675  			strictWALTail, err = strconv.ParseBool(value)
  1676  			if err != nil {
  1677  				return errors.Errorf("pebble: error parsing strict_wal_tail value %q: %w", value, err)
  1678  			}
  1679  		}
  1680  		return nil
  1681  	})
  1682  }
  1683  
  1684  // Check verifies the options are compatible with the previous options
  1685  // serialized by Options.String(). For example, the Comparer and Merger must be
  1686  // the same, or data will not be able to be properly read from the DB.
  1687  func (o *Options) Check(s string) error {
  1688  	_, err := o.checkOptions(s)
  1689  	return err
  1690  }
  1691  
  1692  // Validate verifies that the options are mutually consistent. For example,
  1693  // L0StopWritesThreshold must be >= L0CompactionThreshold, otherwise a write
  1694  // stall would persist indefinitely.
  1695  func (o *Options) Validate() error {
  1696  	// Note that we can presume Options.EnsureDefaults has been called, so there
  1697  	// is no need to check for zero values.
  1698  
  1699  	var buf strings.Builder
  1700  	if o.Experimental.L0CompactionConcurrency < 1 {
  1701  		fmt.Fprintf(&buf, "L0CompactionConcurrency (%d) must be >= 1\n",
  1702  			o.Experimental.L0CompactionConcurrency)
  1703  	}
  1704  	if o.L0StopWritesThreshold < o.L0CompactionThreshold {
  1705  		fmt.Fprintf(&buf, "L0StopWritesThreshold (%d) must be >= L0CompactionThreshold (%d)\n",
  1706  			o.L0StopWritesThreshold, o.L0CompactionThreshold)
  1707  	}
  1708  	if uint64(o.MemTableSize) >= maxMemTableSize {
  1709  		fmt.Fprintf(&buf, "MemTableSize (%s) must be < %s\n",
  1710  			humanize.Bytes.Uint64(uint64(o.MemTableSize)), humanize.Bytes.Uint64(maxMemTableSize))
  1711  	}
  1712  	if o.MemTableStopWritesThreshold < 2 {
  1713  		fmt.Fprintf(&buf, "MemTableStopWritesThreshold (%d) must be >= 2\n",
  1714  			o.MemTableStopWritesThreshold)
  1715  	}
  1716  	if o.FormatMajorVersion > internalFormatNewest {
  1717  		fmt.Fprintf(&buf, "FormatMajorVersion (%d) must be <= %d\n",
  1718  			o.FormatMajorVersion, internalFormatNewest)
  1719  	}
  1720  	if o.TableCache != nil && o.Cache != o.TableCache.cache {
  1721  		fmt.Fprintf(&buf, "underlying cache in the TableCache and the Cache dont match\n")
  1722  	}
  1723  	if buf.Len() == 0 {
  1724  		return nil
  1725  	}
  1726  	return errors.New(buf.String())
  1727  }
  1728  
  1729  // MakeReaderOptions constructs sstable.ReaderOptions from the corresponding
  1730  // options in the receiver.
  1731  func (o *Options) MakeReaderOptions() sstable.ReaderOptions {
  1732  	var readerOpts sstable.ReaderOptions
  1733  	if o != nil {
  1734  		readerOpts.Cache = o.Cache
  1735  		readerOpts.LoadBlockSema = o.LoadBlockSema
  1736  		readerOpts.Comparer = o.Comparer
  1737  		readerOpts.Filters = o.Filters
  1738  		if o.Merger != nil {
  1739  			readerOpts.Merge = o.Merger.Merge
  1740  			readerOpts.MergerName = o.Merger.Name
  1741  		}
  1742  		readerOpts.LoggerAndTracer = o.LoggerAndTracer
  1743  	}
  1744  	return readerOpts
  1745  }
  1746  
  1747  // MakeWriterOptions constructs sstable.WriterOptions for the specified level
  1748  // from the corresponding options in the receiver.
  1749  func (o *Options) MakeWriterOptions(level int, format sstable.TableFormat) sstable.WriterOptions {
  1750  	var writerOpts sstable.WriterOptions
  1751  	writerOpts.TableFormat = format
  1752  	if o != nil {
  1753  		writerOpts.Cache = o.Cache
  1754  		writerOpts.Comparer = o.Comparer
  1755  		if o.Merger != nil {
  1756  			writerOpts.MergerName = o.Merger.Name
  1757  		}
  1758  		writerOpts.TablePropertyCollectors = o.TablePropertyCollectors
  1759  		writerOpts.BlockPropertyCollectors = o.BlockPropertyCollectors
  1760  	}
  1761  	if format >= sstable.TableFormatPebblev3 {
  1762  		writerOpts.ShortAttributeExtractor = o.Experimental.ShortAttributeExtractor
  1763  		writerOpts.RequiredInPlaceValueBound = o.Experimental.RequiredInPlaceValueBound
  1764  		if format >= sstable.TableFormatPebblev4 && level == numLevels-1 {
  1765  			writerOpts.WritingToLowestLevel = true
  1766  		}
  1767  	}
  1768  	levelOpts := o.Level(level)
  1769  	writerOpts.BlockRestartInterval = levelOpts.BlockRestartInterval
  1770  	writerOpts.BlockSize = levelOpts.BlockSize
  1771  	writerOpts.BlockSizeThreshold = levelOpts.BlockSizeThreshold
  1772  	writerOpts.Compression = levelOpts.Compression
  1773  	writerOpts.FilterPolicy = levelOpts.FilterPolicy
  1774  	writerOpts.FilterType = levelOpts.FilterType
  1775  	writerOpts.IndexBlockSize = levelOpts.IndexBlockSize
  1776  	return writerOpts
  1777  }