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