Skip to content

Skip LevelIterator file boundary sentinels that no range tombstone needs - #15757

Open
zaidoon1 wants to merge 2 commits into
meta:mainfrom
zaidoon1:zaidoon/level-iterator-skip-idle-sentinel
Open

zaidoon1 wants to merge 2 commits into
meta:mainfrom
zaidoon1:zaidoon/level-iterator-skip-idle-sentinel

Conversation

@zaidoon1

@zaidoon1 zaidoon1 commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Background

Since #10449, a LevelIterator that tracks range tombstones doesn't go invalid when the current file runs out of point keys going forward. It returns the file's largest key as a file boundary sentinel instead, and the sentinel does two jobs for MergingIterator. While the sentinel is in the merging iterator's heap, the file's range tombstones stay active and keep covering keys from older levels. When the merging iterator reaches the sentinel, it calls Next(), the level moves on to its next file, and the merging iterator adds that file's range tombstones.

Problem

Often a sentinel has neither job to do. The file has no range tombstones, and the level can't move on because the file is the last in its level, the upper bound ends before the next file, the file iterator stopped mid-file at IterBoundCheck::kOutOfBound, or a prefix seek ran out of its prefix. The merging iterator still pushes the sentinel, pops it and calls Next(), and the level then drops its file iterator. When nothing sorts before the sentinel, all of that happens inside the same Seek(), and a later seek into the same file builds the file's table and index iterators again. When the file's prefix filter ruled the seek out, the empty stand-in that #15477 leaves in the file's place is dropped too, so the next seek into the file goes through TableCache::NewIterator() again instead of checking the filter on the stand-in's table reader. Prefix seeks for absent prefixes reach this on almost every seek.

When another key, such as a memtable key, sorts before the sentinel, the merging iterator doesn't reach it during the seek. The sentinel stays in the heap until the next seek, and the level keeps its file iterator until then.

New behavior

Forward sentinel emission and empty-file skipping are unified in LevelIterator::SkipEmptyFileForward(try_sentinel, keep_file_iter_at_end). A level that runs out of point keys going forward returns a sentinel only when the file has range tombstones or the level can still move on to a next file. Otherwise it goes invalid right away, like a level iterator with ignore_range_deletions already does. Evaluating sentinel eligibility and end-of-level handling in one pass avoids repeating file_iter_.status().ok(), UpperBoundCheckResult(), and KeyReachedUpperBound() checks, and checks cheap inline end-of-level conditions (prefix_exhausted_, last file) before the virtual UpperBoundCheckResult() call or upper-bound comparator comparison. Backward iteration is unchanged.

When Seek() in prefix mode (prefix_same_as_start, implicit prefix seek, or auto_prefix_mode, excluding MultiScan) runs out of keys in a tombstone-free file with no reachable next file, the level keeps file_iter_ (whether a built table iterator or a prefix-filtered stand-in) until the next positioning call or iterator destruction. This applies consistently across non-last files, the last file of a level, single-file levels, and auto_prefix_mode. A later seek into the same file then reuses the file iterator or checks the filter on the stand-in's table reader. Scans (Next(), NextAndGetResult(), SeekToFirst(), total-order seeks, compaction inputs, and MultiScan) still drop the file iterator on natural EOF (while preserving file_iter_ on mid-file kOutOfBound, including across MultiScan ranges in the last file). Files with range tombstones still emit a sentinel and drop the file iterator after the sentinel is consumed, as before.

Iterators return the same keys as before. What changes is how many sentinels the merging iterator handles and how long a prefix seek's level holds its file iterator.

Alternatives considered

  • Skipping the sentinel without keeping the file iterator. The level then dropped its file iterator inside every seek that ran out, including the ones where a sentinel used to stay in the heap and keep it. With keys in the memtable, sorted seeks through one iterator regressed by 11.9% instructions on absent prefixes and 10.1% at 94% absent.
  • Also keeping the file iterator with ignore_range_deletions. Those iterators never had sentinels, so this change leaves them alone. Keeping the file iterator there cut instructions for sorted seeks by 22.5% (empty memtable) and 10.6% (memtable keys), but cost random seeks 4.0% and 1.9% more.
  • Keeping the file iterator whenever a level runs out, in scans and compaction inputs too. A scan or compaction that runs out of a level is usually done with it, and the level would hold the file's table cache handle, index iterator, and readahead buffer until the iterator goes away.
  • Keeping the file iterator for files with range tombstones. By the time such a level runs out, the merging iterator has already used up the file's sentinel. Keeping the file would leave its range tombstone iterator alive as well.

