Line data Source code
1 : // Copyright 2018 The LevelDB-Go and Pebble Authors. All rights reserved. Use
2 : // of this source code is governed by a BSD-style license that can be found in
3 : // the LICENSE file.
4 :
5 : package pebble
6 :
7 : import (
8 : "context"
9 : "fmt"
10 : "runtime/debug"
11 :
12 : "github.com/cockroachdb/errors"
13 : "github.com/cockroachdb/pebble/internal/base"
14 : "github.com/cockroachdb/pebble/internal/invariants"
15 : "github.com/cockroachdb/pebble/internal/keyspan"
16 : "github.com/cockroachdb/pebble/internal/manifest"
17 : "github.com/cockroachdb/pebble/internal/treeprinter"
18 : )
19 :
20 : // levelIter provides a merged view of the sstables in a level.
21 : //
22 : // levelIter is used during compaction and as part of the Iterator
23 : // implementation. When used as part of the Iterator implementation, level
24 : // iteration needs to "pause" at range deletion boundaries if file contains
25 : // range deletions. In this case, the levelIter uses a keyspan.InterleavingIter
26 : // to materialize InternalKVs at start and end boundaries of range deletions.
27 : // This prevents mergingIter from advancing past the sstable until the sstable
28 : // contains the smallest (or largest for reverse iteration) key in the merged
29 : // heap. Note that mergingIter treats a range deletion tombstone returned by the
30 : // point iterator as a no-op.
31 : type levelIter struct {
32 : // The context is stored here since (a) iterators are expected to be
33 : // short-lived (since they pin sstables), (b) plumbing a context into every
34 : // method is very painful, (c) they do not (yet) respect context
35 : // cancellation and are only used for tracing.
36 : ctx context.Context
37 : logger Logger
38 : comparer *Comparer
39 : cmp Compare
40 : split Split
41 : // The lower/upper bounds for iteration as specified at creation or the most
42 : // recent call to SetBounds.
43 : lower []byte
44 : upper []byte
45 : // prefix holds the iteration prefix when the most recent absolute
46 : // positioning method was a SeekPrefixGE.
47 : prefix []byte
48 : // The iterator options for the currently open table. If
49 : // tableOpts.{Lower,Upper}Bound are nil, the corresponding iteration boundary
50 : // does not lie within the table bounds.
51 : tableOpts IterOptions
52 : // The layer this levelIter is initialized for. This can be either
53 : // a level L1+, an L0 sublevel, or a flushable ingests layer.
54 : layer manifest.Layer
55 : // combinedIterState may be set when a levelIter is used during user
56 : // iteration. Although levelIter only iterates over point keys, it's also
57 : // responsible for lazily constructing the combined range & point iterator
58 : // when it observes a file containing range keys. If the combined iter
59 : // state's initialized field is true, the iterator is already using combined
60 : // iterator, OR the iterator is not configured to use combined iteration. If
61 : // it's false, the levelIter must set the `triggered` and `key` fields when
62 : // the levelIter passes over a file containing range keys. See the
63 : // lazyCombinedIter for more details.
64 : combinedIterState *combinedIterState
65 : // The iter for the current file. It is nil under any of the following conditions:
66 : // - files.Current() == nil
67 : // - err != nil
68 : // - some other constraint, like the bounds in opts, caused the file at index to not
69 : // be relevant to the iteration.
70 : iter internalIterator
71 : // iterFile holds the current file. It is always equal to l.files.Current().
72 : iterFile *manifest.TableMetadata
73 : newIters tableNewIters
74 : files manifest.LevelIterator
75 : err error
76 :
77 : // When rangeDelIterSetter != nil, the caller requires that this function
78 : // gets called with a range deletion iterator whenever the current file
79 : // changes. The iterator is relinquished to the caller which is responsible
80 : // for closing it.
81 : //
82 : // When rangeDelIterSetter != nil, the levelIter will also interleave the
83 : // boundaries of range deletions among point keys.
84 : rangeDelIterSetter rangeDelIterSetter
85 :
86 : // interleaving is used when rangeDelIterFn != nil to interleave the
87 : // boundaries of range deletions among point keys. When the leve iterator is
88 : // used by a merging iterator, this ensures that we don't advance to a new
89 : // file until the range deletions are no longer needed by other levels.
90 : interleaving keyspan.InterleavingIter
91 :
92 : // internalOpts holds the internal iterator options to pass to the table
93 : // cache when constructing new table iterators.
94 : internalOpts internalIterOpts
95 :
96 : // Scratch space for the obsolete keys filter, when there are no other block
97 : // property filters specified. See the performance note where
98 : // IterOptions.PointKeyFilters is declared.
99 : filtersBuf [1]BlockPropertyFilter
100 :
101 : // exhaustedDir is set to +1 or -1 when the levelIter has been exhausted in
102 : // the forward or backward direction respectively. It is set when the
103 : // underlying data is exhausted or when iteration has reached the upper or
104 : // lower boundary and interleaved a synthetic iterator bound key. When the
105 : // iterator is exhausted and Next or Prev is called, the levelIter uses
106 : // exhaustedDir to determine whether the iterator should step on to the
107 : // first or last key within iteration bounds.
108 : exhaustedDir int8
109 :
110 : // Disable invariant checks even if they are otherwise enabled. Used by tests
111 : // which construct "impossible" situations (e.g. seeking to a key before the
112 : // lower bound).
113 : disableInvariants bool
114 : }
115 :
116 : type rangeDelIterSetter interface {
117 : setRangeDelIter(rangeDelIter keyspan.FragmentIterator)
118 : }
119 :
120 : // levelIter implements the base.InternalIterator interface.
121 : var _ base.InternalIterator = (*levelIter)(nil)
122 :
123 : // newLevelIter returns a levelIter. It is permissible to pass a nil split
124 : // parameter if the caller is never going to call SeekPrefixGE.
125 : func newLevelIter(
126 : ctx context.Context,
127 : opts IterOptions,
128 : comparer *Comparer,
129 : newIters tableNewIters,
130 : files manifest.LevelIterator,
131 : layer manifest.Layer,
132 : internalOpts internalIterOpts,
133 2 : ) *levelIter {
134 2 : l := &levelIter{}
135 2 : l.init(ctx, opts, comparer, newIters, files, layer, internalOpts)
136 2 : return l
137 2 : }
138 :
139 : func (l *levelIter) init(
140 : ctx context.Context,
141 : opts IterOptions,
142 : comparer *Comparer,
143 : newIters tableNewIters,
144 : files manifest.LevelIterator,
145 : layer manifest.Layer,
146 : internalOpts internalIterOpts,
147 2 : ) {
148 2 : l.ctx = ctx
149 2 : l.err = nil
150 2 : l.layer = layer
151 2 : l.logger = opts.getLogger()
152 2 : l.prefix = nil
153 2 : l.lower = opts.LowerBound
154 2 : l.upper = opts.UpperBound
155 2 : l.tableOpts.PointKeyFilters = opts.PointKeyFilters
156 2 : if len(opts.PointKeyFilters) == 0 {
157 2 : l.tableOpts.PointKeyFilters = l.filtersBuf[:0:1]
158 2 : }
159 2 : l.tableOpts.UseL6Filters = opts.UseL6Filters
160 2 : l.tableOpts.Category = opts.Category
161 2 : l.tableOpts.layer = l.layer
162 2 : l.tableOpts.snapshotForHideObsoletePoints = opts.snapshotForHideObsoletePoints
163 2 : l.comparer = comparer
164 2 : l.cmp = comparer.Compare
165 2 : l.split = comparer.Split
166 2 : l.iterFile = nil
167 2 : l.newIters = newIters
168 2 : l.files = files
169 2 : l.exhaustedDir = 0
170 2 : l.internalOpts = internalOpts
171 : }
172 :
173 : // initRangeDel puts the level iterator into a mode where it interleaves range
174 : // deletion boundaries with point keys and provides a range deletion iterator
175 : // (through rangeDelIterFn) whenever the current file changes.
176 : //
177 : // The range deletion iterator passed to rangeDelIterFn is relinquished to the
178 : // implementor who is responsible for closing it.
179 2 : func (l *levelIter) initRangeDel(rangeDelSetter rangeDelIterSetter) {
180 2 : l.rangeDelIterSetter = rangeDelSetter
181 2 : }
182 :
183 2 : func (l *levelIter) initCombinedIterState(state *combinedIterState) {
184 2 : l.combinedIterState = state
185 2 : }
186 :
187 2 : func (l *levelIter) maybeTriggerCombinedIteration(file *manifest.TableMetadata, dir int) {
188 2 : // If we encounter a file that contains range keys, we may need to
189 2 : // trigger a switch to combined range-key and point-key iteration,
190 2 : // if the *pebble.Iterator is configured for it. This switch is done
191 2 : // lazily because range keys are intended to be rare, and
192 2 : // constructing the range-key iterator substantially adds to the
193 2 : // cost of iterator construction and seeking.
194 2 : //
195 2 : // If l.combinedIterState.initialized is already true, either the
196 2 : // iterator is already using combined iteration or the iterator is not
197 2 : // configured to observe range keys. Either way, there's nothing to do.
198 2 : // If false, trigger the switch to combined iteration, using the the
199 2 : // file's bounds to seek the range-key iterator appropriately.
200 2 : //
201 2 : // We only need to trigger combined iteration if the file contains
202 2 : // RangeKeySets: if there are only Unsets and Dels, the user will observe no
203 2 : // range keys regardless. If this file has table stats available, they'll
204 2 : // tell us whether the file has any RangeKeySets. Otherwise, we must
205 2 : // fallback to assuming it does if HasRangeKeys=true.
206 2 : if file != nil && file.HasRangeKeys && l.combinedIterState != nil && !l.combinedIterState.initialized &&
207 2 : (l.upper == nil || l.cmp(file.RangeKeyBounds.SmallestUserKey(), l.upper) < 0) &&
208 2 : (l.lower == nil || l.cmp(file.RangeKeyBounds.LargestUserKey(), l.lower) > 0) &&
209 2 : (!file.StatsValid() || file.Stats.NumRangeKeySets > 0) {
210 2 : // The file contains range keys, and we're not using combined iteration yet.
211 2 : // Trigger a switch to combined iteration. It's possible that a switch has
212 2 : // already been triggered if multiple levels encounter files containing
213 2 : // range keys while executing a single mergingIter operation. In this case,
214 2 : // we need to compare the existing key recorded to l.combinedIterState.key,
215 2 : // adjusting it if our key is smaller (forward iteration) or larger
216 2 : // (backward iteration) than the existing key.
217 2 : //
218 2 : // These key comparisons are only required during a single high-level
219 2 : // iterator operation. When the high-level iter op completes,
220 2 : // iinitialized will be true, and future calls to this function will be
221 2 : // no-ops.
222 2 : switch dir {
223 2 : case +1:
224 2 : if !l.combinedIterState.triggered {
225 2 : l.combinedIterState.triggered = true
226 2 : l.combinedIterState.key = file.RangeKeyBounds.SmallestUserKey()
227 2 : } else if l.cmp(l.combinedIterState.key, file.RangeKeyBounds.SmallestUserKey()) > 0 {
228 2 : l.combinedIterState.key = file.RangeKeyBounds.SmallestUserKey()
229 2 : }
230 2 : case -1:
231 2 : if !l.combinedIterState.triggered {
232 2 : l.combinedIterState.triggered = true
233 2 : l.combinedIterState.key = file.RangeKeyBounds.LargestUserKey()
234 2 : } else if l.cmp(l.combinedIterState.key, file.RangeKeyBounds.LargestUserKey()) < 0 {
235 2 : l.combinedIterState.key = file.RangeKeyBounds.LargestUserKey()
236 2 : }
237 : }
238 : }
239 : }
240 :
241 2 : func (l *levelIter) findFileGE(key []byte, flags base.SeekGEFlags) *manifest.TableMetadata {
242 2 : // Find the earliest file whose largest key is >= key.
243 2 :
244 2 : // NB: if flags.TrySeekUsingNext()=true, the levelIter must respect it. If
245 2 : // the levelIter is positioned at the key P, it must return a key ≥ P. If
246 2 : // used within a merging iterator, the merging iterator will depend on the
247 2 : // levelIter only moving forward to maintain heap invariants.
248 2 :
249 2 : // Ordinarily we seek the LevelIterator using SeekGE. In some instances, we
250 2 : // Next instead. In other instances, we try Next-ing first, falling back to
251 2 : // seek:
252 2 : // a) flags.TrySeekUsingNext(): The top-level Iterator knows we're seeking
253 2 : // to a key later than the current iterator position. We don't know how
254 2 : // much later the seek key is, so it's possible there are many sstables
255 2 : // between the current position and the seek key. However in most real-
256 2 : // world use cases, the seek key is likely to be nearby. Rather than
257 2 : // performing a log(N) seek through the table metadata, we next a few
258 2 : // times from our existing location. If we don't find a file whose
259 2 : // largest is >= key within a few nexts, we fall back to seeking.
260 2 : //
261 2 : // Note that in this case, the file returned by findFileGE may be
262 2 : // different than the file returned by a raw binary search (eg, when
263 2 : // TrySeekUsingNext=false). This is possible because the most recent
264 2 : // positioning operation may have already determined that previous
265 2 : // files' keys that are ≥ key are all deleted. This information is
266 2 : // encoded within the iterator's current iterator position and is
267 2 : // unavailable to a fresh binary search.
268 2 : //
269 2 : // b) flags.RelativeSeek(): The merging iterator decided to re-seek this
270 2 : // level according to a range tombstone. When lazy combined iteration
271 2 : // is enabled, the level iterator is responsible for watching for
272 2 : // files containing range keys and triggering the switch to combined
273 2 : // iteration when such a file is observed. If a range deletion was
274 2 : // observed in a higher level causing the merging iterator to seek the
275 2 : // level to the range deletion's end key, we need to check whether all
276 2 : // of the files between the old position and the new position contain
277 2 : // any range keys.
278 2 : //
279 2 : // In this scenario, we don't seek the LevelIterator and instead we
280 2 : // Next it, one file at a time, checking each for range keys. The
281 2 : // merging iterator sets this flag to inform us that we're moving
282 2 : // forward relative to the existing position and that we must examine
283 2 : // each intermediate sstable's metadata for lazy-combined iteration.
284 2 : // In this case, we only Next and never Seek. We set nextsUntilSeek=-1
285 2 : // to signal this intention.
286 2 : //
287 2 : // NB: At most one of flags.RelativeSeek() and flags.TrySeekUsingNext() may
288 2 : // be set, because the merging iterator re-seeks relative seeks with
289 2 : // explicitly only the RelativeSeek flag set.
290 2 : var nextsUntilSeek int
291 2 : var nextInsteadOfSeek bool
292 2 : if flags.TrySeekUsingNext() {
293 2 : nextInsteadOfSeek = true
294 2 : nextsUntilSeek = 4 // arbitrary
295 2 : }
296 2 : if flags.RelativeSeek() && l.combinedIterState != nil && !l.combinedIterState.initialized {
297 2 : nextInsteadOfSeek = true
298 2 : nextsUntilSeek = -1
299 2 : }
300 :
301 2 : var m *manifest.TableMetadata
302 2 : if nextInsteadOfSeek {
303 2 : m = l.iterFile
304 2 : } else {
305 2 : m = l.files.SeekGE(l.cmp, key)
306 2 : }
307 : // The below loop has a bit of an unusual organization. There are several
308 : // conditions under which we need to Next to a later file. If none of those
309 : // conditions are met, the file in `m` is okay to return. The loop body is
310 : // structured with a series of if statements, each of which may continue the
311 : // loop to the next file. If none of the statements are met, the end of the
312 : // loop body is a break.
313 2 : for m != nil {
314 2 : if m.HasRangeKeys {
315 2 : l.maybeTriggerCombinedIteration(m, +1)
316 2 :
317 2 : // Some files may only contain range keys, which we can skip.
318 2 : // NB: HasPointKeys=true if the file contains any points or range
319 2 : // deletions (which delete points).
320 2 : if !m.HasPointKeys {
321 2 : m = l.files.Next()
322 2 : continue
323 : }
324 : }
325 :
326 : // This file has point keys.
327 : //
328 : // However, there are a couple reasons why `m` may not be positioned ≥
329 : // `key` yet:
330 : //
331 : // 1. If SeekGE(key) landed on a file containing range keys, the file
332 : // may contain range keys ≥ `key` but no point keys ≥ `key`.
333 : // 2. When nexting instead of seeking, we must check to see whether
334 : // we've nexted sufficiently far, or we need to next again.
335 : //
336 : // If the file does not contain point keys ≥ `key`, next to continue
337 : // looking for a file that does.
338 2 : if (m.HasRangeKeys || nextInsteadOfSeek) && l.cmp(m.PointKeyBounds.LargestUserKey(), key) < 0 {
339 2 : // If nextInsteadOfSeek is set and nextsUntilSeek is non-negative,
340 2 : // the iterator has been nexting hoping to discover the relevant
341 2 : // file without seeking. It's exhausted the allotted nextsUntilSeek
342 2 : // and should seek to the sought key.
343 2 : if nextInsteadOfSeek && nextsUntilSeek == 0 {
344 1 : nextInsteadOfSeek = false
345 1 : m = l.files.SeekGE(l.cmp, key)
346 1 : continue
347 2 : } else if nextsUntilSeek > 0 {
348 2 : nextsUntilSeek--
349 2 : }
350 2 : m = l.files.Next()
351 2 : continue
352 : }
353 :
354 : // This file has a point key bound ≥ `key`. But the largest point key
355 : // bound may still be a range deletion sentinel, which is exclusive. In
356 : // this case, the file doesn't actually contain any point keys equal to
357 : // `key`. We next to keep searching for a file that actually contains
358 : // point keys ≥ key.
359 : //
360 : // Additionally, this prevents loading untruncated range deletions from
361 : // a table which can't possibly contain the target key and is required
362 : // for correctness by mergingIter.SeekGE (see the comment in that
363 : // function).
364 2 : if m.PointKeyBounds.Largest().IsExclusiveSentinel() && l.cmp(m.PointKeyBounds.LargestUserKey(), key) == 0 {
365 2 : m = l.files.Next()
366 2 : continue
367 : }
368 :
369 : // This file contains point keys ≥ `key`. Break and return it.
370 2 : break
371 : }
372 2 : return m
373 : }
374 :
375 2 : func (l *levelIter) findFileLT(key []byte, flags base.SeekLTFlags) *manifest.TableMetadata {
376 2 : // Find the last file whose smallest key is < ikey.
377 2 :
378 2 : // Ordinarily we seek the LevelIterator using SeekLT.
379 2 : //
380 2 : // When lazy combined iteration is enabled, there's a complication. The
381 2 : // level iterator is responsible for watching for files containing range
382 2 : // keys and triggering the switch to combined iteration when such a file is
383 2 : // observed. If a range deletion was observed in a higher level causing the
384 2 : // merging iterator to seek the level to the range deletion's start key, we
385 2 : // need to check whether all of the files between the old position and the
386 2 : // new position contain any range keys.
387 2 : //
388 2 : // In this scenario, we don't seek the LevelIterator and instead we Prev it,
389 2 : // one file at a time, checking each for range keys.
390 2 : prevInsteadOfSeek := flags.RelativeSeek() && l.combinedIterState != nil && !l.combinedIterState.initialized
391 2 :
392 2 : var m *manifest.TableMetadata
393 2 : if prevInsteadOfSeek {
394 2 : m = l.iterFile
395 2 : } else {
396 2 : m = l.files.SeekLT(l.cmp, key)
397 2 : }
398 : // The below loop has a bit of an unusual organization. There are several
399 : // conditions under which we need to Prev to a previous file. If none of
400 : // those conditions are met, the file in `m` is okay to return. The loop
401 : // body is structured with a series of if statements, each of which may
402 : // continue the loop to the previous file. If none of the statements are
403 : // met, the end of the loop body is a break.
404 2 : for m != nil {
405 2 : if m.HasRangeKeys {
406 2 : l.maybeTriggerCombinedIteration(m, -1)
407 2 :
408 2 : // Some files may only contain range keys, which we can skip.
409 2 : // NB: HasPointKeys=true if the file contains any points or range
410 2 : // deletions (which delete points).
411 2 : if !m.HasPointKeys {
412 2 : m = l.files.Prev()
413 2 : continue
414 : }
415 : }
416 :
417 : // This file has point keys.
418 : //
419 : // However, there are a couple reasons why `m` may not be positioned <
420 : // `key` yet:
421 : //
422 : // 1. If SeekLT(key) landed on a file containing range keys, the file
423 : // may contain range keys < `key` but no point keys < `key`.
424 : // 2. When preving instead of seeking, we must check to see whether
425 : // we've preved sufficiently far, or we need to prev again.
426 : //
427 : // If the file does not contain point keys < `key`, prev to continue
428 : // looking for a file that does.
429 2 : if (m.HasRangeKeys || prevInsteadOfSeek) && l.cmp(m.PointKeyBounds.SmallestUserKey(), key) >= 0 {
430 2 : m = l.files.Prev()
431 2 : continue
432 : }
433 :
434 : // This file contains point keys < `key`. Break and return it.
435 2 : break
436 : }
437 2 : return m
438 : }
439 :
440 : // Init the iteration bounds for the current table. Returns -1 if the table
441 : // lies fully before the lower bound, +1 if the table lies fully after the
442 : // upper bound, and 0 if the table overlaps the iteration bounds.
443 2 : func (l *levelIter) initTableBounds(f *manifest.TableMetadata) int {
444 2 : l.tableOpts.LowerBound = l.lower
445 2 : if l.tableOpts.LowerBound != nil {
446 2 : if l.cmp(f.PointKeyBounds.LargestUserKey(), l.tableOpts.LowerBound) < 0 {
447 2 : // The largest key in the sstable is smaller than the lower bound.
448 2 : return -1
449 2 : }
450 2 : if l.cmp(l.tableOpts.LowerBound, f.PointKeyBounds.SmallestUserKey()) <= 0 {
451 2 : // The lower bound is smaller or equal to the smallest key in the
452 2 : // table. Iteration within the table does not need to check the lower
453 2 : // bound.
454 2 : l.tableOpts.LowerBound = nil
455 2 : }
456 : }
457 2 : l.tableOpts.UpperBound = l.upper
458 2 : if l.tableOpts.UpperBound != nil {
459 2 : if l.cmp(f.PointKeyBounds.SmallestUserKey(), l.tableOpts.UpperBound) >= 0 {
460 2 : // The smallest key in the sstable is greater than or equal to the upper
461 2 : // bound.
462 2 : return 1
463 2 : }
464 2 : if l.cmp(l.tableOpts.UpperBound, f.PointKeyBounds.LargestUserKey()) > 0 {
465 2 : // The upper bound is greater than the largest key in the
466 2 : // table. Iteration within the table does not need to check the upper
467 2 : // bound. NB: tableOpts.UpperBound is exclusive and f.PointKeyBounds.Largest() is
468 2 : // inclusive.
469 2 : l.tableOpts.UpperBound = nil
470 2 : }
471 : }
472 2 : return 0
473 : }
474 :
475 : type loadFileReturnIndicator int8
476 :
477 : const (
478 : noFileLoaded loadFileReturnIndicator = iota
479 : fileAlreadyLoaded
480 : newFileLoaded
481 : )
482 :
483 2 : func (l *levelIter) loadFile(file *manifest.TableMetadata, dir int) loadFileReturnIndicator {
484 2 : if l.iterFile == file {
485 2 : if l.err != nil {
486 0 : return noFileLoaded
487 0 : }
488 2 : if l.iter != nil {
489 2 : // We don't bother comparing the file bounds with the iteration bounds when we have
490 2 : // an already open iterator. It is possible that the iter may not be relevant given the
491 2 : // current iteration bounds, but it knows those bounds, so it will enforce them.
492 2 :
493 2 : // There are a few reasons we might not have triggered combined
494 2 : // iteration yet, even though we already had `file` open.
495 2 : // 1. If the bounds changed, we might have previously avoided
496 2 : // switching to combined iteration because the bounds excluded
497 2 : // the range keys contained in this file.
498 2 : // 2. If an existing iterator was reconfigured to iterate over range
499 2 : // keys (eg, using SetOptions), then we wouldn't have triggered
500 2 : // the switch to combined iteration yet.
501 2 : l.maybeTriggerCombinedIteration(file, dir)
502 2 : return fileAlreadyLoaded
503 2 : }
504 : // We were already at file, but don't have an iterator, probably because the file was
505 : // beyond the iteration bounds. It may still be, but it is also possible that the bounds
506 : // have changed. We handle that below.
507 : }
508 :
509 : // Close iter and send a nil iterator through rangeDelIterFn.rangeDelIterFn.
510 2 : if err := l.Close(); err != nil {
511 1 : return noFileLoaded
512 1 : }
513 :
514 2 : for {
515 2 : l.iterFile = file
516 2 : if file == nil {
517 2 : return noFileLoaded
518 2 : }
519 :
520 2 : l.maybeTriggerCombinedIteration(file, dir)
521 2 : if !file.HasPointKeys {
522 2 : switch dir {
523 2 : case +1:
524 2 : file = l.files.Next()
525 2 : continue
526 2 : case -1:
527 2 : file = l.files.Prev()
528 2 : continue
529 : }
530 : }
531 :
532 2 : switch l.initTableBounds(file) {
533 2 : case -1:
534 2 : // The largest key in the sstable is smaller than the lower bound.
535 2 : if dir < 0 {
536 2 : return noFileLoaded
537 2 : }
538 0 : file = l.files.Next()
539 0 : continue
540 2 : case +1:
541 2 : // The smallest key in the sstable is greater than or equal to the upper
542 2 : // bound.
543 2 : if dir > 0 {
544 2 : return noFileLoaded
545 2 : }
546 0 : file = l.files.Prev()
547 0 : continue
548 : }
549 : // If we're in prefix iteration, it's possible this file's smallest
550 : // boundary is large enough to prove the file cannot possibly contain
551 : // any keys within the iteration prefix. Loading the next file is
552 : // unnecessary. This has been observed in practice on slow shared
553 : // storage. See #3575.
554 2 : if l.prefix != nil && l.cmp(l.split.Prefix(file.PointKeyBounds.SmallestUserKey()), l.prefix) > 0 {
555 2 : // Note that because l.iter is nil, a subsequent call to
556 2 : // SeekPrefixGE with TrySeekUsingNext()=true will load the file
557 2 : // (returning newFileLoaded) and disable TrySeekUsingNext before
558 2 : // performing a seek in the file.
559 2 : return noFileLoaded
560 2 : }
561 :
562 2 : iterKinds := iterPointKeys
563 2 : if l.rangeDelIterSetter != nil {
564 2 : iterKinds |= iterRangeDeletions
565 2 : }
566 :
567 2 : var iters iterSet
568 2 : iters, l.err = l.newIters(l.ctx, l.iterFile, &l.tableOpts, l.internalOpts, iterKinds)
569 2 : if l.err != nil {
570 1 : if l.rangeDelIterSetter != nil {
571 1 : l.rangeDelIterSetter.setRangeDelIter(nil)
572 1 : }
573 1 : return noFileLoaded
574 : }
575 2 : l.iter = iters.Point()
576 2 : if l.rangeDelIterSetter != nil && iters.rangeDeletion != nil {
577 2 : // If this file has range deletions, interleave the bounds of the
578 2 : // range deletions among the point keys. When used with a
579 2 : // mergingIter, this ensures we don't move beyond a file with range
580 2 : // deletions until its range deletions are no longer relevant.
581 2 : //
582 2 : // For now, we open a second range deletion iterator. Future work
583 2 : // will avoid the need to open a second range deletion iterator, and
584 2 : // avoid surfacing the file's range deletion iterator via rangeDelIterFn.
585 2 : itersForBounds, err := l.newIters(l.ctx, l.iterFile, &l.tableOpts, l.internalOpts, iterRangeDeletions)
586 2 : if err != nil {
587 1 : l.iter = nil
588 1 : l.err = errors.CombineErrors(err, iters.CloseAll())
589 1 : return noFileLoaded
590 1 : }
591 2 : l.interleaving.Init(l.comparer, l.iter, itersForBounds.RangeDeletion(), keyspan.InterleavingIterOpts{
592 2 : LowerBound: l.tableOpts.LowerBound,
593 2 : UpperBound: l.tableOpts.UpperBound,
594 2 : InterleaveEndKeys: true,
595 2 : })
596 2 : l.iter = &l.interleaving
597 2 :
598 2 : // Relinquish iters.rangeDeletion to the caller.
599 2 : l.rangeDelIterSetter.setRangeDelIter(iters.rangeDeletion)
600 : }
601 2 : return newFileLoaded
602 : }
603 : }
604 :
605 : // In race builds we verify that the keys returned by levelIter lie within
606 : // [lower,upper).
607 2 : func (l *levelIter) verify(kv *base.InternalKV) *base.InternalKV {
608 2 : // Note that invariants.Enabled is a compile time constant, which means the
609 2 : // block of code will be compiled out of normal builds making this method
610 2 : // eligible for inlining. Do not change this to use a variable.
611 2 : if invariants.Enabled && !l.disableInvariants && kv != nil {
612 2 : // We allow returning a boundary key that is outside of the lower/upper
613 2 : // bounds as such keys are always range tombstones which will be skipped
614 2 : // by the Iterator.
615 2 : if l.lower != nil && kv != nil && !kv.K.IsExclusiveSentinel() && l.cmp(kv.K.UserKey, l.lower) < 0 {
616 0 : l.logger.Fatalf("levelIter %s: lower bound violation: %s < %s\n%s", l.layer, kv, l.lower, debug.Stack())
617 0 : }
618 2 : if l.upper != nil && kv != nil && !kv.K.IsExclusiveSentinel() && l.cmp(kv.K.UserKey, l.upper) > 0 {
619 0 : l.logger.Fatalf("levelIter %s: upper bound violation: %s > %s\n%s", l.layer, kv, l.upper, debug.Stack())
620 0 : }
621 : }
622 2 : return kv
623 : }
624 :
625 2 : func (l *levelIter) SeekGE(key []byte, flags base.SeekGEFlags) *base.InternalKV {
626 2 : if invariants.Enabled && l.lower != nil && l.cmp(key, l.lower) < 0 {
627 0 : panic(errors.AssertionFailedf("levelIter SeekGE to key %q violates lower bound %q", key, l.lower))
628 : }
629 :
630 2 : l.err = nil // clear cached iteration error
631 2 : l.exhaustedDir = 0
632 2 : l.prefix = nil
633 2 : // NB: the top-level Iterator has already adjusted key based on
634 2 : // IterOptions.LowerBound.
635 2 : loadFileIndicator := l.loadFile(l.findFileGE(key, flags), +1)
636 2 : if loadFileIndicator == noFileLoaded {
637 2 : l.exhaustedForward()
638 2 : return nil
639 2 : }
640 2 : if loadFileIndicator == newFileLoaded {
641 2 : // File changed, so l.iter has changed, and that iterator is not
642 2 : // positioned appropriately.
643 2 : flags = flags.DisableTrySeekUsingNext()
644 2 : }
645 2 : if kv := l.iter.SeekGE(key, flags); kv != nil {
646 2 : return l.verify(kv)
647 2 : }
648 2 : return l.verify(l.skipEmptyFileForward())
649 : }
650 :
651 2 : func (l *levelIter) SeekPrefixGE(prefix, key []byte, flags base.SeekGEFlags) *base.InternalKV {
652 2 : if invariants.Enabled && l.lower != nil && l.cmp(key, l.lower) < 0 {
653 0 : panic(errors.AssertionFailedf("levelIter SeekGE to key %q violates lower bound %q", key, l.lower))
654 : }
655 2 : l.err = nil // clear cached iteration error
656 2 : l.exhaustedDir = 0
657 2 : l.prefix = prefix
658 2 :
659 2 : // NB: the top-level Iterator has already adjusted key based on
660 2 : // IterOptions.LowerBound.
661 2 : loadFileIndicator := l.loadFile(l.findFileGE(key, flags), +1)
662 2 : if loadFileIndicator == noFileLoaded {
663 2 : l.exhaustedForward()
664 2 : return nil
665 2 : }
666 2 : if loadFileIndicator == newFileLoaded {
667 2 : // File changed, so l.iter has changed, and that iterator is not
668 2 : // positioned appropriately.
669 2 : flags = flags.DisableTrySeekUsingNext()
670 2 : }
671 2 : if kv := l.iter.SeekPrefixGE(prefix, key, flags); kv != nil {
672 2 : return l.verify(kv)
673 2 : }
674 2 : if err := l.iter.Error(); err != nil {
675 1 : return nil
676 1 : }
677 2 : return l.verify(l.skipEmptyFileForward())
678 : }
679 :
680 2 : func (l *levelIter) SeekLT(key []byte, flags base.SeekLTFlags) *base.InternalKV {
681 2 : if invariants.Enabled && l.upper != nil && l.cmp(key, l.upper) > 0 {
682 0 : panic(errors.AssertionFailedf("levelIter SeekLT to key %q violates upper bound %q", key, l.upper))
683 : }
684 :
685 2 : l.err = nil // clear cached iteration error
686 2 : l.exhaustedDir = 0
687 2 : l.prefix = nil
688 2 :
689 2 : // NB: the top-level Iterator has already adjusted key based on
690 2 : // IterOptions.UpperBound.
691 2 : if l.loadFile(l.findFileLT(key, flags), -1) == noFileLoaded {
692 2 : l.exhaustedBackward()
693 2 : return nil
694 2 : }
695 2 : if kv := l.iter.SeekLT(key, flags); kv != nil {
696 2 : return l.verify(kv)
697 2 : }
698 2 : return l.verify(l.skipEmptyFileBackward())
699 : }
700 :
701 2 : func (l *levelIter) First() *base.InternalKV {
702 2 : if invariants.Enabled && l.lower != nil {
703 0 : panic(errors.AssertionFailedf("levelIter First called while lower bound %q is set", l.lower))
704 : }
705 :
706 2 : l.err = nil // clear cached iteration error
707 2 : l.exhaustedDir = 0
708 2 : l.prefix = nil
709 2 :
710 2 : // NB: the top-level Iterator will call SeekGE if IterOptions.LowerBound is
711 2 : // set.
712 2 : if l.loadFile(l.files.First(), +1) == noFileLoaded {
713 2 : l.exhaustedForward()
714 2 : return nil
715 2 : }
716 2 : if kv := l.iter.First(); kv != nil {
717 2 : return l.verify(kv)
718 2 : }
719 2 : return l.verify(l.skipEmptyFileForward())
720 : }
721 :
722 2 : func (l *levelIter) Last() *base.InternalKV {
723 2 : if invariants.Enabled && l.upper != nil {
724 0 : panic(errors.AssertionFailedf("levelIter Last called while upper bound %q is set", l.upper))
725 : }
726 :
727 2 : l.err = nil // clear cached iteration error
728 2 : l.exhaustedDir = 0
729 2 : l.prefix = nil
730 2 :
731 2 : // NB: the top-level Iterator will call SeekLT if IterOptions.UpperBound is
732 2 : // set.
733 2 : if l.loadFile(l.files.Last(), -1) == noFileLoaded {
734 2 : l.exhaustedBackward()
735 2 : return nil
736 2 : }
737 2 : if kv := l.iter.Last(); kv != nil {
738 2 : return l.verify(kv)
739 2 : }
740 2 : return l.verify(l.skipEmptyFileBackward())
741 : }
742 :
743 2 : func (l *levelIter) Next() *base.InternalKV {
744 2 : if l.exhaustedDir == -1 {
745 2 : if l.lower != nil {
746 2 : return l.SeekGE(l.lower, base.SeekGEFlagsNone)
747 2 : }
748 2 : return l.First()
749 : }
750 2 : if l.err != nil || l.iter == nil {
751 1 : return nil
752 1 : }
753 2 : if kv := l.iter.Next(); kv != nil {
754 2 : return l.verify(kv)
755 2 : }
756 2 : return l.verify(l.skipEmptyFileForward())
757 : }
758 :
759 2 : func (l *levelIter) NextPrefix(succKey []byte) *base.InternalKV {
760 2 : if l.err != nil || l.iter == nil {
761 0 : return nil
762 0 : }
763 :
764 2 : if kv := l.iter.NextPrefix(succKey); kv != nil {
765 2 : return l.verify(kv)
766 2 : }
767 2 : if l.iter.Error() != nil {
768 1 : return nil
769 1 : }
770 2 : if l.tableOpts.UpperBound != nil {
771 1 : // The UpperBound was within this file, so don't load the next file.
772 1 : l.exhaustedForward()
773 1 : return nil
774 1 : }
775 :
776 : // Seek the manifest level iterator using TrySeekUsingNext=true and
777 : // RelativeSeek=true so that we take advantage of the knowledge that
778 : // `succKey` can only be contained in later files.
779 2 : metadataSeekFlags := base.SeekGEFlagsNone.EnableTrySeekUsingNext().EnableRelativeSeek()
780 2 : if l.loadFile(l.findFileGE(succKey, metadataSeekFlags), +1) != noFileLoaded {
781 2 : // NB: The SeekGE on the file's iterator must not set TrySeekUsingNext,
782 2 : // because l.iter is unpositioned.
783 2 : if kv := l.iter.SeekGE(succKey, base.SeekGEFlagsNone); kv != nil {
784 2 : return l.verify(kv)
785 2 : }
786 1 : return l.verify(l.skipEmptyFileForward())
787 : }
788 2 : l.exhaustedForward()
789 2 : return nil
790 : }
791 :
792 2 : func (l *levelIter) Prev() *base.InternalKV {
793 2 : if l.exhaustedDir == +1 {
794 2 : if l.upper != nil {
795 2 : return l.SeekLT(l.upper, base.SeekLTFlagsNone)
796 2 : }
797 2 : return l.Last()
798 : }
799 2 : if l.err != nil || l.iter == nil {
800 1 : return nil
801 1 : }
802 2 : if kv := l.iter.Prev(); kv != nil {
803 2 : return l.verify(kv)
804 2 : }
805 2 : return l.verify(l.skipEmptyFileBackward())
806 : }
807 :
808 2 : func (l *levelIter) skipEmptyFileForward() *base.InternalKV {
809 2 : var kv *base.InternalKV
810 2 : // The first iteration of this loop starts with an already exhausted l.iter.
811 2 : // The reason for the exhaustion is either that we iterated to the end of
812 2 : // the sstable, or our iteration was terminated early due to the presence of
813 2 : // an upper-bound or the use of SeekPrefixGE.
814 2 : //
815 2 : // Subsequent iterations will examine consecutive files such that the first
816 2 : // file that does not have an exhausted iterator causes the code to return
817 2 : // that key.
818 2 : for ; kv == nil; kv = l.iter.First() {
819 2 : if l.iter.Error() != nil {
820 1 : return nil
821 1 : }
822 : // If an upper bound is present and the upper bound lies within the
823 : // current sstable, then we will have reached the upper bound rather
824 : // than the end of the sstable.
825 2 : if l.tableOpts.UpperBound != nil {
826 2 : l.exhaustedForward()
827 2 : return nil
828 2 : }
829 :
830 : // If the iterator is in prefix iteration mode, it's possible that we
831 : // are here because bloom filter matching failed. In that case it is
832 : // likely that all keys matching the prefix are wholly within the
833 : // current file and cannot be in a subsequent file. In that case we
834 : // don't want to go to the next file, since loading and seeking in there
835 : // has some cost.
836 : //
837 : // This is not just an optimization. We must not advance to the next
838 : // file if the current file might possibly contain keys relevant to any
839 : // prefix greater than our current iteration prefix. If we did, a
840 : // subsequent SeekPrefixGE with TrySeekUsingNext could mistakenly skip
841 : // the file's relevant keys.
842 2 : if l.prefix != nil {
843 2 : if l.cmp(l.split.Prefix(l.iterFile.PointKeyBounds.LargestUserKey()), l.prefix) > 0 {
844 2 : l.exhaustedForward()
845 2 : return nil
846 2 : }
847 : }
848 :
849 : // Current file was exhausted. Move to the next file.
850 2 : if l.loadFile(l.files.Next(), +1) == noFileLoaded {
851 2 : l.exhaustedForward()
852 2 : return nil
853 2 : }
854 : }
855 2 : return kv
856 : }
857 :
858 2 : func (l *levelIter) skipEmptyFileBackward() *base.InternalKV {
859 2 : var kv *base.InternalKV
860 2 : // The first iteration of this loop starts with an already exhausted
861 2 : // l.iter. The reason for the exhaustion is either that we iterated to the
862 2 : // end of the sstable, or our iteration was terminated early due to the
863 2 : // presence of a lower-bound.
864 2 : //
865 2 : // Subsequent iterations will examine consecutive files such that the first
866 2 : // file that does not have an exhausted iterator causes the code to return
867 2 : // that key.
868 2 : for ; kv == nil; kv = l.iter.Last() {
869 2 : if l.iter.Error() != nil {
870 1 : return nil
871 1 : }
872 : // If a lower bound is present and the lower bound lies within the
873 : // current sstable, then we will have reached the lowerr bound rather
874 : // than the end of the sstable.
875 2 : if l.tableOpts.LowerBound != nil {
876 2 : l.exhaustedBackward()
877 2 : return nil
878 2 : }
879 : // Current file was exhausted. Move to the previous file.
880 2 : if l.loadFile(l.files.Prev(), -1) == noFileLoaded {
881 2 : l.exhaustedBackward()
882 2 : return nil
883 2 : }
884 : }
885 2 : return kv
886 : }
887 :
888 2 : func (l *levelIter) exhaustedForward() {
889 2 : l.exhaustedDir = +1
890 2 : }
891 :
892 2 : func (l *levelIter) exhaustedBackward() {
893 2 : l.exhaustedDir = -1
894 2 : }
895 :
896 2 : func (l *levelIter) Error() error {
897 2 : if l.err != nil || l.iter == nil {
898 2 : return l.err
899 2 : }
900 2 : return l.iter.Error()
901 : }
902 :
903 2 : func (l *levelIter) Close() error {
904 2 : if l.iter != nil {
905 2 : l.err = l.iter.Close()
906 2 : l.iter = nil
907 2 : }
908 2 : if l.rangeDelIterSetter != nil {
909 2 : l.rangeDelIterSetter.setRangeDelIter(nil)
910 2 : }
911 2 : return l.err
912 : }
913 :
914 2 : func (l *levelIter) SetBounds(lower, upper []byte) {
915 2 : l.lower = lower
916 2 : l.upper = upper
917 2 :
918 2 : if l.iter == nil {
919 2 : return
920 2 : }
921 :
922 : // Update tableOpts.{Lower,Upper}Bound in case the new boundaries fall within
923 : // the boundaries of the current table.
924 2 : if l.initTableBounds(l.iterFile) != 0 {
925 2 : // The table does not overlap the bounds. Close() will set levelIter.err if
926 2 : // an error occurs.
927 2 : _ = l.Close()
928 2 : return
929 2 : }
930 :
931 2 : l.iter.SetBounds(l.tableOpts.LowerBound, l.tableOpts.UpperBound)
932 : }
933 :
934 1 : func (l *levelIter) SetContext(ctx context.Context) {
935 1 : l.ctx = ctx
936 1 : if l.iter != nil {
937 0 : // TODO(sumeer): this is losing the ctx = objiotracing.WithLevel(ctx,
938 0 : // manifest.LevelToInt(opts.level)) that happens in table_cache.go.
939 0 : l.iter.SetContext(ctx)
940 0 : }
941 : }
942 :
943 : // DebugTree is part of the InternalIterator interface.
944 0 : func (l *levelIter) DebugTree(tp treeprinter.Node) {
945 0 : n := tp.Childf("%T(%p) %s", l, l, l.String())
946 0 : if l.iter != nil {
947 0 : l.iter.DebugTree(n)
948 0 : }
949 : }
950 :
951 2 : func (l *levelIter) String() string {
952 2 : if l.iterFile != nil {
953 2 : return fmt.Sprintf("%s: fileNum=%s", l.layer, l.iterFile.TableNum.String())
954 2 : }
955 0 : return fmt.Sprintf("%s: fileNum=<nil>", l.layer)
956 : }
957 :
958 : var _ internalIterator = &levelIter{}
|