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