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 1 : ) *levelIter {
132 1 : l := &levelIter{}
133 1 : l.init(ctx, opts, comparer, newIters, files, layer, internalOpts)
134 1 : return l
135 1 : }
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 1 : ) {
146 1 : l.ctx = ctx
147 1 : l.err = nil
148 1 : l.layer = layer
149 1 : l.logger = opts.getLogger()
150 1 : l.prefix = nil
151 1 : l.lower = opts.LowerBound
152 1 : l.upper = opts.UpperBound
153 1 : l.tableOpts.PointKeyFilters = opts.PointKeyFilters
154 1 : if len(opts.PointKeyFilters) == 0 {
155 1 : l.tableOpts.PointKeyFilters = l.filtersBuf[:0:1]
156 1 : }
157 1 : l.tableOpts.UseL6Filters = opts.UseL6Filters
158 1 : l.tableOpts.Category = opts.Category
159 1 : l.tableOpts.layer = l.layer
160 1 : l.tableOpts.snapshotForHideObsoletePoints = opts.snapshotForHideObsoletePoints
161 1 : l.comparer = comparer
162 1 : l.iterFile = nil
163 1 : l.newIters = newIters
164 1 : l.files = files
165 1 : l.exhaustedDir = 0
166 1 : 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 1 : func (l *levelIter) initRangeDel(rangeDelSetter rangeDelIterSetter) {
176 1 : l.rangeDelIterSetter = rangeDelSetter
177 1 : }
178 :
179 1 : func (l *levelIter) initCombinedIterState(state *combinedIterState) {
180 1 : l.combinedIterState = state
181 1 : }
182 :
183 1 : func (l *levelIter) maybeTriggerCombinedIteration(file *manifest.TableMetadata, dir int) {
184 1 : // If we encounter a file that contains range keys, we may need to
185 1 : // trigger a switch to combined range-key and point-key iteration,
186 1 : // if the *pebble.Iterator is configured for it. This switch is done
187 1 : // lazily because range keys are intended to be rare, and
188 1 : // constructing the range-key iterator substantially adds to the
189 1 : // cost of iterator construction and seeking.
190 1 : if file == nil || !file.HasRangeKeys {
191 1 : return
192 1 : }
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 1 : if l.combinedIterState == nil || l.combinedIterState.initialized {
200 1 : return
201 1 : }
202 :
203 1 : if l.upper != nil && l.comparer.Compare(file.RangeKeyBounds.SmallestUserKey(), l.upper) >= 0 {
204 1 : // Range key bounds are above the upper iteration bound.
205 1 : return
206 1 : }
207 1 : if l.lower != nil && l.comparer.Compare(file.RangeKeyBounds.LargestUserKey(), l.lower) <= 0 {
208 1 : // Range key bounds are below the lower iteration bound.
209 1 : return
210 1 : }
211 1 : if props, ok := file.TableBacking.Properties(); ok && props.NumRangeKeySets == 0 {
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 (given that HasRangeKeys=true).
217 1 : return
218 1 : }
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 1 : switch dir {
233 1 : case +1:
234 1 : if !l.combinedIterState.triggered {
235 1 : l.combinedIterState.triggered = true
236 1 : l.combinedIterState.key = file.RangeKeyBounds.SmallestUserKey()
237 1 : } else if l.comparer.Compare(l.combinedIterState.key, file.RangeKeyBounds.SmallestUserKey()) > 0 {
238 1 : l.combinedIterState.key = file.RangeKeyBounds.SmallestUserKey()
239 1 : }
240 1 : case -1:
241 1 : if !l.combinedIterState.triggered {
242 1 : l.combinedIterState.triggered = true
243 1 : l.combinedIterState.key = file.RangeKeyBounds.LargestUserKey()
244 1 : } else if l.comparer.Compare(l.combinedIterState.key, file.RangeKeyBounds.LargestUserKey()) < 0 {
245 1 : l.combinedIterState.key = file.RangeKeyBounds.LargestUserKey()
246 1 : }
247 : }
248 : }
249 :
250 1 : func (l *levelIter) findFileGE(key []byte, flags base.SeekGEFlags) *manifest.TableMetadata {
251 1 : // Find the earliest file whose largest key is >= key.
252 1 :
253 1 : // NB: if flags.TrySeekUsingNext()=true, the levelIter must respect it. If
254 1 : // the levelIter is positioned at the key P, it must return a key ≥ P. If
255 1 : // used within a merging iterator, the merging iterator will depend on the
256 1 : // levelIter only moving forward to maintain heap invariants.
257 1 :
258 1 : // Ordinarily we seek the LevelIterator using SeekGE. In some instances, we
259 1 : // Next instead. In other instances, we try Next-ing first, falling back to
260 1 : // seek:
261 1 : // a) flags.TrySeekUsingNext(): The top-level Iterator knows we're seeking
262 1 : // to a key later than the current iterator position. We don't know how
263 1 : // much later the seek key is, so it's possible there are many sstables
264 1 : // between the current position and the seek key. However in most real-
265 1 : // world use cases, the seek key is likely to be nearby. Rather than
266 1 : // performing a log(N) seek through the table metadata, we next a few
267 1 : // times from our existing location. If we don't find a file whose
268 1 : // largest is >= key within a few nexts, we fall back to seeking.
269 1 : //
270 1 : // Note that in this case, the file returned by findFileGE may be
271 1 : // different than the file returned by a raw binary search (eg, when
272 1 : // TrySeekUsingNext=false). This is possible because the most recent
273 1 : // positioning operation may have already determined that previous
274 1 : // files' keys that are ≥ key are all deleted. This information is
275 1 : // encoded within the iterator's current iterator position and is
276 1 : // unavailable to a fresh binary search.
277 1 : //
278 1 : // b) flags.RelativeSeek(): The merging iterator decided to re-seek this
279 1 : // level according to a range tombstone. When lazy combined iteration
280 1 : // is enabled, the level iterator is responsible for watching for
281 1 : // files containing range keys and triggering the switch to combined
282 1 : // iteration when such a file is observed. If a range deletion was
283 1 : // observed in a higher level causing the merging iterator to seek the
284 1 : // level to the range deletion's end key, we need to check whether all
285 1 : // of the files between the old position and the new position contain
286 1 : // any range keys.
287 1 : //
288 1 : // In this scenario, we don't seek the LevelIterator and instead we
289 1 : // Next it, one file at a time, checking each for range keys. The
290 1 : // merging iterator sets this flag to inform us that we're moving
291 1 : // forward relative to the existing position and that we must examine
292 1 : // each intermediate sstable's metadata for lazy-combined iteration.
293 1 : // In this case, we only Next and never Seek. We set nextsUntilSeek=-1
294 1 : // to signal this intention.
295 1 : //
296 1 : // NB: At most one of flags.RelativeSeek() and flags.TrySeekUsingNext() may
297 1 : // be set, because the merging iterator re-seeks relative seeks with
298 1 : // explicitly only the RelativeSeek flag set.
299 1 : var nextsUntilSeek int
300 1 : var nextInsteadOfSeek bool
301 1 : if flags.TrySeekUsingNext() {
302 1 : nextInsteadOfSeek = true
303 1 : nextsUntilSeek = 4 // arbitrary
304 1 : }
305 1 : if flags.RelativeSeek() && l.combinedIterState != nil && !l.combinedIterState.initialized {
306 1 : nextInsteadOfSeek = true
307 1 : nextsUntilSeek = -1
308 1 : }
309 :
310 1 : var m *manifest.TableMetadata
311 1 : if nextInsteadOfSeek {
312 1 : m = l.iterFile
313 1 : } else {
314 1 : m = l.files.SeekGE(l.comparer.Compare, key)
315 1 : }
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 1 : for m != nil {
323 1 : if m.HasRangeKeys {
324 1 : l.maybeTriggerCombinedIteration(m, +1)
325 1 :
326 1 : // Some files may only contain range keys, which we can skip.
327 1 : // NB: HasPointKeys=true if the file contains any points or range
328 1 : // deletions (which delete points).
329 1 : if !m.HasPointKeys {
330 1 : m = l.files.Next()
331 1 : 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 1 : if (m.HasRangeKeys || nextInsteadOfSeek) && l.comparer.Compare(m.PointKeyBounds.LargestUserKey(), key) < 0 {
348 1 : // If nextInsteadOfSeek is set and nextsUntilSeek is non-negative,
349 1 : // the iterator has been nexting hoping to discover the relevant
350 1 : // file without seeking. It's exhausted the allotted nextsUntilSeek
351 1 : // and should seek to the sought key.
352 1 : if nextInsteadOfSeek && nextsUntilSeek == 0 {
353 0 : nextInsteadOfSeek = false
354 0 : m = l.files.SeekGE(l.comparer.Compare, key)
355 0 : continue
356 1 : } else if nextsUntilSeek > 0 {
357 1 : nextsUntilSeek--
358 1 : }
359 1 : m = l.files.Next()
360 1 : 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 1 : if m.PointKeyBounds.Largest().IsExclusiveSentinel() && l.comparer.Compare(m.PointKeyBounds.LargestUserKey(), key) == 0 {
374 1 : m = l.files.Next()
375 1 : continue
376 : }
377 :
378 : // This file contains point keys ≥ `key`. Break and return it.
379 1 : break
380 : }
381 1 : return m
382 : }
383 :
384 1 : func (l *levelIter) findFileLT(key []byte, flags base.SeekLTFlags) *manifest.TableMetadata {
385 1 : // Find the last file whose smallest key is < ikey.
386 1 :
387 1 : // Ordinarily we seek the LevelIterator using SeekLT.
388 1 : //
389 1 : // When lazy combined iteration is enabled, there's a complication. The
390 1 : // level iterator is responsible for watching for files containing range
391 1 : // keys and triggering the switch to combined iteration when such a file is
392 1 : // observed. If a range deletion was observed in a higher level causing the
393 1 : // merging iterator to seek the level to the range deletion's start key, we
394 1 : // need to check whether all of the files between the old position and the
395 1 : // new position contain any range keys.
396 1 : //
397 1 : // In this scenario, we don't seek the LevelIterator and instead we Prev it,
398 1 : // one file at a time, checking each for range keys.
399 1 : prevInsteadOfSeek := flags.RelativeSeek() && l.combinedIterState != nil && !l.combinedIterState.initialized
400 1 :
401 1 : var m *manifest.TableMetadata
402 1 : if prevInsteadOfSeek {
403 1 : m = l.iterFile
404 1 : } else {
405 1 : m = l.files.SeekLT(l.comparer.Compare, key)
406 1 : }
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 1 : for m != nil {
414 1 : if m.HasRangeKeys {
415 1 : l.maybeTriggerCombinedIteration(m, -1)
416 1 :
417 1 : // Some files may only contain range keys, which we can skip.
418 1 : // NB: HasPointKeys=true if the file contains any points or range
419 1 : // deletions (which delete points).
420 1 : if !m.HasPointKeys {
421 1 : m = l.files.Prev()
422 1 : 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 1 : if (m.HasRangeKeys || prevInsteadOfSeek) && l.comparer.Compare(m.PointKeyBounds.SmallestUserKey(), key) >= 0 {
439 1 : m = l.files.Prev()
440 1 : continue
441 : }
442 :
443 : // This file contains point keys < `key`. Break and return it.
444 1 : break
445 : }
446 1 : 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 1 : func (l *levelIter) initTableBounds(f *manifest.TableMetadata) int {
453 1 : l.tableOpts.LowerBound = l.lower
454 1 : if l.tableOpts.LowerBound != nil {
455 1 : if l.comparer.Compare(f.PointKeyBounds.LargestUserKey(), l.tableOpts.LowerBound) < 0 {
456 1 : // The largest key in the sstable is smaller than the lower bound.
457 1 : return -1
458 1 : }
459 1 : if l.comparer.Compare(l.tableOpts.LowerBound, f.PointKeyBounds.SmallestUserKey()) <= 0 {
460 1 : // The lower bound is smaller or equal to the smallest key in the
461 1 : // table. Iteration within the table does not need to check the lower
462 1 : // bound.
463 1 : l.tableOpts.LowerBound = nil
464 1 : }
465 : }
466 1 : l.tableOpts.UpperBound = l.upper
467 1 : if l.tableOpts.UpperBound != nil {
468 1 : if l.comparer.Compare(f.PointKeyBounds.SmallestUserKey(), l.tableOpts.UpperBound) >= 0 {
469 1 : // The smallest key in the sstable is greater than or equal to the upper
470 1 : // bound.
471 1 : return 1
472 1 : }
473 1 : if l.comparer.Compare(l.tableOpts.UpperBound, f.PointKeyBounds.LargestUserKey()) > 0 {
474 1 : // The upper bound is greater than the largest key in the
475 1 : // table. Iteration within the table does not need to check the upper
476 1 : // bound. NB: tableOpts.UpperBound is exclusive and f.PointKeyBounds.Largest() is
477 1 : // inclusive.
478 1 : l.tableOpts.UpperBound = nil
479 1 : }
480 : }
481 1 : return 0
482 : }
483 :
484 : type loadFileReturnIndicator int8
485 :
486 : const (
487 : noFileLoaded loadFileReturnIndicator = iota
488 : fileAlreadyLoaded
489 : newFileLoaded
490 : )
491 :
492 1 : func (l *levelIter) loadFile(file *manifest.TableMetadata, dir int) loadFileReturnIndicator {
493 1 : if l.iterFile == file {
494 1 : if l.err != nil {
495 0 : return noFileLoaded
496 0 : }
497 1 : if l.iter != nil {
498 1 : // We don't bother comparing the file bounds with the iteration bounds when we have
499 1 : // an already open iterator. It is possible that the iter may not be relevant given the
500 1 : // current iteration bounds, but it knows those bounds, so it will enforce them.
501 1 :
502 1 : // There are a few reasons we might not have triggered combined
503 1 : // iteration yet, even though we already had `file` open.
504 1 : // 1. If the bounds changed, we might have previously avoided
505 1 : // switching to combined iteration because the bounds excluded
506 1 : // the range keys contained in this file.
507 1 : // 2. If an existing iterator was reconfigured to iterate over range
508 1 : // keys (eg, using SetOptions), then we wouldn't have triggered
509 1 : // the switch to combined iteration yet.
510 1 : l.maybeTriggerCombinedIteration(file, dir)
511 1 : return fileAlreadyLoaded
512 1 : }
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 1 : if err := l.Close(); err != nil {
520 1 : return noFileLoaded
521 1 : }
522 :
523 1 : for {
524 1 : l.iterFile = file
525 1 : if file == nil {
526 1 : return noFileLoaded
527 1 : }
528 :
529 1 : l.maybeTriggerCombinedIteration(file, dir)
530 1 : if !file.HasPointKeys {
531 1 : switch dir {
532 1 : case +1:
533 1 : file = l.files.Next()
534 1 : continue
535 1 : case -1:
536 1 : file = l.files.Prev()
537 1 : continue
538 : }
539 : }
540 :
541 1 : switch l.initTableBounds(file) {
542 1 : case -1:
543 1 : // The largest key in the sstable is smaller than the lower bound.
544 1 : if dir < 0 {
545 1 : return noFileLoaded
546 1 : }
547 0 : file = l.files.Next()
548 0 : continue
549 1 : case +1:
550 1 : // The smallest key in the sstable is greater than or equal to the upper
551 1 : // bound.
552 1 : if dir > 0 {
553 1 : return noFileLoaded
554 1 : }
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 1 : if l.prefix != nil && l.comparer.Compare(l.comparer.Split.Prefix(file.PointKeyBounds.SmallestUserKey()), l.prefix) > 0 {
564 1 : // Note that because l.iter is nil, a subsequent call to
565 1 : // SeekPrefixGE with TrySeekUsingNext()=true will load the file
566 1 : // (returning newFileLoaded) and disable TrySeekUsingNext before
567 1 : // performing a seek in the file.
568 1 : return noFileLoaded
569 1 : }
570 :
571 1 : iterKinds := iterPointKeys
572 1 : if l.rangeDelIterSetter != nil {
573 1 : iterKinds |= iterRangeDeletions
574 1 : }
575 :
576 1 : var iters iterSet
577 1 : iters, l.err = l.newIters(l.ctx, l.iterFile, &l.tableOpts, l.internalOpts, iterKinds)
578 1 : if l.err != nil {
579 1 : if l.rangeDelIterSetter != nil {
580 1 : l.rangeDelIterSetter.setRangeDelIter(nil)
581 1 : }
582 1 : return noFileLoaded
583 : }
584 1 : l.iter = iters.Point()
585 1 : if l.rangeDelIterSetter != nil && iters.rangeDeletion != nil {
586 1 : // If this file has range deletions, interleave the bounds of the
587 1 : // range deletions among the point keys. When used with a
588 1 : // mergingIter, this ensures we don't move beyond a file with range
589 1 : // deletions until its range deletions are no longer relevant.
590 1 : //
591 1 : // For now, we open a second range deletion iterator. Future work
592 1 : // will avoid the need to open a second range deletion iterator, and
593 1 : // avoid surfacing the file's range deletion iterator via rangeDelIterFn.
594 1 : itersForBounds, err := l.newIters(l.ctx, l.iterFile, &l.tableOpts, l.internalOpts, iterRangeDeletions)
595 1 : if err != nil {
596 0 : l.iter = nil
597 0 : l.err = errors.CombineErrors(err, iters.CloseAll())
598 0 : return noFileLoaded
599 0 : }
600 1 : l.interleaving.Init(l.comparer, l.iter, itersForBounds.RangeDeletion(), keyspan.InterleavingIterOpts{
601 1 : LowerBound: l.tableOpts.LowerBound,
602 1 : UpperBound: l.tableOpts.UpperBound,
603 1 : InterleaveEndKeys: true,
604 1 : })
605 1 : l.iter = &l.interleaving
606 1 :
607 1 : // Relinquish iters.rangeDeletion to the caller.
608 1 : l.rangeDelIterSetter.setRangeDelIter(iters.rangeDeletion)
609 : }
610 1 : return newFileLoaded
611 : }
612 : }
613 :
614 : // In race builds we verify that the keys returned by levelIter lie within
615 : // [lower,upper).
616 1 : func (l *levelIter) verify(kv *base.InternalKV) *base.InternalKV {
617 1 : // Note that invariants.Enabled is a compile time constant, which means the
618 1 : // block of code will be compiled out of normal builds making this method
619 1 : // eligible for inlining. Do not change this to use a variable.
620 1 : if invariants.Enabled && !l.disableInvariants && kv != nil {
621 1 : // We allow returning a boundary key that is outside of the lower/upper
622 1 : // bounds as such keys are always range tombstones which will be skipped
623 1 : // by the Iterator.
624 1 : 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 1 : 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 1 : return kv
632 : }
633 :
634 1 : func (l *levelIter) SeekGE(key []byte, flags base.SeekGEFlags) *base.InternalKV {
635 1 : 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 1 : l.err = nil // clear cached iteration error
640 1 : l.exhaustedDir = 0
641 1 : l.prefix = nil
642 1 : // NB: the top-level Iterator has already adjusted key based on
643 1 : // IterOptions.LowerBound.
644 1 : loadFileIndicator := l.loadFile(l.findFileGE(key, flags), +1)
645 1 : if loadFileIndicator == noFileLoaded {
646 1 : l.exhaustedForward()
647 1 : return nil
648 1 : }
649 1 : if loadFileIndicator == newFileLoaded {
650 1 : // File changed, so l.iter has changed, and that iterator is not
651 1 : // positioned appropriately.
652 1 : flags = flags.DisableTrySeekUsingNext()
653 1 : }
654 1 : if kv := l.iter.SeekGE(key, flags); kv != nil {
655 1 : return l.verify(kv)
656 1 : }
657 1 : return l.verify(l.skipEmptyFileForward())
658 : }
659 :
660 1 : func (l *levelIter) SeekPrefixGE(prefix, key []byte, flags base.SeekGEFlags) *base.InternalKV {
661 1 : 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 1 : l.err = nil // clear cached iteration error
665 1 : l.exhaustedDir = 0
666 1 : l.prefix = prefix
667 1 :
668 1 : // NB: the top-level Iterator has already adjusted key based on
669 1 : // IterOptions.LowerBound.
670 1 : loadFileIndicator := l.loadFile(l.findFileGE(key, flags), +1)
671 1 : if loadFileIndicator == noFileLoaded {
672 1 : l.exhaustedForward()
673 1 : return nil
674 1 : }
675 1 : if loadFileIndicator == newFileLoaded {
676 1 : // File changed, so l.iter has changed, and that iterator is not
677 1 : // positioned appropriately.
678 1 : flags = flags.DisableTrySeekUsingNext()
679 1 : }
680 1 : if kv := l.iter.SeekPrefixGE(prefix, key, flags); kv != nil {
681 1 : return l.verify(kv)
682 1 : }
683 1 : if err := l.iter.Error(); err != nil {
684 1 : return nil
685 1 : }
686 1 : return l.verify(l.skipEmptyFileForward())
687 : }
688 :
689 1 : func (l *levelIter) SeekLT(key []byte, flags base.SeekLTFlags) *base.InternalKV {
690 1 : 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 1 : l.err = nil // clear cached iteration error
695 1 : l.exhaustedDir = 0
696 1 : l.prefix = nil
697 1 :
698 1 : // NB: the top-level Iterator has already adjusted key based on
699 1 : // IterOptions.UpperBound.
700 1 : if l.loadFile(l.findFileLT(key, flags), -1) == noFileLoaded {
701 1 : l.exhaustedBackward()
702 1 : return nil
703 1 : }
704 1 : if kv := l.iter.SeekLT(key, flags); kv != nil {
705 1 : return l.verify(kv)
706 1 : }
707 1 : return l.verify(l.skipEmptyFileBackward())
708 : }
709 :
710 1 : func (l *levelIter) First() *base.InternalKV {
711 1 : 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 1 : l.err = nil // clear cached iteration error
716 1 : l.exhaustedDir = 0
717 1 : l.prefix = nil
718 1 :
719 1 : // NB: the top-level Iterator will call SeekGE if IterOptions.LowerBound is
720 1 : // set.
721 1 : if l.loadFile(l.files.First(), +1) == noFileLoaded {
722 1 : l.exhaustedForward()
723 1 : return nil
724 1 : }
725 1 : if kv := l.iter.First(); kv != nil {
726 1 : return l.verify(kv)
727 1 : }
728 1 : return l.verify(l.skipEmptyFileForward())
729 : }
730 :
731 1 : func (l *levelIter) Last() *base.InternalKV {
732 1 : 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 1 : l.err = nil // clear cached iteration error
737 1 : l.exhaustedDir = 0
738 1 : l.prefix = nil
739 1 :
740 1 : // NB: the top-level Iterator will call SeekLT if IterOptions.UpperBound is
741 1 : // set.
742 1 : if l.loadFile(l.files.Last(), -1) == noFileLoaded {
743 1 : l.exhaustedBackward()
744 1 : return nil
745 1 : }
746 1 : if kv := l.iter.Last(); kv != nil {
747 1 : return l.verify(kv)
748 1 : }
749 1 : return l.verify(l.skipEmptyFileBackward())
750 : }
751 :
752 1 : func (l *levelIter) Next() *base.InternalKV {
753 1 : if l.exhaustedDir == -1 {
754 1 : if l.lower != nil {
755 1 : return l.SeekGE(l.lower, base.SeekGEFlagsNone)
756 1 : }
757 1 : return l.First()
758 : }
759 1 : if l.err != nil || l.iter == nil {
760 1 : return nil
761 1 : }
762 1 : if kv := l.iter.Next(); kv != nil {
763 1 : return l.verify(kv)
764 1 : }
765 1 : return l.verify(l.skipEmptyFileForward())
766 : }
767 :
768 1 : func (l *levelIter) NextPrefix(succKey []byte) *base.InternalKV {
769 1 : if l.err != nil || l.iter == nil {
770 0 : return nil
771 0 : }
772 :
773 1 : if kv := l.iter.NextPrefix(succKey); kv != nil {
774 1 : return l.verify(kv)
775 1 : }
776 1 : if l.iter.Error() != nil {
777 1 : return nil
778 1 : }
779 1 : if l.tableOpts.UpperBound != nil {
780 0 : // The UpperBound was within this file, so don't load the next file.
781 0 : l.exhaustedForward()
782 0 : return nil
783 0 : }
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 1 : metadataSeekFlags := base.SeekGEFlagsNone.EnableTrySeekUsingNext().EnableRelativeSeek()
789 1 : if l.loadFile(l.findFileGE(succKey, metadataSeekFlags), +1) != noFileLoaded {
790 1 : // NB: The SeekGE on the file's iterator must not set TrySeekUsingNext,
791 1 : // because l.iter is unpositioned.
792 1 : if kv := l.iter.SeekGE(succKey, base.SeekGEFlagsNone); kv != nil {
793 1 : return l.verify(kv)
794 1 : }
795 0 : return l.verify(l.skipEmptyFileForward())
796 : }
797 1 : l.exhaustedForward()
798 1 : return nil
799 : }
800 :
801 1 : func (l *levelIter) Prev() *base.InternalKV {
802 1 : if l.exhaustedDir == +1 {
803 1 : if l.upper != nil {
804 1 : return l.SeekLT(l.upper, base.SeekLTFlagsNone)
805 1 : }
806 1 : return l.Last()
807 : }
808 1 : if l.err != nil || l.iter == nil {
809 1 : return nil
810 1 : }
811 1 : if kv := l.iter.Prev(); kv != nil {
812 1 : return l.verify(kv)
813 1 : }
814 1 : return l.verify(l.skipEmptyFileBackward())
815 : }
816 :
817 1 : func (l *levelIter) skipEmptyFileForward() *base.InternalKV {
818 1 : var kv *base.InternalKV
819 1 : // The first iteration of this loop starts with an already exhausted l.iter.
820 1 : // The reason for the exhaustion is either that we iterated to the end of
821 1 : // the sstable, or our iteration was terminated early due to the presence of
822 1 : // an upper-bound or the use of SeekPrefixGE.
823 1 : //
824 1 : // Subsequent iterations will examine consecutive files such that the first
825 1 : // file that does not have an exhausted iterator causes the code to return
826 1 : // that key.
827 1 : for ; kv == nil; kv = l.iter.First() {
828 1 : 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 1 : if l.tableOpts.UpperBound != nil {
835 1 : l.exhaustedForward()
836 1 : return nil
837 1 : }
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 1 : if l.prefix != nil {
852 1 : if l.comparer.Compare(l.comparer.Split.Prefix(l.iterFile.PointKeyBounds.LargestUserKey()), l.prefix) > 0 {
853 1 : l.exhaustedForward()
854 1 : return nil
855 1 : }
856 : }
857 :
858 : // Current file was exhausted. Move to the next file.
859 1 : if l.loadFile(l.files.Next(), +1) == noFileLoaded {
860 1 : l.exhaustedForward()
861 1 : return nil
862 1 : }
863 : }
864 1 : return kv
865 : }
866 :
867 1 : func (l *levelIter) skipEmptyFileBackward() *base.InternalKV {
868 1 : var kv *base.InternalKV
869 1 : // The first iteration of this loop starts with an already exhausted
870 1 : // l.iter. The reason for the exhaustion is either that we iterated to the
871 1 : // end of the sstable, or our iteration was terminated early due to the
872 1 : // presence of a lower-bound.
873 1 : //
874 1 : // Subsequent iterations will examine consecutive files such that the first
875 1 : // file that does not have an exhausted iterator causes the code to return
876 1 : // that key.
877 1 : for ; kv == nil; kv = l.iter.Last() {
878 1 : 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 1 : if l.tableOpts.LowerBound != nil {
885 1 : l.exhaustedBackward()
886 1 : return nil
887 1 : }
888 : // Current file was exhausted. Move to the previous file.
889 1 : if l.loadFile(l.files.Prev(), -1) == noFileLoaded {
890 1 : l.exhaustedBackward()
891 1 : return nil
892 1 : }
893 : }
894 1 : return kv
895 : }
896 :
897 1 : func (l *levelIter) exhaustedForward() {
898 1 : l.exhaustedDir = +1
899 1 : }
900 :
901 1 : func (l *levelIter) exhaustedBackward() {
902 1 : l.exhaustedDir = -1
903 1 : }
904 :
905 1 : func (l *levelIter) Error() error {
906 1 : if l.err != nil || l.iter == nil {
907 1 : return l.err
908 1 : }
909 1 : return l.iter.Error()
910 : }
911 :
912 1 : func (l *levelIter) Close() error {
913 1 : if l.iter != nil {
914 1 : l.err = l.iter.Close()
915 1 : l.iter = nil
916 1 : }
917 1 : if l.rangeDelIterSetter != nil {
918 1 : l.rangeDelIterSetter.setRangeDelIter(nil)
919 1 : }
920 1 : return l.err
921 : }
922 :
923 1 : func (l *levelIter) SetBounds(lower, upper []byte) {
924 1 : l.lower = lower
925 1 : l.upper = upper
926 1 :
927 1 : if l.iter == nil {
928 1 : return
929 1 : }
930 :
931 : // Update tableOpts.{Lower,Upper}Bound in case the new boundaries fall within
932 : // the boundaries of the current table.
933 1 : if l.initTableBounds(l.iterFile) != 0 {
934 1 : // The table does not overlap the bounds. Close() will set levelIter.err if
935 1 : // an error occurs.
936 1 : _ = l.Close()
937 1 : return
938 1 : }
939 :
940 1 : 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 1 : func (l *levelIter) String() string {
961 1 : if l.iterFile != nil {
962 1 : return fmt.Sprintf("%s: fileNum=%s", l.layer, l.iterFile.TableNum.String())
963 1 : }
964 0 : return fmt.Sprintf("%s: fileNum=<nil>", l.layer)
965 : }
966 :
967 : var _ internalIterator = &levelIter{}
|