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