Line data Source code
1 : // Copyright 2012 The LevelDB-Go and Pebble Authors. All rights reserved. Use
2 : // of this source code is governed by a BSD-style license that can be found in
3 : // the LICENSE file.
4 :
5 : package manifest
6 :
7 : import (
8 : "bytes"
9 : stdcmp "cmp"
10 : "fmt"
11 : "slices"
12 : "sort"
13 : "strings"
14 : "sync"
15 : "sync/atomic"
16 :
17 : "github.com/cockroachdb/errors"
18 : "github.com/cockroachdb/pebble/internal/base"
19 : "github.com/cockroachdb/pebble/internal/invariants"
20 : "github.com/cockroachdb/pebble/sstable"
21 : "github.com/cockroachdb/pebble/sstable/block"
22 : )
23 :
24 : // Compare exports the base.Compare type.
25 : type Compare = base.Compare
26 :
27 : // InternalKey exports the base.InternalKey type.
28 : type InternalKey = base.InternalKey
29 :
30 : // TableInfo contains the common information for table related events.
31 : type TableInfo struct {
32 : // FileNum is the internal DB identifier for the table.
33 : FileNum base.FileNum
34 : // Size is the size of the file in bytes.
35 : Size uint64
36 : // Smallest is the smallest internal key in the table.
37 : Smallest InternalKey
38 : // Largest is the largest internal key in the table.
39 : Largest InternalKey
40 : // SmallestSeqNum is the smallest sequence number in the table.
41 : SmallestSeqNum base.SeqNum
42 : // LargestSeqNum is the largest sequence number in the table.
43 : LargestSeqNum base.SeqNum
44 : }
45 :
46 : // TableStats contains statistics on a table used for compaction heuristics,
47 : // and export via Metrics.
48 : type TableStats struct {
49 : // The total number of entries in the table.
50 : NumEntries uint64
51 : // The number of point and range deletion entries in the table.
52 : NumDeletions uint64
53 : // NumRangeKeySets is the total number of range key sets in the table.
54 : //
55 : // NB: If there's a chance that the sstable contains any range key sets,
56 : // then NumRangeKeySets must be > 0.
57 : NumRangeKeySets uint64
58 : // Estimate of the total disk space that may be dropped by this table's
59 : // point deletions by compacting them.
60 : PointDeletionsBytesEstimate uint64
61 : // Estimate of the total disk space that may be dropped by this table's
62 : // range deletions by compacting them. This estimate is at data-block
63 : // granularity and is not updated if compactions beneath the table reduce
64 : // the amount of reclaimable disk space. It also does not account for
65 : // overlapping data in L0 and ignores L0 sublevels, but the error that
66 : // introduces is expected to be small.
67 : //
68 : // Tables in the bottommost level of the LSM may have a nonzero estimate if
69 : // snapshots or move compactions prevented the elision of their range
70 : // tombstones. A table in the bottommost level that was ingested into L6
71 : // will have a zero estimate, because the file's sequence numbers indicate
72 : // that the tombstone cannot drop any data contained within the file itself.
73 : RangeDeletionsBytesEstimate uint64
74 : // Total size of value blocks and value index block.
75 : ValueBlocksSize uint64
76 : // CompressionType is the compression type of the table.
77 : CompressionType block.Compression
78 : // TombstoneDenseBlocksRatio is the ratio of data blocks in this table that
79 : // fulfills at least one of the following:
80 : // 1. The block contains at least options.Experimental.NumDeletionsThreshold
81 : // point tombstones.
82 : // 2. The ratio of the uncompressed size of point tombstones to the
83 : // uncompressed size of the block is at least
84 : // options.Experimental.DeletionSizeRatioThreshold.
85 : // This statistic is used to determine eligibility for a tombstone density
86 : // compaction.
87 : TombstoneDenseBlocksRatio float64
88 : }
89 :
90 : // boundType represents the type of key (point or range) present as the smallest
91 : // and largest keys.
92 : type boundType uint8
93 :
94 : const (
95 : boundTypePointKey boundType = iota + 1
96 : boundTypeRangeKey
97 : )
98 :
99 : // CompactionState is the compaction state of a file.
100 : //
101 : // The following shows the valid state transitions:
102 : //
103 : // NotCompacting --> Compacting --> Compacted
104 : // ^ |
105 : // | |
106 : // +-------<-------+
107 : //
108 : // Input files to a compaction transition to Compacting when a compaction is
109 : // picked. A file that has finished compacting typically transitions into the
110 : // Compacted state, at which point it is effectively obsolete ("zombied") and
111 : // will eventually be removed from the LSM. A file that has been move-compacted
112 : // will transition from Compacting back into the NotCompacting state, signaling
113 : // that the file may be selected for a subsequent compaction. A failed
114 : // compaction will result in all input tables transitioning from Compacting to
115 : // NotCompacting.
116 : //
117 : // This state is in-memory only. It is not persisted to the manifest.
118 : type CompactionState uint8
119 :
120 : // CompactionStates.
121 : const (
122 : CompactionStateNotCompacting CompactionState = iota
123 : CompactionStateCompacting
124 : CompactionStateCompacted
125 : )
126 :
127 : // String implements fmt.Stringer.
128 0 : func (s CompactionState) String() string {
129 0 : switch s {
130 0 : case CompactionStateNotCompacting:
131 0 : return "NotCompacting"
132 0 : case CompactionStateCompacting:
133 0 : return "Compacting"
134 0 : case CompactionStateCompacted:
135 0 : return "Compacted"
136 0 : default:
137 0 : panic(fmt.Sprintf("pebble: unknown compaction state %d", s))
138 : }
139 : }
140 :
141 : // FileMetadata is maintained for leveled-ssts, i.e., they belong to a level of
142 : // some version. FileMetadata does not contain the actual level of the sst,
143 : // since such leveled-ssts can move across levels in different versions, while
144 : // sharing the same FileMetadata. There are two kinds of leveled-ssts, physical
145 : // and virtual. Underlying both leveled-ssts is a backing-sst, for which the
146 : // only state is FileBacking. A backing-sst is level-less. It is possible for a
147 : // backing-sst to be referred to by a physical sst in one version and by one or
148 : // more virtual ssts in one or more versions. A backing-sst becomes obsolete
149 : // and can be deleted once it is no longer required by any physical or virtual
150 : // sst in any version.
151 : //
152 : // We maintain some invariants:
153 : //
154 : // 1. Each physical and virtual sst will have a unique FileMetadata.FileNum,
155 : // and there will be exactly one FileMetadata associated with the FileNum.
156 : //
157 : // 2. Within a version, a backing-sst is either only referred to by one
158 : // physical sst or one or more virtual ssts.
159 : //
160 : // 3. Once a backing-sst is referred to by a virtual sst in the latest version,
161 : // it cannot go back to being referred to by a physical sst in any future
162 : // version.
163 : //
164 : // Once a physical sst is no longer needed by any version, we will no longer
165 : // maintain the file metadata associated with it. We will still maintain the
166 : // FileBacking associated with the physical sst if the backing sst is required
167 : // by any virtual ssts in any version.
168 : type FileMetadata struct {
169 : // AllowedSeeks is used to determine if a file should be picked for
170 : // a read triggered compaction. It is decremented when read sampling
171 : // in pebble.Iterator after every after every positioning operation
172 : // that returns a user key (eg. Next, Prev, SeekGE, SeekLT, etc).
173 : AllowedSeeks atomic.Int64
174 :
175 : // statsValid indicates if stats have been loaded for the table. The
176 : // TableStats structure is populated only if valid is true.
177 : statsValid atomic.Bool
178 :
179 : // FileBacking is the state which backs either a physical or virtual
180 : // sstables.
181 : FileBacking *FileBacking
182 :
183 : // InitAllowedSeeks is the inital value of allowed seeks. This is used
184 : // to re-set allowed seeks on a file once it hits 0.
185 : InitAllowedSeeks int64
186 : // FileNum is the file number.
187 : //
188 : // INVARIANT: when !FileMetadata.Virtual, FileNum == FileBacking.DiskFileNum.
189 : FileNum base.FileNum
190 : // Size is the size of the file, in bytes. Size is an approximate value for
191 : // virtual sstables.
192 : //
193 : // INVARIANTS:
194 : // - When !FileMetadata.Virtual, Size == FileBacking.Size.
195 : // - Size should be non-zero. Size 0 virtual sstables must not be created.
196 : Size uint64
197 : // File creation time in seconds since the epoch (1970-01-01 00:00:00
198 : // UTC). For ingested sstables, this corresponds to the time the file was
199 : // ingested. For virtual sstables, this corresponds to the wall clock time
200 : // when the FileMetadata for the virtual sstable was first created.
201 : CreationTime int64
202 : // LargestSeqNumAbsolute is an upper bound for the largest sequence number
203 : // in the table. This upper bound is guaranteed to be higher than any
204 : // sequence number any of the table's keys have held at any point in time
205 : // while the database has been open. Specifically, if the table contains
206 : // keys that have had their sequence numbers zeroed during a compaction,
207 : // LargestSeqNumAbsolute will be at least as high as the pre-zeroing
208 : // sequence number. LargestSeqNumAbsolute is NOT durably persisted, so after
209 : // a database restart it takes on the value of LargestSeqNum.
210 : LargestSeqNumAbsolute base.SeqNum
211 : // Lower and upper bounds for the smallest and largest sequence numbers in
212 : // the table, across both point and range keys. For physical sstables, these
213 : // values are tight bounds. For virtual sstables, there is no guarantee that
214 : // there will be keys with SmallestSeqNum or LargestSeqNum within virtual
215 : // sstable bounds.
216 : SmallestSeqNum base.SeqNum
217 : LargestSeqNum base.SeqNum
218 : // SmallestPointKey and LargestPointKey are the inclusive bounds for the
219 : // internal point keys stored in the table. This includes RANGEDELs, which
220 : // alter point keys.
221 : // NB: these field should be set using ExtendPointKeyBounds. They are left
222 : // exported for reads as an optimization.
223 : SmallestPointKey InternalKey
224 : LargestPointKey InternalKey
225 : // SmallestRangeKey and LargestRangeKey are the inclusive bounds for the
226 : // internal range keys stored in the table.
227 : // NB: these field should be set using ExtendRangeKeyBounds. They are left
228 : // exported for reads as an optimization.
229 : SmallestRangeKey InternalKey
230 : LargestRangeKey InternalKey
231 : // Smallest and Largest are the inclusive bounds for the internal keys stored
232 : // in the table, across both point and range keys.
233 : // NB: these fields are derived from their point and range key equivalents,
234 : // and are updated via the MaybeExtend{Point,Range}KeyBounds methods.
235 : Smallest InternalKey
236 : Largest InternalKey
237 : // Stats describe table statistics. Protected by DB.mu.
238 : //
239 : // For virtual sstables, set stats upon virtual sstable creation as
240 : // asynchronous computation of stats is not currently supported.
241 : //
242 : // TODO(bananabrick): To support manifest replay for virtual sstables, we
243 : // probably need to compute virtual sstable stats asynchronously. Otherwise,
244 : // we'd have to write virtual sstable stats to the version edit.
245 : Stats TableStats
246 :
247 : // For L0 files only. Protected by DB.mu. Used to generate L0 sublevels and
248 : // pick L0 compactions. Only accurate for the most recent Version.
249 : SubLevel int
250 : L0Index int
251 : minIntervalIndex int
252 : maxIntervalIndex int
253 :
254 : // NB: the alignment of this struct is 8 bytes. We pack all the bools to
255 : // ensure an optimal packing.
256 :
257 : // IsIntraL0Compacting is set to True if this file is part of an intra-L0
258 : // compaction. When it's true, IsCompacting must also return true. If
259 : // Compacting is true and IsIntraL0Compacting is false for an L0 file, the
260 : // file must be part of a compaction to Lbase.
261 : IsIntraL0Compacting bool
262 : CompactionState CompactionState
263 : // True if compaction of this file has been explicitly requested.
264 : // Previously, RocksDB and earlier versions of Pebble allowed this
265 : // flag to be set by a user table property collector. Some earlier
266 : // versions of Pebble respected this flag, while other more recent
267 : // versions ignored this flag.
268 : //
269 : // More recently this flag has been repurposed to facilitate the
270 : // compaction of 'atomic compaction units'. Files marked for
271 : // compaction are compacted in a rewrite compaction at the lowest
272 : // possible compaction priority.
273 : //
274 : // NB: A count of files marked for compaction is maintained on
275 : // Version, and compaction picking reads cached annotations
276 : // determined by this field.
277 : //
278 : // Protected by DB.mu.
279 : MarkedForCompaction bool
280 : // HasPointKeys tracks whether the table contains point keys (including
281 : // RANGEDELs). If a table contains only range deletions, HasPointsKeys is
282 : // still true.
283 : HasPointKeys bool
284 : // HasRangeKeys tracks whether the table contains any range keys.
285 : HasRangeKeys bool
286 : // smallestSet and largestSet track whether the overall bounds have been set.
287 : boundsSet bool
288 : // boundTypeSmallest and boundTypeLargest provide an indication as to which
289 : // key type (point or range) corresponds to the smallest and largest overall
290 : // table bounds.
291 : boundTypeSmallest, boundTypeLargest boundType
292 : // Virtual is true if the FileMetadata belongs to a virtual sstable.
293 : Virtual bool
294 :
295 : // SyntheticPrefix is used to prepend a prefix to all keys; used for some virtual
296 : // tables.
297 : SyntheticPrefix sstable.SyntheticPrefix
298 :
299 : // SyntheticSuffix overrides all suffixes in a table; used for some virtual tables.
300 : SyntheticSuffix sstable.SyntheticSuffix
301 : }
302 :
303 : // InternalKeyBounds returns the set of overall table bounds.
304 0 : func (m *FileMetadata) InternalKeyBounds() (InternalKey, InternalKey) {
305 0 : return m.Smallest, m.Largest
306 0 : }
307 :
308 : // UserKeyBounds returns the user key bounds that correspond to m.Smallest and
309 : // Largest. Because we do not allow split user keys, the user key bounds of
310 : // files within a level do not overlap.
311 1 : func (m *FileMetadata) UserKeyBounds() base.UserKeyBounds {
312 1 : return base.UserKeyBoundsFromInternal(m.Smallest, m.Largest)
313 1 : }
314 :
315 : // UserKeyBoundsByType returns the user key bounds for the given key types.
316 : // Note that the returned bounds are invalid when requesting KeyTypePoint but
317 : // HasPointKeys is false, or when requesting KeyTypeRange and HasRangeKeys is
318 : // false.
319 1 : func (m *FileMetadata) UserKeyBoundsByType(keyType KeyType) base.UserKeyBounds {
320 1 : switch keyType {
321 1 : case KeyTypePoint:
322 1 : return base.UserKeyBoundsFromInternal(m.SmallestPointKey, m.LargestPointKey)
323 1 : case KeyTypeRange:
324 1 : return base.UserKeyBoundsFromInternal(m.SmallestRangeKey, m.LargestRangeKey)
325 0 : default:
326 0 : return base.UserKeyBoundsFromInternal(m.Smallest, m.Largest)
327 : }
328 : }
329 :
330 : // SyntheticSeqNum returns a SyntheticSeqNum which is set when SmallestSeqNum
331 : // equals LargestSeqNum.
332 1 : func (m *FileMetadata) SyntheticSeqNum() sstable.SyntheticSeqNum {
333 1 : if m.SmallestSeqNum == m.LargestSeqNum {
334 1 : return sstable.SyntheticSeqNum(m.SmallestSeqNum)
335 1 : }
336 1 : return sstable.NoSyntheticSeqNum
337 : }
338 :
339 : // IterTransforms returns an sstable.IterTransforms populated according to the
340 : // file.
341 1 : func (m *FileMetadata) IterTransforms() sstable.IterTransforms {
342 1 : return sstable.IterTransforms{
343 1 : SyntheticSeqNum: m.SyntheticSeqNum(),
344 1 : SyntheticSuffix: m.SyntheticSuffix,
345 1 : SyntheticPrefix: m.SyntheticPrefix,
346 1 : }
347 1 : }
348 :
349 : // FragmentIterTransforms returns an sstable.FragmentIterTransforms populated
350 : // according to the file.
351 1 : func (m *FileMetadata) FragmentIterTransforms() sstable.FragmentIterTransforms {
352 1 : return sstable.FragmentIterTransforms{
353 1 : SyntheticSeqNum: m.SyntheticSeqNum(),
354 1 : SyntheticSuffix: m.SyntheticSuffix,
355 1 : SyntheticPrefix: m.SyntheticPrefix,
356 1 : }
357 1 : }
358 :
359 : // PhysicalFileMeta is used by functions which want a guarantee that their input
360 : // belongs to a physical sst and not a virtual sst.
361 : //
362 : // NB: This type should only be constructed by calling
363 : // FileMetadata.PhysicalMeta.
364 : type PhysicalFileMeta struct {
365 : *FileMetadata
366 : }
367 :
368 : // VirtualFileMeta is used by functions which want a guarantee that their input
369 : // belongs to a virtual sst and not a physical sst.
370 : //
371 : // A VirtualFileMeta inherits all the same fields as a FileMetadata. These
372 : // fields have additional invariants imposed on them, and/or slightly varying
373 : // meanings:
374 : // - Smallest and Largest (and their counterparts
375 : // {Smallest, Largest}{Point,Range}Key) remain tight bounds that represent a
376 : // key at that exact bound. We make the effort to determine the next smallest
377 : // or largest key in an sstable after virtualizing it, to maintain this
378 : // tightness. If the largest is a sentinel key (IsExclusiveSentinel()), it
379 : // could mean that a rangedel or range key ends at that user key, or has been
380 : // truncated to that user key.
381 : // - One invariant is that if a rangedel or range key is truncated on its
382 : // upper bound, the virtual sstable *must* have a rangedel or range key
383 : // sentinel key as its upper bound. This is because truncation yields
384 : // an exclusive upper bound for the rangedel/rangekey, and if there are
385 : // any points at that exclusive upper bound within the same virtual
386 : // sstable, those could get uncovered by this truncation. We enforce this
387 : // invariant in calls to keyspan.Truncate.
388 : // - Size is an estimate of the size of the virtualized portion of this sstable.
389 : // The underlying file's size is stored in FileBacking.Size, though it could
390 : // also be estimated or could correspond to just the referenced portion of
391 : // a file (eg. if the file originated on another node).
392 : // - Size must be > 0.
393 : // - SmallestSeqNum and LargestSeqNum are loose bounds for virtual sstables.
394 : // This means that all keys in the virtual sstable must have seqnums within
395 : // [SmallestSeqNum, LargestSeqNum], however there's no guarantee that there's
396 : // a key with a seqnum at either of the bounds. Calculating tight seqnum
397 : // bounds would be too expensive and deliver little value.
398 : //
399 : // NB: This type should only be constructed by calling FileMetadata.VirtualMeta.
400 : type VirtualFileMeta struct {
401 : *FileMetadata
402 : }
403 :
404 : // VirtualReaderParams fills in the parameters necessary to create a virtual
405 : // sstable reader.
406 1 : func (m VirtualFileMeta) VirtualReaderParams(isShared bool) sstable.VirtualReaderParams {
407 1 : return sstable.VirtualReaderParams{
408 1 : Lower: m.Smallest,
409 1 : Upper: m.Largest,
410 1 : FileNum: m.FileNum,
411 1 : IsSharedIngested: isShared && m.SyntheticSeqNum() != 0,
412 1 : Size: m.Size,
413 1 : BackingSize: m.FileBacking.Size,
414 1 : }
415 1 : }
416 :
417 : // PhysicalMeta should be the only source of creating the PhysicalFileMeta
418 : // wrapper type.
419 1 : func (m *FileMetadata) PhysicalMeta() PhysicalFileMeta {
420 1 : if m.Virtual {
421 0 : panic("pebble: file metadata does not belong to a physical sstable")
422 : }
423 1 : return PhysicalFileMeta{
424 1 : m,
425 1 : }
426 : }
427 :
428 : // VirtualMeta should be the only source of creating the VirtualFileMeta wrapper
429 : // type.
430 1 : func (m *FileMetadata) VirtualMeta() VirtualFileMeta {
431 1 : if !m.Virtual {
432 0 : panic("pebble: file metadata does not belong to a virtual sstable")
433 : }
434 1 : return VirtualFileMeta{
435 1 : m,
436 1 : }
437 : }
438 :
439 : // FileBacking either backs a single physical sstable, or one or more virtual
440 : // sstables.
441 : //
442 : // See the comment above the FileMetadata type for sstable terminology.
443 : type FileBacking struct {
444 : DiskFileNum base.DiskFileNum
445 : Size uint64
446 :
447 : // Reference count for the backing file, used to determine when a backing file
448 : // is obsolete and can be removed.
449 : //
450 : // The reference count is at least the number of distinct tables that use this
451 : // backing across all versions that have a non-zero reference count. The tables
452 : // in each version are maintained in a copy-on-write B-tree and each B-tree node
453 : // keeps a reference on the respective backings.
454 : //
455 : // In addition, a reference count is taken for every backing in the latest
456 : // version's VirtualBackings (necessary to support Protect/Unprotect).
457 : refs atomic.Int32
458 : }
459 :
460 : // MustHaveRefs asserts that the backing has a positive refcount.
461 1 : func (b *FileBacking) MustHaveRefs() {
462 1 : if refs := b.refs.Load(); refs <= 0 {
463 0 : panic(errors.AssertionFailedf("backing %s must have positive refcount (refs=%d)",
464 0 : b.DiskFileNum, refs))
465 : }
466 : }
467 :
468 : // Ref increments the backing's ref count.
469 1 : func (b *FileBacking) Ref() {
470 1 : b.refs.Add(1)
471 1 : }
472 :
473 : // Unref decrements the backing's ref count (and returns the new count).
474 1 : func (b *FileBacking) Unref() int32 {
475 1 : v := b.refs.Add(-1)
476 1 : if invariants.Enabled && v < 0 {
477 0 : panic("pebble: invalid FileMetadata refcounting")
478 : }
479 1 : return v
480 : }
481 :
482 : // InitPhysicalBacking allocates and sets the FileBacking which is required by a
483 : // physical sstable FileMetadata.
484 : //
485 : // Ensure that the state required by FileBacking, such as the FileNum, is
486 : // already set on the FileMetadata before InitPhysicalBacking is called.
487 : // Calling InitPhysicalBacking only after the relevant state has been set in the
488 : // FileMetadata is not necessary in tests which don't rely on FileBacking.
489 1 : func (m *FileMetadata) InitPhysicalBacking() {
490 1 : if m.Virtual {
491 0 : panic("pebble: virtual sstables should use a pre-existing FileBacking")
492 : }
493 1 : if m.FileBacking == nil {
494 1 : m.FileBacking = &FileBacking{
495 1 : DiskFileNum: base.PhysicalTableDiskFileNum(m.FileNum),
496 1 : Size: m.Size,
497 1 : }
498 1 : }
499 : }
500 :
501 : // InitProviderBacking creates a new FileBacking for a file backed by
502 : // an objstorage.Provider.
503 1 : func (m *FileMetadata) InitProviderBacking(fileNum base.DiskFileNum, size uint64) {
504 1 : if !m.Virtual {
505 0 : panic("pebble: provider-backed sstables must be virtual")
506 : }
507 1 : if m.FileBacking == nil {
508 1 : m.FileBacking = &FileBacking{DiskFileNum: fileNum}
509 1 : }
510 1 : m.FileBacking.Size = size
511 : }
512 :
513 : // ValidateVirtual should be called once the FileMetadata for a virtual sstable
514 : // is created to verify that the fields of the virtual sstable are sound.
515 1 : func (m *FileMetadata) ValidateVirtual(createdFrom *FileMetadata) {
516 1 : switch {
517 0 : case !m.Virtual:
518 0 : panic("pebble: invalid virtual sstable")
519 0 : case createdFrom.SmallestSeqNum != m.SmallestSeqNum:
520 0 : panic("pebble: invalid smallest sequence number for virtual sstable")
521 0 : case createdFrom.LargestSeqNum != m.LargestSeqNum:
522 0 : panic("pebble: invalid largest sequence number for virtual sstable")
523 0 : case createdFrom.LargestSeqNumAbsolute != m.LargestSeqNumAbsolute:
524 0 : panic("pebble: invalid largest absolute sequence number for virtual sstable")
525 0 : case createdFrom.FileBacking != nil && createdFrom.FileBacking != m.FileBacking:
526 0 : panic("pebble: invalid physical sstable state for virtual sstable")
527 0 : case m.Size == 0:
528 0 : panic("pebble: virtual sstable size must be set upon creation")
529 : }
530 : }
531 :
532 : // SetCompactionState transitions this file's compaction state to the given
533 : // state. Protected by DB.mu.
534 1 : func (m *FileMetadata) SetCompactionState(to CompactionState) {
535 1 : if invariants.Enabled {
536 1 : transitionErr := func() error {
537 0 : return errors.Newf("pebble: invalid compaction state transition: %s -> %s", m.CompactionState, to)
538 0 : }
539 1 : switch m.CompactionState {
540 1 : case CompactionStateNotCompacting:
541 1 : if to != CompactionStateCompacting {
542 0 : panic(transitionErr())
543 : }
544 1 : case CompactionStateCompacting:
545 1 : if to != CompactionStateCompacted && to != CompactionStateNotCompacting {
546 0 : panic(transitionErr())
547 : }
548 0 : case CompactionStateCompacted:
549 0 : panic(transitionErr())
550 0 : default:
551 0 : panic(fmt.Sprintf("pebble: unknown compaction state: %d", m.CompactionState))
552 : }
553 : }
554 1 : m.CompactionState = to
555 : }
556 :
557 : // IsCompacting returns true if this file's compaction state is
558 : // CompactionStateCompacting. Protected by DB.mu.
559 1 : func (m *FileMetadata) IsCompacting() bool {
560 1 : return m.CompactionState == CompactionStateCompacting
561 1 : }
562 :
563 : // StatsValid returns true if the table stats have been populated. If StatValid
564 : // returns true, the Stats field may be read (with or without holding the
565 : // database mutex).
566 1 : func (m *FileMetadata) StatsValid() bool {
567 1 : return m.statsValid.Load()
568 1 : }
569 :
570 : // StatsMarkValid marks the TableStats as valid. The caller must hold DB.mu
571 : // while populating TableStats and calling StatsMarkValud. Once stats are
572 : // populated, they must not be mutated.
573 1 : func (m *FileMetadata) StatsMarkValid() {
574 1 : m.statsValid.Store(true)
575 1 : }
576 :
577 : // ExtendPointKeyBounds attempts to extend the lower and upper point key bounds
578 : // and overall table bounds with the given smallest and largest keys. The
579 : // smallest and largest bounds may not be extended if the table already has a
580 : // bound that is smaller or larger, respectively. The receiver is returned.
581 : // NB: calling this method should be preferred to manually setting the bounds by
582 : // manipulating the fields directly, to maintain certain invariants.
583 : func (m *FileMetadata) ExtendPointKeyBounds(
584 : cmp Compare, smallest, largest InternalKey,
585 1 : ) *FileMetadata {
586 1 : // Update the point key bounds.
587 1 : if !m.HasPointKeys {
588 1 : m.SmallestPointKey, m.LargestPointKey = smallest, largest
589 1 : m.HasPointKeys = true
590 1 : } else {
591 1 : if base.InternalCompare(cmp, smallest, m.SmallestPointKey) < 0 {
592 1 : m.SmallestPointKey = smallest
593 1 : }
594 1 : if base.InternalCompare(cmp, largest, m.LargestPointKey) > 0 {
595 1 : m.LargestPointKey = largest
596 1 : }
597 : }
598 : // Update the overall bounds.
599 1 : m.extendOverallBounds(cmp, m.SmallestPointKey, m.LargestPointKey, boundTypePointKey)
600 1 : return m
601 : }
602 :
603 : // ExtendRangeKeyBounds attempts to extend the lower and upper range key bounds
604 : // and overall table bounds with the given smallest and largest keys. The
605 : // smallest and largest bounds may not be extended if the table already has a
606 : // bound that is smaller or larger, respectively. The receiver is returned.
607 : // NB: calling this method should be preferred to manually setting the bounds by
608 : // manipulating the fields directly, to maintain certain invariants.
609 : func (m *FileMetadata) ExtendRangeKeyBounds(
610 : cmp Compare, smallest, largest InternalKey,
611 1 : ) *FileMetadata {
612 1 : // Update the range key bounds.
613 1 : if !m.HasRangeKeys {
614 1 : m.SmallestRangeKey, m.LargestRangeKey = smallest, largest
615 1 : m.HasRangeKeys = true
616 1 : } else {
617 1 : if base.InternalCompare(cmp, smallest, m.SmallestRangeKey) < 0 {
618 1 : m.SmallestRangeKey = smallest
619 1 : }
620 1 : if base.InternalCompare(cmp, largest, m.LargestRangeKey) > 0 {
621 1 : m.LargestRangeKey = largest
622 1 : }
623 : }
624 : // Update the overall bounds.
625 1 : m.extendOverallBounds(cmp, m.SmallestRangeKey, m.LargestRangeKey, boundTypeRangeKey)
626 1 : return m
627 : }
628 :
629 : // extendOverallBounds attempts to extend the overall table lower and upper
630 : // bounds. The given bounds may not be used if a lower or upper bound already
631 : // exists that is smaller or larger than the given keys, respectively. The given
632 : // boundType will be used if the bounds are updated.
633 : func (m *FileMetadata) extendOverallBounds(
634 : cmp Compare, smallest, largest InternalKey, bTyp boundType,
635 1 : ) {
636 1 : if !m.boundsSet {
637 1 : m.Smallest, m.Largest = smallest, largest
638 1 : m.boundsSet = true
639 1 : m.boundTypeSmallest, m.boundTypeLargest = bTyp, bTyp
640 1 : } else {
641 1 : if base.InternalCompare(cmp, smallest, m.Smallest) < 0 {
642 1 : m.Smallest = smallest
643 1 : m.boundTypeSmallest = bTyp
644 1 : }
645 1 : if base.InternalCompare(cmp, largest, m.Largest) > 0 {
646 1 : m.Largest = largest
647 1 : m.boundTypeLargest = bTyp
648 1 : }
649 : }
650 : }
651 :
652 : // Overlaps returns true if the file key range overlaps with the given user key bounds.
653 1 : func (m *FileMetadata) Overlaps(cmp Compare, bounds *base.UserKeyBounds) bool {
654 1 : b := m.UserKeyBounds()
655 1 : return b.Overlaps(cmp, bounds)
656 1 : }
657 :
658 : // ContainedWithinSpan returns true if the file key range completely overlaps with the
659 : // given range ("end" is assumed to exclusive).
660 1 : func (m *FileMetadata) ContainedWithinSpan(cmp Compare, start, end []byte) bool {
661 1 : lowerCmp, upperCmp := cmp(m.Smallest.UserKey, start), cmp(m.Largest.UserKey, end)
662 1 : return lowerCmp >= 0 && (upperCmp < 0 || (upperCmp == 0 && m.Largest.IsExclusiveSentinel()))
663 1 : }
664 :
665 : // ContainsKeyType returns whether or not the file contains keys of the provided
666 : // type.
667 1 : func (m *FileMetadata) ContainsKeyType(kt KeyType) bool {
668 1 : switch kt {
669 1 : case KeyTypePointAndRange:
670 1 : return true
671 1 : case KeyTypePoint:
672 1 : return m.HasPointKeys
673 1 : case KeyTypeRange:
674 1 : return m.HasRangeKeys
675 0 : default:
676 0 : panic("unrecognized key type")
677 : }
678 : }
679 :
680 : // SmallestBound returns the file's smallest bound of the key type. It returns a
681 : // false second return value if the file does not contain any keys of the key
682 : // type.
683 1 : func (m *FileMetadata) SmallestBound(kt KeyType) (*InternalKey, bool) {
684 1 : switch kt {
685 0 : case KeyTypePointAndRange:
686 0 : return &m.Smallest, true
687 1 : case KeyTypePoint:
688 1 : return &m.SmallestPointKey, m.HasPointKeys
689 1 : case KeyTypeRange:
690 1 : return &m.SmallestRangeKey, m.HasRangeKeys
691 0 : default:
692 0 : panic("unrecognized key type")
693 : }
694 : }
695 :
696 : // LargestBound returns the file's largest bound of the key type. It returns a
697 : // false second return value if the file does not contain any keys of the key
698 : // type.
699 1 : func (m *FileMetadata) LargestBound(kt KeyType) (*InternalKey, bool) {
700 1 : switch kt {
701 0 : case KeyTypePointAndRange:
702 0 : return &m.Largest, true
703 1 : case KeyTypePoint:
704 1 : return &m.LargestPointKey, m.HasPointKeys
705 1 : case KeyTypeRange:
706 1 : return &m.LargestRangeKey, m.HasRangeKeys
707 0 : default:
708 0 : panic("unrecognized key type")
709 : }
710 : }
711 :
712 : const (
713 : maskContainsPointKeys = 1 << 0
714 : maskSmallest = 1 << 1
715 : maskLargest = 1 << 2
716 : )
717 :
718 : // boundsMarker returns a marker byte whose bits encode the following
719 : // information (in order from least significant bit):
720 : // - if the table contains point keys
721 : // - if the table's smallest key is a point key
722 : // - if the table's largest key is a point key
723 1 : func (m *FileMetadata) boundsMarker() (sentinel uint8, err error) {
724 1 : if m.HasPointKeys {
725 1 : sentinel |= maskContainsPointKeys
726 1 : }
727 1 : switch m.boundTypeSmallest {
728 1 : case boundTypePointKey:
729 1 : sentinel |= maskSmallest
730 1 : case boundTypeRangeKey:
731 : // No op - leave bit unset.
732 0 : default:
733 0 : return 0, base.CorruptionErrorf("file %s has neither point nor range key as smallest key", m.FileNum)
734 : }
735 1 : switch m.boundTypeLargest {
736 1 : case boundTypePointKey:
737 1 : sentinel |= maskLargest
738 1 : case boundTypeRangeKey:
739 : // No op - leave bit unset.
740 0 : default:
741 0 : return 0, base.CorruptionErrorf("file %s has neither point nor range key as largest key", m.FileNum)
742 : }
743 1 : return
744 : }
745 :
746 : // String implements fmt.Stringer, printing the file number and the overall
747 : // table bounds.
748 1 : func (m *FileMetadata) String() string {
749 1 : return fmt.Sprintf("%s:[%s-%s]", m.FileNum, m.Smallest, m.Largest)
750 1 : }
751 :
752 : // DebugString returns a verbose representation of FileMetadata, typically for
753 : // use in tests and debugging, returning the file number and the point, range
754 : // and overall bounds for the table.
755 1 : func (m *FileMetadata) DebugString(format base.FormatKey, verbose bool) string {
756 1 : var b bytes.Buffer
757 1 : if m.Virtual {
758 1 : fmt.Fprintf(&b, "%s(%s):[%s-%s]",
759 1 : m.FileNum, m.FileBacking.DiskFileNum, m.Smallest.Pretty(format), m.Largest.Pretty(format))
760 1 : } else {
761 1 : fmt.Fprintf(&b, "%s:[%s-%s]",
762 1 : m.FileNum, m.Smallest.Pretty(format), m.Largest.Pretty(format))
763 1 : }
764 1 : if !verbose {
765 1 : return b.String()
766 1 : }
767 1 : fmt.Fprintf(&b, " seqnums:[%d-%d]", m.SmallestSeqNum, m.LargestSeqNum)
768 1 : if m.HasPointKeys {
769 1 : fmt.Fprintf(&b, " points:[%s-%s]",
770 1 : m.SmallestPointKey.Pretty(format), m.LargestPointKey.Pretty(format))
771 1 : }
772 1 : if m.HasRangeKeys {
773 1 : fmt.Fprintf(&b, " ranges:[%s-%s]",
774 1 : m.SmallestRangeKey.Pretty(format), m.LargestRangeKey.Pretty(format))
775 1 : }
776 1 : if m.Size != 0 {
777 1 : fmt.Fprintf(&b, " size:%d", m.Size)
778 1 : }
779 1 : return b.String()
780 : }
781 :
782 : // ParseFileMetadataDebug parses a FileMetadata from its DebugString
783 : // representation.
784 1 : func ParseFileMetadataDebug(s string) (_ *FileMetadata, err error) {
785 1 : defer func() {
786 1 : err = errors.CombineErrors(err, maybeRecover())
787 1 : }()
788 :
789 : // Input format:
790 : // 000000:[a#0,SET-z#0,SET] seqnums:[5-5] points:[...] ranges:[...] size:5
791 1 : m := &FileMetadata{}
792 1 : p := makeDebugParser(s)
793 1 : m.FileNum = p.FileNum()
794 1 : var backingNum base.DiskFileNum
795 1 : if p.Peek() == "(" {
796 1 : p.Expect("(")
797 1 : backingNum = p.DiskFileNum()
798 1 : p.Expect(")")
799 1 : }
800 1 : p.Expect(":", "[")
801 1 : m.Smallest = p.InternalKey()
802 1 : p.Expect("-")
803 1 : m.Largest = p.InternalKey()
804 1 : p.Expect("]")
805 1 :
806 1 : for !p.Done() {
807 1 : field := p.Next()
808 1 : p.Expect(":")
809 1 : switch field {
810 1 : case "seqnums":
811 1 : p.Expect("[")
812 1 : m.SmallestSeqNum = p.SeqNum()
813 1 : p.Expect("-")
814 1 : m.LargestSeqNum = p.SeqNum()
815 1 : p.Expect("]")
816 1 : m.LargestSeqNumAbsolute = m.LargestSeqNum
817 :
818 1 : case "points":
819 1 : p.Expect("[")
820 1 : m.SmallestPointKey = p.InternalKey()
821 1 : p.Expect("-")
822 1 : m.LargestPointKey = p.InternalKey()
823 1 : m.HasPointKeys = true
824 1 : p.Expect("]")
825 :
826 1 : case "ranges":
827 1 : p.Expect("[")
828 1 : m.SmallestRangeKey = p.InternalKey()
829 1 : p.Expect("-")
830 1 : m.LargestRangeKey = p.InternalKey()
831 1 : m.HasRangeKeys = true
832 1 : p.Expect("]")
833 :
834 1 : case "size":
835 1 : m.Size = p.Uint64()
836 :
837 0 : default:
838 0 : p.Errf("unknown field %q", field)
839 : }
840 : }
841 :
842 : // By default, when the parser sees just the overall bounds, we set the point
843 : // keys. This preserves backwards compatability with existing test cases that
844 : // specify only the overall bounds.
845 1 : if !m.HasPointKeys && !m.HasRangeKeys {
846 1 : m.SmallestPointKey, m.LargestPointKey = m.Smallest, m.Largest
847 1 : m.HasPointKeys = true
848 1 : }
849 1 : if backingNum == 0 {
850 1 : m.InitPhysicalBacking()
851 1 : } else {
852 1 : m.Virtual = true
853 1 : m.InitProviderBacking(backingNum, 0 /* size */)
854 1 : }
855 1 : return m, nil
856 : }
857 :
858 : // Validate validates the metadata for consistency with itself, returning an
859 : // error if inconsistent.
860 1 : func (m *FileMetadata) Validate(cmp Compare, formatKey base.FormatKey) error {
861 1 : // Combined range and point key validation.
862 1 :
863 1 : if !m.HasPointKeys && !m.HasRangeKeys {
864 0 : return base.CorruptionErrorf("file %s has neither point nor range keys",
865 0 : errors.Safe(m.FileNum))
866 0 : }
867 1 : if base.InternalCompare(cmp, m.Smallest, m.Largest) > 0 {
868 1 : return base.CorruptionErrorf("file %s has inconsistent bounds: %s vs %s",
869 1 : errors.Safe(m.FileNum), m.Smallest.Pretty(formatKey),
870 1 : m.Largest.Pretty(formatKey))
871 1 : }
872 1 : if m.SmallestSeqNum > m.LargestSeqNum {
873 0 : return base.CorruptionErrorf("file %s has inconsistent seqnum bounds: %d vs %d",
874 0 : errors.Safe(m.FileNum), m.SmallestSeqNum, m.LargestSeqNum)
875 0 : }
876 1 : if m.LargestSeqNumAbsolute < m.LargestSeqNum {
877 0 : return base.CorruptionErrorf("file %s has inconsistent absolute largest seqnum bounds: %d vs %d",
878 0 : errors.Safe(m.FileNum), m.LargestSeqNumAbsolute, m.LargestSeqNum)
879 0 : }
880 :
881 : // Point key validation.
882 :
883 1 : if m.HasPointKeys {
884 1 : if base.InternalCompare(cmp, m.SmallestPointKey, m.LargestPointKey) > 0 {
885 0 : return base.CorruptionErrorf("file %s has inconsistent point key bounds: %s vs %s",
886 0 : errors.Safe(m.FileNum), m.SmallestPointKey.Pretty(formatKey),
887 0 : m.LargestPointKey.Pretty(formatKey))
888 0 : }
889 1 : if base.InternalCompare(cmp, m.SmallestPointKey, m.Smallest) < 0 ||
890 1 : base.InternalCompare(cmp, m.LargestPointKey, m.Largest) > 0 {
891 0 : return base.CorruptionErrorf(
892 0 : "file %s has inconsistent point key bounds relative to overall bounds: "+
893 0 : "overall = [%s-%s], point keys = [%s-%s]",
894 0 : errors.Safe(m.FileNum),
895 0 : m.Smallest.Pretty(formatKey), m.Largest.Pretty(formatKey),
896 0 : m.SmallestPointKey.Pretty(formatKey), m.LargestPointKey.Pretty(formatKey),
897 0 : )
898 0 : }
899 1 : if !isValidPointBoundKeyKind[m.SmallestPointKey.Kind()] {
900 0 : return base.CorruptionErrorf("file %s has invalid smallest point key kind", m)
901 0 : }
902 1 : if !isValidPointBoundKeyKind[m.LargestPointKey.Kind()] {
903 0 : return base.CorruptionErrorf("file %s has invalid largest point key kind", m)
904 0 : }
905 : }
906 :
907 : // Range key validation.
908 :
909 1 : if m.HasRangeKeys {
910 1 : if base.InternalCompare(cmp, m.SmallestRangeKey, m.LargestRangeKey) > 0 {
911 0 : return base.CorruptionErrorf("file %s has inconsistent range key bounds: %s vs %s",
912 0 : errors.Safe(m.FileNum), m.SmallestRangeKey.Pretty(formatKey),
913 0 : m.LargestRangeKey.Pretty(formatKey))
914 0 : }
915 1 : if base.InternalCompare(cmp, m.SmallestRangeKey, m.Smallest) < 0 ||
916 1 : base.InternalCompare(cmp, m.LargestRangeKey, m.Largest) > 0 {
917 0 : return base.CorruptionErrorf(
918 0 : "file %s has inconsistent range key bounds relative to overall bounds: "+
919 0 : "overall = [%s-%s], range keys = [%s-%s]",
920 0 : errors.Safe(m.FileNum),
921 0 : m.Smallest.Pretty(formatKey), m.Largest.Pretty(formatKey),
922 0 : m.SmallestRangeKey.Pretty(formatKey), m.LargestRangeKey.Pretty(formatKey),
923 0 : )
924 0 : }
925 1 : if !isValidRangeKeyBoundKeyKind[m.SmallestRangeKey.Kind()] {
926 0 : return base.CorruptionErrorf("file %s has invalid smallest range key kind", m)
927 0 : }
928 1 : if !isValidRangeKeyBoundKeyKind[m.LargestRangeKey.Kind()] {
929 0 : return base.CorruptionErrorf("file %s has invalid largest range key kind", m)
930 0 : }
931 : }
932 :
933 : // Ensure that FileMetadata.Init was called.
934 1 : if m.FileBacking == nil {
935 0 : return base.CorruptionErrorf("file metadata FileBacking not set")
936 0 : }
937 :
938 1 : if m.SyntheticPrefix.IsSet() {
939 1 : if !m.Virtual {
940 0 : return base.CorruptionErrorf("non-virtual file with synthetic prefix")
941 0 : }
942 1 : if !bytes.HasPrefix(m.Smallest.UserKey, m.SyntheticPrefix) {
943 0 : return base.CorruptionErrorf("virtual file with synthetic prefix has smallest key with a different prefix: %s", m.Smallest.Pretty(formatKey))
944 0 : }
945 1 : if !bytes.HasPrefix(m.Largest.UserKey, m.SyntheticPrefix) {
946 0 : return base.CorruptionErrorf("virtual file with synthetic prefix has largest key with a different prefix: %s", m.Largest.Pretty(formatKey))
947 0 : }
948 : }
949 :
950 1 : if m.SyntheticSuffix != nil {
951 1 : if !m.Virtual {
952 0 : return base.CorruptionErrorf("non-virtual file with synthetic suffix")
953 0 : }
954 : }
955 :
956 1 : return nil
957 : }
958 :
959 : var (
960 : isValidPointBoundKeyKind = [base.InternalKeyKindMax + 1]bool{
961 : base.InternalKeyKindDelete: true,
962 : base.InternalKeyKindSet: true,
963 : base.InternalKeyKindMerge: true,
964 : base.InternalKeyKindSingleDelete: true,
965 : base.InternalKeyKindRangeDelete: true,
966 : base.InternalKeyKindSetWithDelete: true,
967 : base.InternalKeyKindDeleteSized: true,
968 : }
969 : isValidRangeKeyBoundKeyKind = [base.InternalKeyKindMax + 1]bool{
970 : base.InternalKeyKindRangeKeySet: true,
971 : base.InternalKeyKindRangeKeyUnset: true,
972 : base.InternalKeyKindRangeKeyDelete: true,
973 : }
974 : )
975 :
976 : // TableInfo returns a subset of the FileMetadata state formatted as a
977 : // TableInfo.
978 1 : func (m *FileMetadata) TableInfo() TableInfo {
979 1 : return TableInfo{
980 1 : FileNum: m.FileNum,
981 1 : Size: m.Size,
982 1 : Smallest: m.Smallest,
983 1 : Largest: m.Largest,
984 1 : SmallestSeqNum: m.SmallestSeqNum,
985 1 : LargestSeqNum: m.LargestSeqNum,
986 1 : }
987 1 : }
988 :
989 1 : func (m *FileMetadata) cmpSeqNum(b *FileMetadata) int {
990 1 : // NB: This is the same ordering that RocksDB uses for L0 files.
991 1 :
992 1 : // Sort first by largest sequence number.
993 1 : if v := stdcmp.Compare(m.LargestSeqNum, b.LargestSeqNum); v != 0 {
994 1 : return v
995 1 : }
996 : // Then by smallest sequence number.
997 1 : if v := stdcmp.Compare(m.SmallestSeqNum, b.SmallestSeqNum); v != 0 {
998 1 : return v
999 1 : }
1000 : // Break ties by file number.
1001 1 : return stdcmp.Compare(m.FileNum, b.FileNum)
1002 : }
1003 :
1004 1 : func (m *FileMetadata) lessSeqNum(b *FileMetadata) bool {
1005 1 : return m.cmpSeqNum(b) < 0
1006 1 : }
1007 :
1008 1 : func (m *FileMetadata) cmpSmallestKey(b *FileMetadata, cmp Compare) int {
1009 1 : return base.InternalCompare(cmp, m.Smallest, b.Smallest)
1010 1 : }
1011 :
1012 : // KeyRange returns the minimum smallest and maximum largest internalKey for
1013 : // all the FileMetadata in iters.
1014 1 : func KeyRange(ucmp Compare, iters ...LevelIterator) (smallest, largest InternalKey) {
1015 1 : first := true
1016 1 : for _, iter := range iters {
1017 1 : for meta := iter.First(); meta != nil; meta = iter.Next() {
1018 1 : if first {
1019 1 : first = false
1020 1 : smallest, largest = meta.Smallest, meta.Largest
1021 1 : continue
1022 : }
1023 1 : if base.InternalCompare(ucmp, smallest, meta.Smallest) >= 0 {
1024 1 : smallest = meta.Smallest
1025 1 : }
1026 1 : if base.InternalCompare(ucmp, largest, meta.Largest) <= 0 {
1027 1 : largest = meta.Largest
1028 1 : }
1029 : }
1030 : }
1031 1 : return smallest, largest
1032 : }
1033 :
1034 : type bySeqNum []*FileMetadata
1035 :
1036 1 : func (b bySeqNum) Len() int { return len(b) }
1037 1 : func (b bySeqNum) Less(i, j int) bool {
1038 1 : return b[i].lessSeqNum(b[j])
1039 1 : }
1040 1 : func (b bySeqNum) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
1041 :
1042 : // SortBySeqNum sorts the specified files by increasing sequence number.
1043 1 : func SortBySeqNum(files []*FileMetadata) {
1044 1 : sort.Sort(bySeqNum(files))
1045 1 : }
1046 :
1047 : type bySmallest struct {
1048 : files []*FileMetadata
1049 : cmp Compare
1050 : }
1051 :
1052 1 : func (b bySmallest) Len() int { return len(b.files) }
1053 1 : func (b bySmallest) Less(i, j int) bool {
1054 1 : return b.files[i].cmpSmallestKey(b.files[j], b.cmp) < 0
1055 1 : }
1056 0 : func (b bySmallest) Swap(i, j int) { b.files[i], b.files[j] = b.files[j], b.files[i] }
1057 :
1058 : // SortBySmallest sorts the specified files by smallest key using the supplied
1059 : // comparison function to order user keys.
1060 1 : func SortBySmallest(files []*FileMetadata, cmp Compare) {
1061 1 : sort.Sort(bySmallest{files, cmp})
1062 1 : }
1063 :
1064 : // NumLevels is the number of levels a Version contains.
1065 : const NumLevels = 7
1066 :
1067 : // NewVersion constructs a new Version with the provided files. It requires
1068 : // the provided files are already well-ordered. It's intended for testing.
1069 : func NewVersion(
1070 : comparer *base.Comparer, flushSplitBytes int64, files [NumLevels][]*FileMetadata,
1071 1 : ) *Version {
1072 1 : v := &Version{
1073 1 : cmp: comparer,
1074 1 : }
1075 1 : for l := range files {
1076 1 : // NB: We specifically insert `files` into the B-Tree in the order
1077 1 : // they appear within `files`. Some tests depend on this behavior in
1078 1 : // order to test consistency checking, etc. Once we've constructed the
1079 1 : // initial B-Tree, we swap out the btreeCmp for the correct one.
1080 1 : // TODO(jackson): Adjust or remove the tests and remove this.
1081 1 : v.Levels[l].tree, _ = makeBTree(comparer.Compare, btreeCmpSpecificOrder(files[l]), files[l])
1082 1 : v.Levels[l].level = l
1083 1 : if l == 0 {
1084 1 : v.Levels[l].tree.bcmp = btreeCmpSeqNum
1085 1 : } else {
1086 1 : v.Levels[l].tree.bcmp = btreeCmpSmallestKey(comparer.Compare)
1087 1 : }
1088 1 : for _, f := range files[l] {
1089 1 : v.Levels[l].totalSize += f.Size
1090 1 : }
1091 : }
1092 1 : if err := v.InitL0Sublevels(flushSplitBytes); err != nil {
1093 0 : panic(err)
1094 : }
1095 1 : return v
1096 : }
1097 :
1098 : // TestingNewVersion returns a blank Version, used for tests.
1099 1 : func TestingNewVersion(comparer *base.Comparer) *Version {
1100 1 : return &Version{
1101 1 : cmp: comparer,
1102 1 : }
1103 1 : }
1104 :
1105 : // Version is a collection of file metadata for on-disk tables at various
1106 : // levels. In-memory DBs are written to level-0 tables, and compactions
1107 : // migrate data from level N to level N+1. The tables map internal keys (which
1108 : // are a user key, a delete or set bit, and a sequence number) to user values.
1109 : //
1110 : // The tables at level 0 are sorted by largest sequence number. Due to file
1111 : // ingestion, there may be overlap in the ranges of sequence numbers contain in
1112 : // level 0 sstables. In particular, it is valid for one level 0 sstable to have
1113 : // the seqnum range [1,100] while an adjacent sstable has the seqnum range
1114 : // [50,50]. This occurs when the [50,50] table was ingested and given a global
1115 : // seqnum. The ingestion code will have ensured that the [50,50] sstable will
1116 : // not have any keys that overlap with the [1,100] in the seqnum range
1117 : // [1,49]. The range of internal keys [fileMetadata.smallest,
1118 : // fileMetadata.largest] in each level 0 table may overlap.
1119 : //
1120 : // The tables at any non-0 level are sorted by their internal key range and any
1121 : // two tables at the same non-0 level do not overlap.
1122 : //
1123 : // The internal key ranges of two tables at different levels X and Y may
1124 : // overlap, for any X != Y.
1125 : //
1126 : // Finally, for every internal key in a table at level X, there is no internal
1127 : // key in a higher level table that has both the same user key and a higher
1128 : // sequence number.
1129 : type Version struct {
1130 : refs atomic.Int32
1131 :
1132 : // The level 0 sstables are organized in a series of sublevels. Similar to
1133 : // the seqnum invariant in normal levels, there is no internal key in a
1134 : // higher level table that has both the same user key and a higher sequence
1135 : // number. Within a sublevel, tables are sorted by their internal key range
1136 : // and any two tables at the same sublevel do not overlap. Unlike the normal
1137 : // levels, sublevel n contains older tables (lower sequence numbers) than
1138 : // sublevel n+1.
1139 : //
1140 : // The L0Sublevels struct is mostly used for compaction picking. As most
1141 : // internal data structures in it are only necessary for compaction picking
1142 : // and not for iterator creation, the reference to L0Sublevels is nil'd
1143 : // after this version becomes the non-newest version, to reduce memory
1144 : // usage.
1145 : //
1146 : // L0Sublevels.Levels contains L0 files ordered by sublevels. All the files
1147 : // in Levels[0] are in L0Sublevels.Levels. L0SublevelFiles is also set to
1148 : // a reference to that slice, as that slice is necessary for iterator
1149 : // creation and needs to outlast L0Sublevels.
1150 : L0Sublevels *L0Sublevels
1151 : L0SublevelFiles []LevelSlice
1152 :
1153 : Levels [NumLevels]LevelMetadata
1154 :
1155 : // RangeKeyLevels holds a subset of the same files as Levels that contain range
1156 : // keys (i.e. fileMeta.HasRangeKeys == true). The memory amplification of this
1157 : // duplication should be minimal, as range keys are expected to be rare.
1158 : RangeKeyLevels [NumLevels]LevelMetadata
1159 :
1160 : // The callback to invoke when the last reference to a version is
1161 : // removed. Will be called with list.mu held.
1162 : Deleted func(obsolete []*FileBacking)
1163 :
1164 : // Stats holds aggregated stats about the version maintained from
1165 : // version to version.
1166 : Stats struct {
1167 : // MarkedForCompaction records the count of files marked for
1168 : // compaction within the version.
1169 : MarkedForCompaction int
1170 : }
1171 :
1172 : cmp *base.Comparer
1173 :
1174 : // The list the version is linked into.
1175 : list *VersionList
1176 :
1177 : // The next/prev link for the versionList doubly-linked list of versions.
1178 : prev, next *Version
1179 : }
1180 :
1181 : // String implements fmt.Stringer, printing the FileMetadata for each level in
1182 : // the Version.
1183 1 : func (v *Version) String() string {
1184 1 : return v.string(false)
1185 1 : }
1186 :
1187 : // DebugString returns an alternative format to String() which includes sequence
1188 : // number and kind information for the sstable boundaries.
1189 1 : func (v *Version) DebugString() string {
1190 1 : return v.string(true)
1191 1 : }
1192 :
1193 1 : func describeSublevels(format base.FormatKey, verbose bool, sublevels []LevelSlice) string {
1194 1 : var buf bytes.Buffer
1195 1 : for sublevel := len(sublevels) - 1; sublevel >= 0; sublevel-- {
1196 1 : fmt.Fprintf(&buf, "L0.%d:\n", sublevel)
1197 1 : sublevels[sublevel].Each(func(f *FileMetadata) {
1198 1 : fmt.Fprintf(&buf, " %s\n", f.DebugString(format, verbose))
1199 1 : })
1200 : }
1201 1 : return buf.String()
1202 : }
1203 :
1204 1 : func (v *Version) string(verbose bool) string {
1205 1 : var buf bytes.Buffer
1206 1 : if len(v.L0SublevelFiles) > 0 {
1207 1 : fmt.Fprintf(&buf, "%s", describeSublevels(v.cmp.FormatKey, verbose, v.L0SublevelFiles))
1208 1 : }
1209 1 : for level := 1; level < NumLevels; level++ {
1210 1 : if v.Levels[level].Empty() {
1211 1 : continue
1212 : }
1213 1 : fmt.Fprintf(&buf, "L%d:\n", level)
1214 1 : iter := v.Levels[level].Iter()
1215 1 : for f := iter.First(); f != nil; f = iter.Next() {
1216 1 : fmt.Fprintf(&buf, " %s\n", f.DebugString(v.cmp.FormatKey, verbose))
1217 1 : }
1218 : }
1219 1 : return buf.String()
1220 : }
1221 :
1222 : // ParseVersionDebug parses a Version from its DebugString output.
1223 1 : func ParseVersionDebug(comparer *base.Comparer, flushSplitBytes int64, s string) (*Version, error) {
1224 1 : var files [NumLevels][]*FileMetadata
1225 1 : level := -1
1226 1 : for _, l := range strings.Split(s, "\n") {
1227 1 : if l == "" {
1228 1 : continue
1229 : }
1230 1 : p := makeDebugParser(l)
1231 1 : if l, ok := p.TryLevel(); ok {
1232 1 : level = l
1233 1 : continue
1234 : }
1235 :
1236 1 : if level == -1 {
1237 0 : return nil, errors.Errorf("version string must start with a level")
1238 0 : }
1239 1 : m, err := ParseFileMetadataDebug(l)
1240 1 : if err != nil {
1241 0 : return nil, err
1242 0 : }
1243 1 : files[level] = append(files[level], m)
1244 : }
1245 : // L0 files are printed from higher sublevel to lower, which means in a
1246 : // partial order that represents newest to oldest. Reverse the order of L0
1247 : // files to ensure we construct the same sublevels.
1248 1 : slices.Reverse(files[0])
1249 1 : v := NewVersion(comparer, flushSplitBytes, files)
1250 1 : if err := v.CheckOrdering(); err != nil {
1251 1 : return nil, err
1252 1 : }
1253 1 : return v, nil
1254 : }
1255 :
1256 : // Refs returns the number of references to the version.
1257 1 : func (v *Version) Refs() int32 {
1258 1 : return v.refs.Load()
1259 1 : }
1260 :
1261 : // Ref increments the version refcount.
1262 1 : func (v *Version) Ref() {
1263 1 : v.refs.Add(1)
1264 1 : }
1265 :
1266 : // Unref decrements the version refcount. If the last reference to the version
1267 : // was removed, the version is removed from the list of versions and the
1268 : // Deleted callback is invoked. Requires that the VersionList mutex is NOT
1269 : // locked.
1270 1 : func (v *Version) Unref() {
1271 1 : if v.refs.Add(-1) == 0 {
1272 1 : l := v.list
1273 1 : l.mu.Lock()
1274 1 : l.Remove(v)
1275 1 : v.Deleted(v.unrefFiles())
1276 1 : l.mu.Unlock()
1277 1 : }
1278 : }
1279 :
1280 : // UnrefLocked decrements the version refcount. If the last reference to the
1281 : // version was removed, the version is removed from the list of versions and
1282 : // the Deleted callback is invoked. Requires that the VersionList mutex is
1283 : // already locked.
1284 1 : func (v *Version) UnrefLocked() {
1285 1 : if v.refs.Add(-1) == 0 {
1286 1 : v.list.Remove(v)
1287 1 : v.Deleted(v.unrefFiles())
1288 1 : }
1289 : }
1290 :
1291 1 : func (v *Version) unrefFiles() []*FileBacking {
1292 1 : var obsolete []*FileBacking
1293 1 : for _, lm := range v.Levels {
1294 1 : obsolete = append(obsolete, lm.release()...)
1295 1 : }
1296 1 : for _, lm := range v.RangeKeyLevels {
1297 1 : obsolete = append(obsolete, lm.release()...)
1298 1 : }
1299 1 : return obsolete
1300 : }
1301 :
1302 : // Next returns the next version in the list of versions.
1303 0 : func (v *Version) Next() *Version {
1304 0 : return v.next
1305 0 : }
1306 :
1307 : // InitL0Sublevels initializes the L0Sublevels
1308 1 : func (v *Version) InitL0Sublevels(flushSplitBytes int64) error {
1309 1 : var err error
1310 1 : v.L0Sublevels, err = NewL0Sublevels(&v.Levels[0], v.cmp.Compare, v.cmp.FormatKey, flushSplitBytes)
1311 1 : if err == nil && v.L0Sublevels != nil {
1312 1 : v.L0SublevelFiles = v.L0Sublevels.Levels
1313 1 : }
1314 1 : return err
1315 : }
1316 :
1317 : // CalculateInuseKeyRanges examines file metadata in levels [level, maxLevel]
1318 : // within bounds [smallest,largest], returning an ordered slice of key ranges
1319 : // that include all keys that exist within levels [level, maxLevel] and within
1320 : // [smallest,largest].
1321 : func (v *Version) CalculateInuseKeyRanges(
1322 : level, maxLevel int, smallest, largest []byte,
1323 1 : ) []base.UserKeyBounds {
1324 1 : // Use two slices, alternating which one is input and which one is output
1325 1 : // as we descend the LSM.
1326 1 : var input, output []base.UserKeyBounds
1327 1 :
1328 1 : // L0 requires special treatment, since sstables within L0 may overlap.
1329 1 : // We use the L0 Sublevels structure to efficiently calculate the merged
1330 1 : // in-use key ranges.
1331 1 : if level == 0 {
1332 1 : output = v.L0Sublevels.InUseKeyRanges(smallest, largest)
1333 1 : level++
1334 1 : }
1335 :
1336 : // NB: We always treat `largest` as inclusive for simplicity, because
1337 : // there's little consequence to calculating slightly broader in-use key
1338 : // ranges.
1339 1 : bounds := base.UserKeyBoundsInclusive(smallest, largest)
1340 1 : for ; level <= maxLevel; level++ {
1341 1 : overlaps := v.Overlaps(level, bounds)
1342 1 : iter := overlaps.Iter()
1343 1 :
1344 1 : // We may already have in-use key ranges from higher levels. Iterate
1345 1 : // through both our accumulated in-use key ranges and this level's
1346 1 : // files, merging the two.
1347 1 : //
1348 1 : // Tables higher within the LSM have broader key spaces. We use this
1349 1 : // when possible to seek past a level's files that are contained by
1350 1 : // our current accumulated in-use key ranges. This helps avoid
1351 1 : // per-sstable work during flushes or compactions in high levels which
1352 1 : // overlap the majority of the LSM's sstables.
1353 1 : input, output = output, input
1354 1 : output = output[:0]
1355 1 :
1356 1 : cmp := v.cmp.Compare
1357 1 : inputIdx := 0
1358 1 : var currFile *FileMetadata
1359 1 : // If we have an accumulated key range and its start is ≤ smallest,
1360 1 : // we can seek to the accumulated range's end. Otherwise, we need to
1361 1 : // start at the first overlapping file within the level.
1362 1 : if len(input) > 0 && cmp(input[0].Start, smallest) <= 0 {
1363 1 : currFile = seekGT(&iter, cmp, input[0].End)
1364 1 : } else {
1365 1 : currFile = iter.First()
1366 1 : }
1367 :
1368 1 : for currFile != nil && inputIdx < len(input) {
1369 1 : // Invariant: Neither currFile nor input[inputIdx] overlaps any earlier
1370 1 : // ranges.
1371 1 : switch {
1372 1 : case cmp(currFile.Largest.UserKey, input[inputIdx].Start) < 0:
1373 1 : // File is completely before input range.
1374 1 : output = append(output, currFile.UserKeyBounds())
1375 1 : currFile = iter.Next()
1376 :
1377 1 : case cmp(input[inputIdx].End.Key, currFile.Smallest.UserKey) < 0:
1378 1 : // Input range is completely before the next file.
1379 1 : output = append(output, input[inputIdx])
1380 1 : inputIdx++
1381 :
1382 1 : default:
1383 1 : // Input range and file range overlap or touch. We will maximally extend
1384 1 : // the range with more overlapping inputs and files.
1385 1 : currAccum := currFile.UserKeyBounds()
1386 1 : if cmp(input[inputIdx].Start, currAccum.Start) < 0 {
1387 1 : currAccum.Start = input[inputIdx].Start
1388 1 : }
1389 1 : currFile = iter.Next()
1390 1 :
1391 1 : // Extend curAccum with any overlapping (or touching) input intervals or
1392 1 : // files. Note that we will always consume at least input[inputIdx].
1393 1 : for {
1394 1 : if inputIdx < len(input) && cmp(input[inputIdx].Start, currAccum.End.Key) <= 0 {
1395 1 : if currAccum.End.CompareUpperBounds(cmp, input[inputIdx].End) < 0 {
1396 1 : currAccum.End = input[inputIdx].End
1397 1 : // Skip over files that are entirely inside this newly extended
1398 1 : // accumulated range; we expect ranges to be wider in levels that
1399 1 : // are higher up so this might skip over a non-trivial number of
1400 1 : // files.
1401 1 : currFile = seekGT(&iter, cmp, currAccum.End)
1402 1 : }
1403 1 : inputIdx++
1404 1 : } else if currFile != nil && cmp(currFile.Smallest.UserKey, currAccum.End.Key) <= 0 {
1405 1 : if b := currFile.UserKeyBounds(); currAccum.End.CompareUpperBounds(cmp, b.End) < 0 {
1406 1 : currAccum.End = b.End
1407 1 : }
1408 1 : currFile = iter.Next()
1409 1 : } else {
1410 1 : // No overlaps remaining.
1411 1 : break
1412 : }
1413 : }
1414 1 : output = append(output, currAccum)
1415 : }
1416 : }
1417 : // If we have either files or input ranges left over, add them to the
1418 : // output.
1419 1 : output = append(output, input[inputIdx:]...)
1420 1 : for ; currFile != nil; currFile = iter.Next() {
1421 1 : output = append(output, currFile.UserKeyBounds())
1422 1 : }
1423 : }
1424 1 : return output
1425 : }
1426 :
1427 : // seekGT seeks to the first file that ends with a boundary that is after the
1428 : // given boundary. Specifically:
1429 : // - if boundary.End is inclusive, the returned file ending boundary is strictly
1430 : // greater than boundary.End.Key
1431 : // - if boundary.End is exclusive, the returned file ending boundary is either
1432 : // greater than boundary.End.Key, or it's inclusive at boundary.End.Key.
1433 1 : func seekGT(iter *LevelIterator, cmp base.Compare, boundary base.UserKeyBoundary) *FileMetadata {
1434 1 : f := iter.SeekGE(cmp, boundary.Key)
1435 1 : if f == nil {
1436 1 : return nil
1437 1 : }
1438 : // If boundary is inclusive or the file boundary is exclusive we do not
1439 : // tolerate an equal largest key.
1440 : // Note: we know f.Largest.UserKey >= boundary.End.Key so this condition is
1441 : // equivalent to boundary.End.IsUpperBoundForInternalKey(cmp, f.Largest).
1442 1 : if (boundary.Kind == base.Inclusive || f.Largest.IsExclusiveSentinel()) && cmp(boundary.Key, f.Largest.UserKey) == 0 {
1443 1 : return iter.Next()
1444 1 : }
1445 1 : return f
1446 : }
1447 :
1448 : // Contains returns a boolean indicating whether the provided file exists in
1449 : // the version at the given level. If level is non-zero then Contains binary
1450 : // searches among the files. If level is zero, Contains scans the entire
1451 : // level.
1452 1 : func (v *Version) Contains(level int, m *FileMetadata) bool {
1453 1 : iter := v.Levels[level].Iter()
1454 1 : if level > 0 {
1455 1 : overlaps := v.Overlaps(level, m.UserKeyBounds())
1456 1 : iter = overlaps.Iter()
1457 1 : }
1458 1 : for f := iter.First(); f != nil; f = iter.Next() {
1459 1 : if f == m {
1460 1 : return true
1461 1 : }
1462 : }
1463 1 : return false
1464 : }
1465 :
1466 : // Overlaps returns all elements of v.files[level] whose user key range
1467 : // intersects the given bounds. If level is non-zero then the user key bounds of
1468 : // v.files[level] are assumed to not overlap (although they may touch). If level
1469 : // is zero then that assumption cannot be made, and the given bounds are
1470 : // expanded to the union of those matching bounds so far and the computation is
1471 : // repeated until the bounds stabilize.
1472 : // The returned files are a subsequence of the input files, i.e., the ordering
1473 : // is not changed.
1474 1 : func (v *Version) Overlaps(level int, bounds base.UserKeyBounds) LevelSlice {
1475 1 : if level == 0 {
1476 1 : // Indices that have been selected as overlapping.
1477 1 : l0 := v.Levels[level]
1478 1 : l0Iter := l0.Iter()
1479 1 : selectedIndices := make([]bool, l0.Len())
1480 1 : numSelected := 0
1481 1 : var slice LevelSlice
1482 1 : for {
1483 1 : restart := false
1484 1 : for i, meta := 0, l0Iter.First(); meta != nil; i, meta = i+1, l0Iter.Next() {
1485 1 : selected := selectedIndices[i]
1486 1 : if selected {
1487 1 : continue
1488 : }
1489 1 : if !meta.Overlaps(v.cmp.Compare, &bounds) {
1490 1 : // meta is completely outside the specified range; skip it.
1491 1 : continue
1492 : }
1493 : // Overlaps.
1494 1 : selectedIndices[i] = true
1495 1 : numSelected++
1496 1 :
1497 1 : // Since this is L0, check if the newly added fileMetadata has expanded
1498 1 : // the range. We expand the range immediately for files we have
1499 1 : // remaining to check in this loop. All already checked and unselected
1500 1 : // files will need to be rechecked via the restart below.
1501 1 : if v.cmp.Compare(meta.Smallest.UserKey, bounds.Start) < 0 {
1502 1 : bounds.Start = meta.Smallest.UserKey
1503 1 : restart = true
1504 1 : }
1505 1 : if !bounds.End.IsUpperBoundForInternalKey(v.cmp.Compare, meta.Largest) {
1506 1 : bounds.End = base.UserKeyExclusiveIf(meta.Largest.UserKey, meta.Largest.IsExclusiveSentinel())
1507 1 : restart = true
1508 1 : }
1509 : }
1510 :
1511 1 : if !restart {
1512 1 : // Construct a B-Tree containing only the matching items.
1513 1 : var tr btree
1514 1 : tr.bcmp = v.Levels[level].tree.bcmp
1515 1 : for i, meta := 0, l0Iter.First(); meta != nil; i, meta = i+1, l0Iter.Next() {
1516 1 : if selectedIndices[i] {
1517 1 : err := tr.Insert(meta)
1518 1 : if err != nil {
1519 0 : panic(err)
1520 : }
1521 : }
1522 : }
1523 1 : slice = newLevelSlice(tr.Iter())
1524 1 : // TODO(jackson): Avoid the oddity of constructing and
1525 1 : // immediately releasing a B-Tree. Make LevelSlice an
1526 1 : // interface?
1527 1 : tr.Release()
1528 1 : break
1529 : }
1530 : // Continue looping to retry the files that were not selected.
1531 : }
1532 1 : return slice
1533 : }
1534 :
1535 1 : return v.Levels[level].Slice().Overlaps(v.cmp.Compare, bounds)
1536 : }
1537 :
1538 : // IterAllLevelsAndSublevels calls fn with an iterator for each L0 sublevel
1539 : // (from top to bottom), then once for each level below L0.
1540 1 : func (v *Version) IterAllLevelsAndSublevels(fn func(it LevelIterator, level Layer)) {
1541 1 : for sublevel := len(v.L0SublevelFiles) - 1; sublevel >= 0; sublevel-- {
1542 1 : fn(v.L0SublevelFiles[sublevel].Iter(), L0Sublevel(sublevel))
1543 1 : }
1544 1 : for level := 1; level < NumLevels; level++ {
1545 1 : fn(v.Levels[level].Iter(), Level(level))
1546 1 : }
1547 : }
1548 :
1549 : // CheckOrdering checks that the files are consistent with respect to
1550 : // increasing file numbers (for level 0 files) and increasing and non-
1551 : // overlapping internal key ranges (for level non-0 files).
1552 1 : func (v *Version) CheckOrdering() error {
1553 1 : for sublevel := len(v.L0SublevelFiles) - 1; sublevel >= 0; sublevel-- {
1554 1 : sublevelIter := v.L0SublevelFiles[sublevel].Iter()
1555 1 : if err := CheckOrdering(v.cmp.Compare, v.cmp.FormatKey, L0Sublevel(sublevel), sublevelIter); err != nil {
1556 0 : return base.CorruptionErrorf("%s\n%s", err, v.DebugString())
1557 0 : }
1558 : }
1559 :
1560 1 : for level, lm := range v.Levels {
1561 1 : if err := CheckOrdering(v.cmp.Compare, v.cmp.FormatKey, Level(level), lm.Iter()); err != nil {
1562 1 : return base.CorruptionErrorf("%s\n%s", err, v.DebugString())
1563 1 : }
1564 : }
1565 1 : return nil
1566 : }
1567 :
1568 : // VersionList holds a list of versions. The versions are ordered from oldest
1569 : // to newest.
1570 : type VersionList struct {
1571 : mu *sync.Mutex
1572 : root Version
1573 : }
1574 :
1575 : // Init initializes the version list.
1576 1 : func (l *VersionList) Init(mu *sync.Mutex) {
1577 1 : l.mu = mu
1578 1 : l.root.next = &l.root
1579 1 : l.root.prev = &l.root
1580 1 : }
1581 :
1582 : // Empty returns true if the list is empty, and false otherwise.
1583 1 : func (l *VersionList) Empty() bool {
1584 1 : return l.root.next == &l.root
1585 1 : }
1586 :
1587 : // Front returns the oldest version in the list. Note that this version is only
1588 : // valid if Empty() returns true.
1589 1 : func (l *VersionList) Front() *Version {
1590 1 : return l.root.next
1591 1 : }
1592 :
1593 : // Back returns the newest version in the list. Note that this version is only
1594 : // valid if Empty() returns true.
1595 1 : func (l *VersionList) Back() *Version {
1596 1 : return l.root.prev
1597 1 : }
1598 :
1599 : // PushBack adds a new version to the back of the list. This new version
1600 : // becomes the "newest" version in the list.
1601 1 : func (l *VersionList) PushBack(v *Version) {
1602 1 : if v.list != nil || v.prev != nil || v.next != nil {
1603 0 : panic("pebble: version list is inconsistent")
1604 : }
1605 1 : v.prev = l.root.prev
1606 1 : v.prev.next = v
1607 1 : v.next = &l.root
1608 1 : v.next.prev = v
1609 1 : v.list = l
1610 1 : // Let L0Sublevels on the second newest version get GC'd, as it is no longer
1611 1 : // necessary. See the comment in Version.
1612 1 : v.prev.L0Sublevels = nil
1613 : }
1614 :
1615 : // Remove removes the specified version from the list.
1616 1 : func (l *VersionList) Remove(v *Version) {
1617 1 : if v == &l.root {
1618 0 : panic("pebble: cannot remove version list root node")
1619 : }
1620 1 : if v.list != l {
1621 0 : panic("pebble: version list is inconsistent")
1622 : }
1623 1 : v.prev.next = v.next
1624 1 : v.next.prev = v.prev
1625 1 : v.next = nil // avoid memory leaks
1626 1 : v.prev = nil // avoid memory leaks
1627 1 : v.list = nil // avoid memory leaks
1628 : }
1629 :
1630 : // CheckOrdering checks that the files are consistent with respect to
1631 : // seqnums (for level 0 files -- see detailed comment below) and increasing and non-
1632 : // overlapping internal key ranges (for non-level 0 files).
1633 1 : func CheckOrdering(cmp Compare, format base.FormatKey, level Layer, files LevelIterator) error {
1634 1 : // The invariants to check for L0 sublevels are the same as the ones to
1635 1 : // check for all other levels. However, if L0 is not organized into
1636 1 : // sublevels, or if all L0 files are being passed in, we do the legacy L0
1637 1 : // checks, defined in the detailed comment below.
1638 1 : if level == Level(0) {
1639 1 : // We have 2 kinds of files:
1640 1 : // - Files with exactly one sequence number: these could be either ingested files
1641 1 : // or flushed files. We cannot tell the difference between them based on FileMetadata,
1642 1 : // so our consistency checking here uses the weaker checks assuming it is a narrow
1643 1 : // flushed file. We cannot error on ingested files having sequence numbers coincident
1644 1 : // with flushed files as the seemingly ingested file could just be a flushed file
1645 1 : // with just one key in it which is a truncated range tombstone sharing sequence numbers
1646 1 : // with other files in the same flush.
1647 1 : // - Files with multiple sequence numbers: these are necessarily flushed files.
1648 1 : //
1649 1 : // Three cases of overlapping sequence numbers:
1650 1 : // Case 1:
1651 1 : // An ingested file contained in the sequence numbers of the flushed file -- it must be
1652 1 : // fully contained (not coincident with either end of the flushed file) since the memtable
1653 1 : // must have been at [a, b-1] (where b > a) when the ingested file was assigned sequence
1654 1 : // num b, and the memtable got a subsequent update that was given sequence num b+1, before
1655 1 : // being flushed.
1656 1 : //
1657 1 : // So a sequence [1000, 1000] [1002, 1002] [1000, 2000] is invalid since the first and
1658 1 : // third file are inconsistent with each other. So comparing adjacent files is insufficient
1659 1 : // for consistency checking.
1660 1 : //
1661 1 : // Visually we have something like
1662 1 : // x------y x-----------yx-------------y (flushed files where x, y are the endpoints)
1663 1 : // y y y y (y's represent ingested files)
1664 1 : // And these are ordered in increasing order of y. Note that y's must be unique.
1665 1 : //
1666 1 : // Case 2:
1667 1 : // A flushed file that did not overlap in keys with any file in any level, but does overlap
1668 1 : // in the file key intervals. This file is placed in L0 since it overlaps in the file
1669 1 : // key intervals but since it has no overlapping data, it is assigned a sequence number
1670 1 : // of 0 in RocksDB. We handle this case for compatibility with RocksDB.
1671 1 : //
1672 1 : // Case 3:
1673 1 : // A sequence of flushed files that overlap in sequence numbers with one another,
1674 1 : // but do not overlap in keys inside the sstables. These files correspond to
1675 1 : // partitioned flushes or the results of intra-L0 compactions of partitioned
1676 1 : // flushes.
1677 1 : //
1678 1 : // Since these types of SSTables violate most other sequence number
1679 1 : // overlap invariants, and handling this case is important for compatibility
1680 1 : // with future versions of pebble, this method relaxes most L0 invariant
1681 1 : // checks.
1682 1 :
1683 1 : var prev *FileMetadata
1684 1 : for f := files.First(); f != nil; f, prev = files.Next(), f {
1685 1 : if prev == nil {
1686 1 : continue
1687 : }
1688 : // Validate that the sorting is sane.
1689 1 : if prev.LargestSeqNum == 0 && f.LargestSeqNum == prev.LargestSeqNum {
1690 1 : // Multiple files satisfying case 2 mentioned above.
1691 1 : } else if !prev.lessSeqNum(f) {
1692 1 : return base.CorruptionErrorf("L0 files %s and %s are not properly ordered: <#%d-#%d> vs <#%d-#%d>",
1693 1 : errors.Safe(prev.FileNum), errors.Safe(f.FileNum),
1694 1 : errors.Safe(prev.SmallestSeqNum), errors.Safe(prev.LargestSeqNum),
1695 1 : errors.Safe(f.SmallestSeqNum), errors.Safe(f.LargestSeqNum))
1696 1 : }
1697 : }
1698 1 : } else {
1699 1 : var prev *FileMetadata
1700 1 : for f := files.First(); f != nil; f, prev = files.Next(), f {
1701 1 : if err := f.Validate(cmp, format); err != nil {
1702 1 : return errors.Wrapf(err, "%s ", level)
1703 1 : }
1704 1 : if prev != nil {
1705 1 : if prev.cmpSmallestKey(f, cmp) >= 0 {
1706 1 : return base.CorruptionErrorf("%s files %s and %s are not properly ordered: [%s-%s] vs [%s-%s]",
1707 1 : errors.Safe(level), errors.Safe(prev.FileNum), errors.Safe(f.FileNum),
1708 1 : prev.Smallest.Pretty(format), prev.Largest.Pretty(format),
1709 1 : f.Smallest.Pretty(format), f.Largest.Pretty(format))
1710 1 : }
1711 :
1712 : // In all supported format major version, split user keys are
1713 : // prohibited, so both files cannot contain keys with the same user
1714 : // keys. If the bounds have the same user key, the previous file's
1715 : // boundary must have a InternalKeyTrailer indicating that it's exclusive.
1716 1 : if v := cmp(prev.Largest.UserKey, f.Smallest.UserKey); v > 0 || (v == 0 && !prev.Largest.IsExclusiveSentinel()) {
1717 1 : return base.CorruptionErrorf("%s files %s and %s have overlapping ranges: [%s-%s] vs [%s-%s]",
1718 1 : errors.Safe(level), errors.Safe(prev.FileNum), errors.Safe(f.FileNum),
1719 1 : prev.Smallest.Pretty(format), prev.Largest.Pretty(format),
1720 1 : f.Smallest.Pretty(format), f.Largest.Pretty(format))
1721 1 : }
1722 : }
1723 : }
1724 : }
1725 1 : return nil
1726 : }
|