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 *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 1 : ) *levelIter {
134 1 : l := &levelIter{}
135 1 : l.init(ctx, opts, comparer, newIters, files, layer, internalOpts)
136 1 : return l
137 1 : }
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 1 : ) {
148 1 : l.ctx = ctx
149 1 : l.err = nil
150 1 : l.layer = layer
151 1 : l.logger = opts.getLogger()
152 1 : l.prefix = nil
153 1 : l.lower = opts.LowerBound
154 1 : l.upper = opts.UpperBound
155 1 : l.tableOpts.PointKeyFilters = opts.PointKeyFilters
156 1 : if len(opts.PointKeyFilters) == 0 {
157 1 : l.tableOpts.PointKeyFilters = l.filtersBuf[:0:1]
158 1 : }
159 1 : l.tableOpts.UseL6Filters = opts.UseL6Filters
160 1 : l.tableOpts.Category = opts.Category
161 1 : l.tableOpts.layer = l.layer
162 1 : l.tableOpts.snapshotForHideObsoletePoints = opts.snapshotForHideObsoletePoints
163 1 : l.comparer = comparer
164 1 : l.cmp = comparer.Compare
165 1 : l.split = comparer.Split
166 1 : l.iterFile = nil
167 1 : l.newIters = newIters
168 1 : l.files = files
169 1 : l.exhaustedDir = 0
170 1 : 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 1 : func (l *levelIter) initRangeDel(rangeDelSetter rangeDelIterSetter) {
180 1 : l.rangeDelIterSetter = rangeDelSetter
181 1 : }
182 :
183 1 : func (l *levelIter) initCombinedIterState(state *combinedIterState) {
184 1 : l.combinedIterState = state
185 1 : }
186 :
187 1 : func (l *levelIter) maybeTriggerCombinedIteration(file *tableMetadata, dir int) {
188 1 : // If we encounter a file that contains range keys, we may need to
189 1 : // trigger a switch to combined range-key and point-key iteration,
190 1 : // if the *pebble.Iterator is configured for it. This switch is done
191 1 : // lazily because range keys are intended to be rare, and
192 1 : // constructing the range-key iterator substantially adds to the
193 1 : // cost of iterator construction and seeking.
194 1 : //
195 1 : // If l.combinedIterState.initialized is already true, either the
196 1 : // iterator is already using combined iteration or the iterator is not
197 1 : // configured to observe range keys. Either way, there's nothing to do.
198 1 : // If false, trigger the switch to combined iteration, using the the
199 1 : // file's bounds to seek the range-key iterator appropriately.
200 1 : //
201 1 : // We only need to trigger combined iteration if the file contains
202 1 : // RangeKeySets: if there are only Unsets and Dels, the user will observe no
203 1 : // range keys regardless. If this file has table stats available, they'll
204 1 : // tell us whether the file has any RangeKeySets. Otherwise, we must
205 1 : // fallback to assuming it does if HasRangeKeys=true.
206 1 : if file != nil && file.HasRangeKeys && l.combinedIterState != nil && !l.combinedIterState.initialized &&
207 1 : (l.upper == nil || l.cmp(file.SmallestRangeKey.UserKey, l.upper) < 0) &&
208 1 : (l.lower == nil || l.cmp(file.LargestRangeKey.UserKey, l.lower) > 0) &&
209 1 : (!file.StatsValid() || file.Stats.NumRangeKeySets > 0) {
210 1 : // The file contains range keys, and we're not using combined iteration yet.
211 1 : // Trigger a switch to combined iteration. It's possible that a switch has
212 1 : // already been triggered if multiple levels encounter files containing
213 1 : // range keys while executing a single mergingIter operation. In this case,
214 1 : // we need to compare the existing key recorded to l.combinedIterState.key,
215 1 : // adjusting it if our key is smaller (forward iteration) or larger
216 1 : // (backward iteration) than the existing key.
217 1 : //
218 1 : // These key comparisons are only required during a single high-level
219 1 : // iterator operation. When the high-level iter op completes,
220 1 : // iinitialized will be true, and future calls to this function will be
221 1 : // no-ops.
222 1 : switch dir {
223 1 : case +1:
224 1 : if !l.combinedIterState.triggered {
225 1 : l.combinedIterState.triggered = true
226 1 : l.combinedIterState.key = file.SmallestRangeKey.UserKey
227 1 : } else if l.cmp(l.combinedIterState.key, file.SmallestRangeKey.UserKey) > 0 {
228 1 : l.combinedIterState.key = file.SmallestRangeKey.UserKey
229 1 : }
230 1 : case -1:
231 1 : if !l.combinedIterState.triggered {
232 1 : l.combinedIterState.triggered = true
233 1 : l.combinedIterState.key = file.LargestRangeKey.UserKey
234 1 : } else if l.cmp(l.combinedIterState.key, file.LargestRangeKey.UserKey) < 0 {
235 1 : l.combinedIterState.key = file.LargestRangeKey.UserKey
236 1 : }
237 : }
238 : }
239 : }
240 :
241 1 : func (l *levelIter) findFileGE(key []byte, flags base.SeekGEFlags) *tableMetadata {
242 1 : // Find the earliest file whose largest key is >= key.
243 1 :
244 1 : // NB: if flags.TrySeekUsingNext()=true, the levelIter must respect it. If
245 1 : // the levelIter is positioned at the key P, it must return a key ≥ P. If
246 1 : // used within a merging iterator, the merging iterator will depend on the
247 1 : // levelIter only moving forward to maintain heap invariants.
248 1 :
249 1 : // Ordinarily we seek the LevelIterator using SeekGE. In some instances, we
250 1 : // Next instead. In other instances, we try Next-ing first, falling back to
251 1 : // seek:
252 1 : // a) flags.TrySeekUsingNext(): The top-level Iterator knows we're seeking
253 1 : // to a key later than the current iterator position. We don't know how
254 1 : // much later the seek key is, so it's possible there are many sstables
255 1 : // between the current position and the seek key. However in most real-
256 1 : // world use cases, the seek key is likely to be nearby. Rather than
257 1 : // performing a log(N) seek through the table metadata, we next a few
258 1 : // times from our existing location. If we don't find a file whose
259 1 : // largest is >= key within a few nexts, we fall back to seeking.
260 1 : //
261 1 : // Note that in this case, the file returned by findFileGE may be
262 1 : // different than the file returned by a raw binary search (eg, when
263 1 : // TrySeekUsingNext=false). This is possible because the most recent
264 1 : // positioning operation may have already determined that previous
265 1 : // files' keys that are ≥ key are all deleted. This information is
266 1 : // encoded within the iterator's current iterator position and is
267 1 : // unavailable to a fresh binary search.
268 1 : //
269 1 : // b) flags.RelativeSeek(): The merging iterator decided to re-seek this
270 1 : // level according to a range tombstone. When lazy combined iteration
271 1 : // is enabled, the level iterator is responsible for watching for
272 1 : // files containing range keys and triggering the switch to combined
273 1 : // iteration when such a file is observed. If a range deletion was
274 1 : // observed in a higher level causing the merging iterator to seek the
275 1 : // level to the range deletion's end key, we need to check whether all
276 1 : // of the files between the old position and the new position contain
277 1 : // any range keys.
278 1 : //
279 1 : // In this scenario, we don't seek the LevelIterator and instead we
280 1 : // Next it, one file at a time, checking each for range keys. The
281 1 : // merging iterator sets this flag to inform us that we're moving
282 1 : // forward relative to the existing position and that we must examine
283 1 : // each intermediate sstable's metadata for lazy-combined iteration.
284 1 : // In this case, we only Next and never Seek. We set nextsUntilSeek=-1
285 1 : // to signal this intention.
286 1 : //
287 1 : // NB: At most one of flags.RelativeSeek() and flags.TrySeekUsingNext() may
288 1 : // be set, because the merging iterator re-seeks relative seeks with
289 1 : // explicitly only the RelativeSeek flag set.
290 1 : var nextsUntilSeek int
291 1 : var nextInsteadOfSeek bool
292 1 : if flags.TrySeekUsingNext() {
293 1 : nextInsteadOfSeek = true
294 1 : nextsUntilSeek = 4 // arbitrary
295 1 : }
296 1 : if flags.RelativeSeek() && l.combinedIterState != nil && !l.combinedIterState.initialized {
297 1 : nextInsteadOfSeek = true
298 1 : nextsUntilSeek = -1
299 1 : }
300 :
301 1 : var m *tableMetadata
302 1 : if nextInsteadOfSeek {
303 1 : m = l.iterFile
304 1 : } else {
305 1 : m = l.files.SeekGE(l.cmp, key)
306 1 : }
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 1 : for m != nil {
314 1 : if m.HasRangeKeys {
315 1 : l.maybeTriggerCombinedIteration(m, +1)
316 1 :
317 1 : // Some files may only contain range keys, which we can skip.
318 1 : // NB: HasPointKeys=true if the file contains any points or range
319 1 : // deletions (which delete points).
320 1 : if !m.HasPointKeys {
321 1 : m = l.files.Next()
322 1 : 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 1 : if (m.HasRangeKeys || nextInsteadOfSeek) && l.cmp(m.LargestPointKey.UserKey, key) < 0 {
339 1 : // If nextInsteadOfSeek is set and nextsUntilSeek is non-negative,
340 1 : // the iterator has been nexting hoping to discover the relevant
341 1 : // file without seeking. It's exhausted the allotted nextsUntilSeek
342 1 : // and should seek to the sought key.
343 1 : if nextInsteadOfSeek && nextsUntilSeek == 0 {
344 1 : nextInsteadOfSeek = false
345 1 : m = l.files.SeekGE(l.cmp, key)
346 1 : continue
347 1 : } else if nextsUntilSeek > 0 {
348 1 : nextsUntilSeek--
349 1 : }
350 1 : m = l.files.Next()
351 1 : 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 1 : if m.LargestPointKey.IsExclusiveSentinel() && l.cmp(m.LargestPointKey.UserKey, key) == 0 {
365 1 : m = l.files.Next()
366 1 : continue
367 : }
368 :
369 : // This file contains point keys ≥ `key`. Break and return it.
370 1 : break
371 : }
372 1 : return m
373 : }
374 :
375 1 : func (l *levelIter) findFileLT(key []byte, flags base.SeekLTFlags) *tableMetadata {
376 1 : // Find the last file whose smallest key is < ikey.
377 1 :
378 1 : // Ordinarily we seek the LevelIterator using SeekLT.
379 1 : //
380 1 : // When lazy combined iteration is enabled, there's a complication. The
381 1 : // level iterator is responsible for watching for files containing range
382 1 : // keys and triggering the switch to combined iteration when such a file is
383 1 : // observed. If a range deletion was observed in a higher level causing the
384 1 : // merging iterator to seek the level to the range deletion's start key, we
385 1 : // need to check whether all of the files between the old position and the
386 1 : // new position contain any range keys.
387 1 : //
388 1 : // In this scenario, we don't seek the LevelIterator and instead we Prev it,
389 1 : // one file at a time, checking each for range keys.
390 1 : prevInsteadOfSeek := flags.RelativeSeek() && l.combinedIterState != nil && !l.combinedIterState.initialized
391 1 :
392 1 : var m *tableMetadata
393 1 : if prevInsteadOfSeek {
394 1 : m = l.iterFile
395 1 : } else {
396 1 : m = l.files.SeekLT(l.cmp, key)
397 1 : }
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 1 : for m != nil {
405 1 : if m.HasRangeKeys {
406 1 : l.maybeTriggerCombinedIteration(m, -1)
407 1 :
408 1 : // Some files may only contain range keys, which we can skip.
409 1 : // NB: HasPointKeys=true if the file contains any points or range
410 1 : // deletions (which delete points).
411 1 : if !m.HasPointKeys {
412 1 : m = l.files.Prev()
413 1 : 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 1 : if (m.HasRangeKeys || prevInsteadOfSeek) && l.cmp(m.SmallestPointKey.UserKey, key) >= 0 {
430 1 : m = l.files.Prev()
431 1 : continue
432 : }
433 :
434 : // This file contains point keys < `key`. Break and return it.
435 1 : break
436 : }
437 1 : 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 1 : func (l *levelIter) initTableBounds(f *tableMetadata) int {
444 1 : l.tableOpts.LowerBound = l.lower
445 1 : if l.tableOpts.LowerBound != nil {
446 1 : if l.cmp(f.LargestPointKey.UserKey, l.tableOpts.LowerBound) < 0 {
447 1 : // The largest key in the sstable is smaller than the lower bound.
448 1 : return -1
449 1 : }
450 1 : if l.cmp(l.tableOpts.LowerBound, f.SmallestPointKey.UserKey) <= 0 {
451 1 : // The lower bound is smaller or equal to the smallest key in the
452 1 : // table. Iteration within the table does not need to check the lower
453 1 : // bound.
454 1 : l.tableOpts.LowerBound = nil
455 1 : }
456 : }
457 1 : l.tableOpts.UpperBound = l.upper
458 1 : if l.tableOpts.UpperBound != nil {
459 1 : if l.cmp(f.SmallestPointKey.UserKey, l.tableOpts.UpperBound) >= 0 {
460 1 : // The smallest key in the sstable is greater than or equal to the upper
461 1 : // bound.
462 1 : return 1
463 1 : }
464 1 : if l.cmp(l.tableOpts.UpperBound, f.LargestPointKey.UserKey) > 0 {
465 1 : // The upper bound is greater than the largest key in the
466 1 : // table. Iteration within the table does not need to check the upper
467 1 : // bound. NB: tableOpts.UpperBound is exclusive and f.LargestPointKey is
468 1 : // inclusive.
469 1 : l.tableOpts.UpperBound = nil
470 1 : }
471 : }
472 1 : return 0
473 : }
474 :
475 : type loadFileReturnIndicator int8
476 :
477 : const (
478 : noFileLoaded loadFileReturnIndicator = iota
479 : fileAlreadyLoaded
480 : newFileLoaded
481 : )
482 :
483 1 : func (l *levelIter) loadFile(file *tableMetadata, dir int) loadFileReturnIndicator {
484 1 : if l.iterFile == file {
485 1 : if l.err != nil {
486 0 : return noFileLoaded
487 0 : }
488 1 : if l.iter != nil {
489 1 : // We don't bother comparing the file bounds with the iteration bounds when we have
490 1 : // an already open iterator. It is possible that the iter may not be relevant given the
491 1 : // current iteration bounds, but it knows those bounds, so it will enforce them.
492 1 :
493 1 : // There are a few reasons we might not have triggered combined
494 1 : // iteration yet, even though we already had `file` open.
495 1 : // 1. If the bounds changed, we might have previously avoided
496 1 : // switching to combined iteration because the bounds excluded
497 1 : // the range keys contained in this file.
498 1 : // 2. If an existing iterator was reconfigured to iterate over range
499 1 : // keys (eg, using SetOptions), then we wouldn't have triggered
500 1 : // the switch to combined iteration yet.
501 1 : l.maybeTriggerCombinedIteration(file, dir)
502 1 : return fileAlreadyLoaded
503 1 : }
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 1 : if err := l.Close(); err != nil {
511 1 : return noFileLoaded
512 1 : }
513 :
514 1 : for {
515 1 : l.iterFile = file
516 1 : if file == nil {
517 1 : return noFileLoaded
518 1 : }
519 :
520 1 : l.maybeTriggerCombinedIteration(file, dir)
521 1 : if !file.HasPointKeys {
522 1 : switch dir {
523 1 : case +1:
524 1 : file = l.files.Next()
525 1 : continue
526 1 : case -1:
527 1 : file = l.files.Prev()
528 1 : continue
529 : }
530 : }
531 :
532 1 : switch l.initTableBounds(file) {
533 1 : case -1:
534 1 : // The largest key in the sstable is smaller than the lower bound.
535 1 : if dir < 0 {
536 1 : return noFileLoaded
537 1 : }
538 0 : file = l.files.Next()
539 0 : continue
540 1 : case +1:
541 1 : // The smallest key in the sstable is greater than or equal to the upper
542 1 : // bound.
543 1 : if dir > 0 {
544 1 : return noFileLoaded
545 1 : }
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 1 : if l.prefix != nil && l.cmp(l.split.Prefix(file.SmallestPointKey.UserKey), l.prefix) > 0 {
555 1 : // Note that because l.iter is nil, a subsequent call to
556 1 : // SeekPrefixGE with TrySeekUsingNext()=true will load the file
557 1 : // (returning newFileLoaded) and disable TrySeekUsingNext before
558 1 : // performing a seek in the file.
559 1 : return noFileLoaded
560 1 : }
561 :
562 1 : iterKinds := iterPointKeys
563 1 : if l.rangeDelIterSetter != nil {
564 1 : iterKinds |= iterRangeDeletions
565 1 : }
566 :
567 1 : var iters iterSet
568 1 : iters, l.err = l.newIters(l.ctx, l.iterFile, &l.tableOpts, l.internalOpts, iterKinds)
569 1 : if l.err != nil {
570 1 : if l.rangeDelIterSetter != nil {
571 1 : l.rangeDelIterSetter.setRangeDelIter(nil)
572 1 : }
573 1 : return noFileLoaded
574 : }
575 1 : l.iter = iters.Point()
576 1 : if l.rangeDelIterSetter != nil && iters.rangeDeletion != nil {
577 1 : // If this file has range deletions, interleave the bounds of the
578 1 : // range deletions among the point keys. When used with a
579 1 : // mergingIter, this ensures we don't move beyond a file with range
580 1 : // deletions until its range deletions are no longer relevant.
581 1 : //
582 1 : // For now, we open a second range deletion iterator. Future work
583 1 : // will avoid the need to open a second range deletion iterator, and
584 1 : // avoid surfacing the file's range deletion iterator via rangeDelIterFn.
585 1 : itersForBounds, err := l.newIters(l.ctx, l.iterFile, &l.tableOpts, l.internalOpts, iterRangeDeletions)
586 1 : if err != nil {
587 1 : l.iter = nil
588 1 : l.err = errors.CombineErrors(err, iters.CloseAll())
589 1 : return noFileLoaded
590 1 : }
591 1 : l.interleaving.Init(l.comparer, l.iter, itersForBounds.RangeDeletion(), keyspan.InterleavingIterOpts{
592 1 : LowerBound: l.tableOpts.LowerBound,
593 1 : UpperBound: l.tableOpts.UpperBound,
594 1 : InterleaveEndKeys: true,
595 1 : })
596 1 : l.iter = &l.interleaving
597 1 :
598 1 : // Relinquish iters.rangeDeletion to the caller.
599 1 : l.rangeDelIterSetter.setRangeDelIter(iters.rangeDeletion)
600 : }
601 1 : return newFileLoaded
602 : }
603 : }
604 :
605 : // In race builds we verify that the keys returned by levelIter lie within
606 : // [lower,upper).
607 1 : func (l *levelIter) verify(kv *base.InternalKV) *base.InternalKV {
608 1 : // Note that invariants.Enabled is a compile time constant, which means the
609 1 : // block of code will be compiled out of normal builds making this method
610 1 : // eligible for inlining. Do not change this to use a variable.
611 1 : if invariants.Enabled && !l.disableInvariants && kv != nil {
612 1 : // We allow returning a boundary key that is outside of the lower/upper
613 1 : // bounds as such keys are always range tombstones which will be skipped
614 1 : // by the Iterator.
615 1 : 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 1 : 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 1 : return kv
623 : }
624 :
625 1 : func (l *levelIter) SeekGE(key []byte, flags base.SeekGEFlags) *base.InternalKV {
626 1 : 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 1 : l.err = nil // clear cached iteration error
631 1 : l.exhaustedDir = 0
632 1 : l.prefix = nil
633 1 : // NB: the top-level Iterator has already adjusted key based on
634 1 : // IterOptions.LowerBound.
635 1 : loadFileIndicator := l.loadFile(l.findFileGE(key, flags), +1)
636 1 : if loadFileIndicator == noFileLoaded {
637 1 : l.exhaustedForward()
638 1 : return nil
639 1 : }
640 1 : if loadFileIndicator == newFileLoaded {
641 1 : // File changed, so l.iter has changed, and that iterator is not
642 1 : // positioned appropriately.
643 1 : flags = flags.DisableTrySeekUsingNext()
644 1 : }
645 1 : if kv := l.iter.SeekGE(key, flags); kv != nil {
646 1 : return l.verify(kv)
647 1 : }
648 1 : return l.verify(l.skipEmptyFileForward())
649 : }
650 :
651 1 : func (l *levelIter) SeekPrefixGE(prefix, key []byte, flags base.SeekGEFlags) *base.InternalKV {
652 1 : 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 1 : l.err = nil // clear cached iteration error
656 1 : l.exhaustedDir = 0
657 1 : l.prefix = prefix
658 1 :
659 1 : // NB: the top-level Iterator has already adjusted key based on
660 1 : // IterOptions.LowerBound.
661 1 : loadFileIndicator := l.loadFile(l.findFileGE(key, flags), +1)
662 1 : if loadFileIndicator == noFileLoaded {
663 1 : l.exhaustedForward()
664 1 : return nil
665 1 : }
666 1 : if loadFileIndicator == newFileLoaded {
667 1 : // File changed, so l.iter has changed, and that iterator is not
668 1 : // positioned appropriately.
669 1 : flags = flags.DisableTrySeekUsingNext()
670 1 : }
671 1 : if kv := l.iter.SeekPrefixGE(prefix, key, flags); kv != nil {
672 1 : return l.verify(kv)
673 1 : }
674 1 : if err := l.iter.Error(); err != nil {
675 1 : return nil
676 1 : }
677 1 : return l.verify(l.skipEmptyFileForward())
678 : }
679 :
680 1 : func (l *levelIter) SeekLT(key []byte, flags base.SeekLTFlags) *base.InternalKV {
681 1 : 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 1 : l.err = nil // clear cached iteration error
686 1 : l.exhaustedDir = 0
687 1 : l.prefix = nil
688 1 :
689 1 : // NB: the top-level Iterator has already adjusted key based on
690 1 : // IterOptions.UpperBound.
691 1 : if l.loadFile(l.findFileLT(key, flags), -1) == noFileLoaded {
692 1 : l.exhaustedBackward()
693 1 : return nil
694 1 : }
695 1 : if kv := l.iter.SeekLT(key, flags); kv != nil {
696 1 : return l.verify(kv)
697 1 : }
698 1 : return l.verify(l.skipEmptyFileBackward())
699 : }
700 :
701 1 : func (l *levelIter) First() *base.InternalKV {
702 1 : 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 1 : l.err = nil // clear cached iteration error
707 1 : l.exhaustedDir = 0
708 1 : l.prefix = nil
709 1 :
710 1 : // NB: the top-level Iterator will call SeekGE if IterOptions.LowerBound is
711 1 : // set.
712 1 : if l.loadFile(l.files.First(), +1) == noFileLoaded {
713 1 : l.exhaustedForward()
714 1 : return nil
715 1 : }
716 1 : if kv := l.iter.First(); kv != nil {
717 1 : return l.verify(kv)
718 1 : }
719 1 : return l.verify(l.skipEmptyFileForward())
720 : }
721 :
722 1 : func (l *levelIter) Last() *base.InternalKV {
723 1 : 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 1 : l.err = nil // clear cached iteration error
728 1 : l.exhaustedDir = 0
729 1 : l.prefix = nil
730 1 :
731 1 : // NB: the top-level Iterator will call SeekLT if IterOptions.UpperBound is
732 1 : // set.
733 1 : if l.loadFile(l.files.Last(), -1) == noFileLoaded {
734 1 : l.exhaustedBackward()
735 1 : return nil
736 1 : }
737 1 : if kv := l.iter.Last(); kv != nil {
738 1 : return l.verify(kv)
739 1 : }
740 1 : return l.verify(l.skipEmptyFileBackward())
741 : }
742 :
743 1 : func (l *levelIter) Next() *base.InternalKV {
744 1 : if l.exhaustedDir == -1 {
745 1 : if l.lower != nil {
746 1 : return l.SeekGE(l.lower, base.SeekGEFlagsNone)
747 1 : }
748 1 : return l.First()
749 : }
750 1 : if l.err != nil || l.iter == nil {
751 1 : return nil
752 1 : }
753 1 : if kv := l.iter.Next(); kv != nil {
754 1 : return l.verify(kv)
755 1 : }
756 1 : return l.verify(l.skipEmptyFileForward())
757 : }
758 :
759 1 : func (l *levelIter) NextPrefix(succKey []byte) *base.InternalKV {
760 1 : if l.err != nil || l.iter == nil {
761 0 : return nil
762 0 : }
763 :
764 1 : if kv := l.iter.NextPrefix(succKey); kv != nil {
765 1 : return l.verify(kv)
766 1 : }
767 1 : if l.iter.Error() != nil {
768 1 : return nil
769 1 : }
770 1 : if l.tableOpts.UpperBound != nil {
771 0 : // The UpperBound was within this file, so don't load the next file.
772 0 : l.exhaustedForward()
773 0 : return nil
774 0 : }
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 1 : metadataSeekFlags := base.SeekGEFlagsNone.EnableTrySeekUsingNext().EnableRelativeSeek()
780 1 : if l.loadFile(l.findFileGE(succKey, metadataSeekFlags), +1) != noFileLoaded {
781 1 : // NB: The SeekGE on the file's iterator must not set TrySeekUsingNext,
782 1 : // because l.iter is unpositioned.
783 1 : if kv := l.iter.SeekGE(succKey, base.SeekGEFlagsNone); kv != nil {
784 1 : return l.verify(kv)
785 1 : }
786 0 : return l.verify(l.skipEmptyFileForward())
787 : }
788 1 : l.exhaustedForward()
789 1 : return nil
790 : }
791 :
792 1 : func (l *levelIter) Prev() *base.InternalKV {
793 1 : if l.exhaustedDir == +1 {
794 1 : if l.upper != nil {
795 1 : return l.SeekLT(l.upper, base.SeekLTFlagsNone)
796 1 : }
797 1 : return l.Last()
798 : }
799 1 : if l.err != nil || l.iter == nil {
800 1 : return nil
801 1 : }
802 1 : if kv := l.iter.Prev(); kv != nil {
803 1 : return l.verify(kv)
804 1 : }
805 1 : return l.verify(l.skipEmptyFileBackward())
806 : }
807 :
808 1 : func (l *levelIter) skipEmptyFileForward() *base.InternalKV {
809 1 : var kv *base.InternalKV
810 1 : // The first iteration of this loop starts with an already exhausted l.iter.
811 1 : // The reason for the exhaustion is either that we iterated to the end of
812 1 : // the sstable, or our iteration was terminated early due to the presence of
813 1 : // an upper-bound or the use of SeekPrefixGE.
814 1 : //
815 1 : // Subsequent iterations will examine consecutive files such that the first
816 1 : // file that does not have an exhausted iterator causes the code to return
817 1 : // that key.
818 1 : for ; kv == nil; kv = l.iter.First() {
819 1 : 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 1 : if l.tableOpts.UpperBound != nil {
826 1 : l.exhaustedForward()
827 1 : return nil
828 1 : }
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 1 : if l.prefix != nil {
843 1 : if l.cmp(l.split.Prefix(l.iterFile.LargestPointKey.UserKey), l.prefix) > 0 {
844 1 : l.exhaustedForward()
845 1 : return nil
846 1 : }
847 : }
848 :
849 : // Current file was exhausted. Move to the next file.
850 1 : if l.loadFile(l.files.Next(), +1) == noFileLoaded {
851 1 : l.exhaustedForward()
852 1 : return nil
853 1 : }
854 : }
855 1 : return kv
856 : }
857 :
858 1 : func (l *levelIter) skipEmptyFileBackward() *base.InternalKV {
859 1 : var kv *base.InternalKV
860 1 : // The first iteration of this loop starts with an already exhausted
861 1 : // l.iter. The reason for the exhaustion is either that we iterated to the
862 1 : // end of the sstable, or our iteration was terminated early due to the
863 1 : // presence of a lower-bound.
864 1 : //
865 1 : // Subsequent iterations will examine consecutive files such that the first
866 1 : // file that does not have an exhausted iterator causes the code to return
867 1 : // that key.
868 1 : for ; kv == nil; kv = l.iter.Last() {
869 1 : 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 1 : if l.tableOpts.LowerBound != nil {
876 1 : l.exhaustedBackward()
877 1 : return nil
878 1 : }
879 : // Current file was exhausted. Move to the previous file.
880 1 : if l.loadFile(l.files.Prev(), -1) == noFileLoaded {
881 1 : l.exhaustedBackward()
882 1 : return nil
883 1 : }
884 : }
885 1 : return kv
886 : }
887 :
888 1 : func (l *levelIter) exhaustedForward() {
889 1 : l.exhaustedDir = +1
890 1 : }
891 :
892 1 : func (l *levelIter) exhaustedBackward() {
893 1 : l.exhaustedDir = -1
894 1 : }
895 :
896 1 : func (l *levelIter) Error() error {
897 1 : if l.err != nil || l.iter == nil {
898 1 : return l.err
899 1 : }
900 1 : return l.iter.Error()
901 : }
902 :
903 1 : func (l *levelIter) Close() error {
904 1 : if l.iter != nil {
905 1 : l.err = l.iter.Close()
906 1 : l.iter = nil
907 1 : }
908 1 : if l.rangeDelIterSetter != nil {
909 1 : l.rangeDelIterSetter.setRangeDelIter(nil)
910 1 : }
911 1 : return l.err
912 : }
913 :
914 1 : func (l *levelIter) SetBounds(lower, upper []byte) {
915 1 : l.lower = lower
916 1 : l.upper = upper
917 1 :
918 1 : if l.iter == nil {
919 1 : return
920 1 : }
921 :
922 : // Update tableOpts.{Lower,Upper}Bound in case the new boundaries fall within
923 : // the boundaries of the current table.
924 1 : if l.initTableBounds(l.iterFile) != 0 {
925 1 : // The table does not overlap the bounds. Close() will set levelIter.err if
926 1 : // an error occurs.
927 1 : _ = l.Close()
928 1 : return
929 1 : }
930 :
931 1 : 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 1 : func (l *levelIter) String() string {
952 1 : if l.iterFile != nil {
953 1 : return fmt.Sprintf("%s: fileNum=%s", l.layer, l.iterFile.FileNum.String())
954 1 : }
955 0 : return fmt.Sprintf("%s: fileNum=<nil>", l.layer)
956 : }
957 :
958 : var _ internalIterator = &levelIter{}
|