Consequences

  • When a prefix-mode Seek() runs out of keys in a tombstone-free file with no reachable next file, the level holds file_iter_—and its table cache handle (when max_open_files != -1), index iterator/block, and any readahead buffer—until the next positioning call or iterator destruction. (The data block itself is already released by BlockBasedTableIterator::ResetDataIter().) Before this change, the same retention happened whenever another key sorted before the sentinel.
  • When Next() runs off the end of the level's last file or a file whose next file starts past iterate_upper_bound, the level now drops file_iter_ immediately rather than waiting for an unpopped sentinel.
  • Compaction inputs and total-order scans see fewer sentinels and never hold a file iterator longer than before. Tailing iterators don't use LevelIterator.
  • Under DBOptions::prefix_seek_opt_in_only (which forces total_order_seek = true), non-last files still do not set prefix_exhausted_ (left to the follow-up noted in Fix prefix_same_as_start iterator correctness gaps (#15606) #15606), while the last file skips the sentinel and keeps its iterator/stand-in.
  • No option, format, or public API changes. A new sync point, LevelIterator::TrySetDeleteRangeSentinel:Set, lets tests count sentinels.

Test Plan

New and updated unit tests

DBRangeDelSentinelTest (db/db_range_del_test.cc) and DBBloomFilterLevelSeekTest (db/db_bloom_filter_test.cc):

Test Checks
NoSentinelWhenPrefixRunsOutInFile prefix runs out inside the first file (0 sentinels)
NoSentinelWhenLastFileRunsOut seek runs out in the level's last file (0 sentinels)
NoSentinelWhenSingleFileLevelRunsOut seek runs out in a single-file level (0 sentinels)
NoSentinelWhenUpperBoundEndsBeforeNextFile upper bound ends before the next file (0 sentinels)
UpperBoundCheckNotRepeatedAtFileEnd KeyReachedUpperBound() is called once (not twice) at file end when skipping the sentinel
NoSentinelWhenMidFileReachesUpperBound mid-file kOutOfBound stops without a sentinel
TombstoneInFileOutlivesMidFileUpperBound a file's range tombstone still covers an older key when the file iterator stops mid-file at kOutOfBound
NoSentinelWhenMultiScanRangeEndsInFile MultiScan range boundaries emit 0 sentinels and keep the prepared file iterator in both non-last and last files
TombstoneInFileOutlivesPrefixRunningOut a file's range tombstone still covers an older key after the prefix runs out in that file
TombstoneInNextFileAppliesAfterNext a range tombstone in the next file applies after Next()
FilteredSeekInLastFileKeepsStandIn a seek after a filtered seek in the last file checks the filter on the stand-in's table reader
ReseekAfterPrefixRunsOutReusesFileIterator a seek into the same file after a filtered seek reuses a built file iterator in non-last files, last files, and single-file levels
AutoPrefixModeReseekAfterFilterMissReusesFileIterator auto_prefix_mode reuses a built file iterator after a bounded filter miss

Changed existing tests:

  • SentinelKeyCommonCaseTest: forward runs no longer end in a second Key(9) sentinel for L1_2 (last file, no range tombstones).
  • FilteredSeekStandInsAreNotPinned: 100 alternating filtered seeks drop 99 stand-ins (the last goes with the iterator); 0 pinned.
  • PositioningIntoFileOfFilteredSeek: comment updated.

Verification run on the final commit:

  • build_tools/rocksptest.sh db_range_del_test db_bloom_filter_test db_iterator_test merger_test: 496/496 passed.
  • ASSERT_STATUS_CHECKED=1 on DBBloomFilterLevelSeekTest (10/10) and DBRangeDelSentinelTest + SentinelKeyCommonCaseTest (11/11): passed.
  • DEBUG_LEVEL=0 (-fno-rtti) release build of db/version_set.o and static_lib, git clang-format, and make check-sources: clean.
  • Earlier crash tests on the initial commit: db_crashtest.py blackbox for 10 rounds + verification run with range deletes and --test_batches_snapshots=0, no failures.

Benchmark

Release build (DEBUG_LEVEL=0, macOS arm64), prefix_extractor = FixedPrefix(8), Bloom filter 10 bpk, whole_key_filtering = false, max_open_files = -1, 512 MB LRU block cache, fill_cache = false. Instructions per probe measured via proc_pid_rusage (RUSAGE_INFO_V4) comparing main (714026ff3) vs. this PR (e68c70de4c).

35-file L1 (200k prefixes × 4 keys, 200k probes; "Memtable keys" inserts 50k interleaved memtable keys):

Probes Iterator Empty memtable (main → PR) Memtable keys (main → PR)
absent, random reused 3931 → 3785 (-3.7%) 7705 → 7613 (-1.2%)
absent, sorted reused 3928 → 2832 (-27.9%) 6728 → 6661 (-1.0%)
absent, random new per probe 12036 → 11766 (-2.2%) 15685 → 15579 (-0.7%)
94% absent, random reused 5531 → 5376 (-2.8%) 9346 → 9246 (-1.1%)
94% absent, sorted reused 4676 → 3645 (-22.1%) 7557 → 7512 (-0.6%)
94% absent, random new per probe 13568 → 13317 (-1.9%) 17257 → 17161 (-0.6%)
present, bounded scan of 4 keys new per probe, total order 38436 → 38042 (-1.0%) 42730 → 42608 (-0.3%)
absent, random, ignore_range_deletions (control) reused 3559 → 3558 (0.0%) 7388 → 7385 (0.0%)

Single-file L1 (20k prefixes × 4 keys, 100k probes, 94% absent, random, reused, memtable keys): 7855 → 7803 (-0.7%; avoids the 7880 regression from dropping the last file's built iterator).

The largest wins are on sorted reused-iterator prefix seeks with an empty memtable (wall time 210 → 155 ns on absent, 241 → 202 ns on 94% absent). A workload that opens a new iterator per lookup with a populated memtable sees ~0.6–0.7% fewer instructions (within wall-time noise).

When a file iterator runs out of keys going forward, LevelIterator returns
the file's largest key as a sentinel. The sentinel keeps the file's range
tombstones in the merging iterator's heap, and once popped it moves the
level on to the next file so the merging iterator adds that file's range
tombstones. With no range tombstones in the file and no next file to move
to, it only cost a heap push, a pop and a Next() call, so it is now skipped.

A sentinel that the merging iterator never reached also kept the level at
its file until the next seek, so a seek into the same file reused the file
iterator, or the table reader of a prefix-filtered stand-in. A prefix seek
that runs out of keys without a sentinel now keeps the file iterator
itself, in iterators that track range tombstones.
@meta-cla meta-cla Bot added the CLA Signed label Nov 21, 2026
@github-actions

github-actions Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

⚠️ clang-tidy: 3 warning(s) on changed lines

Completed in 1250.5s.

Summary by check

Check Count
concurrency-mt-unsafe 1
cppcoreguidelines-special-member-functions 1
cppcoreguidelines-virtual-class-destructor 1
Total 3

Details

db/db_range_del_test.cc (2 warning(s))
db/db_range_del_test.cc:4375:7: warning: class 'DBRangeDelSentinelTest' defines a non-default destructor but does not define a move constructor or a move assignment operator [cppcoreguidelines-special-member-functions]
db/db_range_del_test.cc:4375:7: warning: destructor of 'DBRangeDelSentinelTest' is protected and virtual [cppcoreguidelines-virtual-class-destructor]
db_stress_tool/db_stress_test_base.cc (1 warning(s))
db_stress_tool/db_stress_test_base.cc:6268:7: warning: function is not thread safe [concurrency-mt-unsafe]

@github-actions

github-actions Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Claude Code Review - OBSOLETE

Superseded by a newer AI review. Expand to see the original review.

✅ Claude Code Review

Auto-triggered after CI passed — reviewing commit e734b88


Summary

Well-crafted performance optimization that skips unnecessary sentinel keys in LevelIterator with thorough benchmarking and testing. The logic is correct and well-scoped.

High-severity findings (0):

No high-severity findings.

Full review (click to expand)

Findings

🟡 MEDIUM

M1. Comment in Seek() still references old sentinel behavior — version_set.cc:1693-1707
  • Issue: The diff updates the first part of this comment to say "If TrySetForwardSentinel() sets no file boundary sentinel key..." but the continuation (lines 1695-1707 original numbering) still discusses only two cases: sentinel is set (merging iterator sees it, calls NextAndGetResult), or no range_tombstone_iter_ (no sentinel at all). The new third case — sentinel skipped but file iterator kept by KeepsFileIteratorAtEnd() — is not discussed. The existing text "this level iterator is !Valid(), so Prev() will not be called" is still correct, but the reader may wonder what happens to the kept file iterator.
  • Root cause: Partial comment update.
  • Suggested fix: Extend the comment to briefly note that when the sentinel is skipped and the file iterator is kept, the LevelIterator is still !Valid() and not in the merging iterator's heap; the kept iterator is cleaned up by the next Seek or by the destructor.

🟢 LOW / NIT

L1. NextFileUnreachable() is not const — version_set.cc
  • Issue: KeepsFileIteratorAtEnd() is marked const but NextFileUnreachable() is not, despite only reading member state. For consistency and to signal no mutation, it should be const.
  • Suggested fix: bool NextFileUnreachable() const {
L2. Backward sentinel path not updated — version_set.cc
  • Issue: SeekToLast, Prev, and SkipEmptyFileBackward still use the old if (range_tombstone_iter_) { TrySetDeleteRangeSentinel(file_smallest_key(...)); } pattern. The same optimization (skip backward sentinel when first file has no tombstones) could apply, but was deliberately excluded. The asymmetry is reasonable for scope but a brief comment at the backward call sites explaining why would help future contributors.
  • Suggested fix: Optional: add a comment at the backward sentinel sites.
L3. Missing single-file level test — db_range_del_test.cc
  • Issue: No test exercises a single-file L1 (file_index_ = 0 and num_files = 1). NoSentinelWhenLastFileRunsOut tests file_index_ = 1 in a two-file level. The logic path is the same (file_index_ >= flevel_->num_files - 1), so this is low priority.
  • Suggested fix: Consider adding a single-file level test.

Cross-Component Analysis

Context Affected? Safe? Notes
Compaction Yes — last file of a level Yes prefix_exhausted_ never set during compaction; sentinel only skipped for tombstone-free last files
MergingIterator forward Yes — LevelIterator may become invalid without sentinel Yes No tombstones to process, no file to transition to
MergingIterator backward No N/A Backward path unchanged
CompactionMergingIterator Yes Yes Assert at line 354 compatible — skipped sentinels correspond to no-tombstone files
ignore_range_deletions No N/A Early return; KeepsFileIteratorAtEnd returns false
WritePreparedTxnDB Yes Yes Sentinel mechanism independent of read_callback
User-defined timestamps Yes Yes KeyReachedUpperBound handles timestamps
DB mutex No N/A LevelIterator doesn't hold mutex_

Positive Observations

  1. Thorough benchmarking with instruction counts across multiple dimensions (random/sorted, reused/new iterator, empty/populated memtable). Sound methodology (interleaved runs, median of 5).

  2. Mutation testing matrix in the PR description showing what breaks when each condition is removed — excellent for safety-critical iterator logic.

  3. Minimal blast radius: entirely within LevelIterator's forward path. No public API, format, or option changes. Two-way door.

  4. Well-designed abstractions: TrySetForwardSentinel(), NextFileUnreachable(), and KeepsFileIteratorAtEnd() are small, descriptive, and cleanly decompose the logic.

  5. Strong test coverage: 5 new sentinel tests + 2 new bloom filter tests covering both positive (sentinel skipped) and negative (sentinel still returned) cases. Existing test modifications are correct.

  6. Crash test evidence: 10 rounds with range deletes and prefix scans, no failures.


ℹ️ About this response

Generated by Claude Code.
Review methodology: claude_md/ci_review_prompt.md

Limitations:

  • Claude may miss context from files not in the diff
  • Large PRs may be truncated
  • Always apply human judgment to AI suggestions

Commands:

  • /claude-review [context] — Request a code review
  • /claude-query <question> — Ask about the PR or codebase

…etention

- Fold TrySetForwardSentinel() into SkipEmptyFileForward(try_sentinel, keep_file_iter_at_end)
  to avoid duplicate UpperBoundCheckResult() virtual calls and KeyReachedUpperBound()
  comparisons on file EOF and filtered seeks, and to check cheap inline conditions
  (prefix_exhausted_, last file) before virtual/comparator calls.
- Retain the built file iterator consistently on empty prefix-mode seeks in the last file,
  single-file levels, and auto_prefix_mode (instead of gating on prefix_exhausted_ alone).
- Add regression tests for last-file/single-file and auto_prefix_mode iterator reuse,
  single-call upper-bound checks, mid-file kOutOfBound (with/without tombstones),
  and MultiScan range boundaries; clean up SyncPoints in ~DBRangeDelSentinelTest().
- Tighten comments and make the release note user-facing.
@github-actions

Copy link
Copy Markdown

✅ Claude Code Review

Auto-triggered after CI passed — reviewing commit e68c70d


Summary

This is a well-designed performance optimization that correctly identifies when file boundary sentinels are unnecessary and when file iterators can be retained for reuse. The change unifies sentinel emission logic into SkipEmptyFileForward(), making the control flow clearer and enabling two optimizations: (1) skipping sentinels when a file has no range tombstones and no next file is reachable, and (2) retaining the file iterator across consecutive prefix seeks into the same file. The sentinel skipping logic correctly preserves both sentinel purposes (keeping range tombstones active and advancing to the next file). Test coverage is thorough and benchmarks show meaningful improvements.

High-severity findings (0):

No high-severity findings.

Full review (click to expand)

Findings

🟡 MEDIUM

M1. keep_file_iter_at_end retains range tombstone iterator pointer without clearing it -- version_set.cc
  • Issue: When keep_file_iter_at_end is true and the level goes invalid (no sentinel, no next file), ClearRangeTombstoneIter() is NOT called. The range_tombstone_iter_ pointer remains pointing to *range_tombstone_iter_ which is null (since has_tombstones is false in this path). This is semantically correct since *range_tombstone_iter_ is already null, but it means the MergingIterator's slot for this level's range tombstone iterator remains allocated (albeit null). If a subsequent Seek() goes to a different file with tombstones, InitFileIterator -> NewFileIterator -> ClearRangeTombstoneIter() is called, which resets *range_tombstone_iter_ before setting the new one. So no leak or stale pointer occurs.
  • Root cause: Intentional design choice -- not a bug. Retaining the tombstone pointer slot without clearing it is correct because *range_tombstone_iter_ is already null. Calling ClearRangeTombstoneIter() would be redundant but would not hurt.
  • Suggested fix: No fix needed. Consider adding an assert or brief comment that *range_tombstone_iter_ is null (via has_tombstones == false) in the keep path, to make this invariant explicit for future readers.
M2. Comment in Seek() references SkipEmptyFileForward() sentinel behavior but could be clearer -- version_set.cc
  • Issue: The updated comment block (around lines 1693-1710 in the new code) now says "If SkipEmptyFileForward() sets no file boundary sentinel key, then since !file_iter_.Valid() from the if condition above, this level iterator is !Valid() (even if file_iter_ is kept for reuse by the next Seek*()), so Prev() will not be called." This is correct but subtly implies that the iterator might appear valid due to the kept file_iter_, which it cannot (since Valid() checks file_iter_.Valid(), not file_iter_.iter() != nullptr).
  • Root cause: The comment is accurate but could be misread.
  • Suggested fix: Minor -- the parenthetical already clarifies. No action required.

🟢 LOW / NIT

L1. Sync point naming -- version_set.cc
  • Issue: The new sync point LevelIterator::TrySetDeleteRangeSentinel:Set is named after the old function TrySetDeleteRangeSentinel but is now called from SetDeleteRangeSentinel. The name still communicates intent (sentinel was set) and test code uses it successfully, but renaming to LevelIterator::SetDeleteRangeSentinel:Set would better match the new function structure.
  • Suggested fix: Consider renaming the sync point to match the new function name, though this is purely cosmetic.
L2. const correctness improvements are welcome -- version_set.cc
  • Issue: file_smallest_key(), file_largest_key(), and KeyReachedUpperBound() are now const. Good cleanup.

Cross-Component Analysis

Context Affected? Analysis
Compaction No Compaction uses kCompaction caller, never sets prefix flags. is_prefix_mode_ is false, keep_file_iter_at_end is false. Sentinel behavior unchanged.
ignore_range_deletions No range_tombstone_iter_ is null. All sentinel branches skipped. keep_file_iter_at_end is false.
MultiScan No scan_opts_ != nullptr forces keep_file_iter_at_end = false. Mid-file kOutOfBound preservation unchanged.
auto_prefix_mode Yes is_prefix_mode_ is true. keep_file_iter_at_end can be true. Tested by AutoPrefixModeReseekAfterFilterMissReusesFileIterator. Correct.
WritePreparedTxnDB No Affects read_callback at higher levels, not LevelIterator sentinel logic.
ReadOnly DB No Same behavior -- read-only operations, sentinel optimization applies equally.
User-defined timestamps No Timestamp handling in prefix_exhausted_ check and KeyReachedUpperBound() unchanged.
prefix_seek_opt_in_only Partial Forces total_order_seek = true. is_prefix_mode_ depends on auto_prefix_mode. PR notes this and defers non-last file prefix_exhausted_ to follow-up (#15606).

Assumption Stress Test

Claim: "A file with no range tombstones and no next file needs neither sentinel purpose."

  1. File has no range tombstones (*range_tombstone_iter_ is null) -- If *range_tombstone_iter_ is non-null but empty (truncation), has_tombstones = true and sentinel is emitted conservatively. No bug.
  2. No next file reachable (last file, prefix exhausted, or upper bound) -- If upper bound changes between seeks (MyRocks), next Seek() clears prefix_exhausted_ and uses new bound. Correct.
  3. MergingIterator doesn't need to advance this level -- When level goes !Valid(), MergingIterator removes it from heap. No tombstone tracking needed. Correct.

Claim: "Retaining file_iter_ at EOF is safe for subsequent Seek() reuse."

  1. Valid() returns false -- Verified: !file_iter_.Valid() && !to_return_sentinel_.
  2. Next Seek() re-seeks the existing iterator via InitFileIterator same-file no-op path (version_set.cc:1992), then file_iter_.Seek(target). Correct.
  3. No resource leak -- ~LevelIterator() or InitFileIterator to different file cleans up.

DB Mutex Analysis

This change does not affect code under the DB mutex. LevelIterator operates during reads on a referenced SuperVersion. File iterator retention only affects TableCache handle and block index iterator lifetime, which are reference-counted and thread-safe.

Positive Observations

  1. Clean refactoring. Moving sentinel-setting into SkipEmptyFileForward() eliminates duplicate condition checks across four call sites.
  2. Principled optimization. Derived from first principles (sentinel's two purposes), not heuristics.
  3. Thorough benchmarking. Instruction-level measurements across 8 workload configurations, including single-file regression check.
  4. Comprehensive test coverage. 13 new/updated tests covering prefix exhaustion, last file, single-file level, upper bound, mid-file stop, tombstone interaction, MultiScan, auto_prefix_mode, and stand-in retention.
  5. Defensive assertions. SetDeleteRangeSentinel() asserts preconditions. TEST_SYNC_POINT enables precise sentinel counting.
  6. Well-documented alternatives. Four rejected approaches with measured results.

ℹ️ About this response

Generated by Claude Code.
Review methodology: claude_md/ci_review_prompt.md

Limitations:

  • Claude may miss context from files not in the diff
  • Large PRs may be truncated
  • Always apply human judgment to AI suggestions

Commands:

  • /claude-review [context] — Request a code review
  • /claude-query <question> — Ask about the PR or codebase

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant