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