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