Repository navigation
Extend read-path range tombstone conversion over keys dropped by MergingIterator - #15801
Open
xingbowang wants to merge 5 commits into
Open
xingbowang wants to merge 5 commits into
xingbowang wants to merge 5 commits into
Conversation
…eta#15798) Summary: Pull Request resolved: meta#15798 Background: with `min_tombstones_for_range_conversion`, a scan that steps over enough adjacent point tombstones inserts one range tombstone over them into the active memtable, at the scan's read sequence number. Later reads at that sequence number or higher see the range tombstone. A SuperVersion references the memtables and the Version (the list of SST files) of a column family. Reads that pick their own sequence number use one of two orders: - Iterator creation, single column family `MultiGet()`, and a `Refresh()` that rebuilds the iterator reference their SuperVersion first and read the last sequence number after that. This is the pin-first rule: the referenced SuperVersion keeps every key version that a later sequence number can need, so a flush or a compaction cannot drop data that the read needs. - A multi column family read (multi-CF `MultiGet()`, `NewIterators()`) reads one sequence number first and then references the SuperVersions of the group. It retries the whole group if a memtable is newer than that sequence number. A file ingestion publishes the ingested files' sequence number S before it installs the SuperVersion that has the files. So a read can get the old SuperVersion and a sequence number at or above S. If the ingestion does not flush the active memtable, the old and the new SuperVersion share it. Previous behavior: without conversion, such a read sees the state from before the ingestion, which is a consistent view. With conversion, a newer iterator that sees the ingested files can convert a run that a delete in an ingested file completes, at S, into the shared active memtable. The old read then sees that range tombstone, but not the other keys of the ingested file. For example: - An SST file holds `b`. The memtable deletes `a` and `c`, and `d` is live. - An ingested file puts `ax` and deletes `b`, at S. - A read references the old SuperVersion and then reads S. - A newer iterator sees `b` and `c` deleted and converts [`b`, `d`) at S. - The old read sees neither `ax` nor `b`. Before the ingestion, it would see `b`; after it, `ax`. A single-key `Get()` cannot show the problem: the range tombstone hides a key only if the key is deleted at S, so the result is the key's value at S. So `GetImpl()` is not changed, and the fix has four call sites. New behavior: such a read uses the SuperVersion that has the ingested files, so it sees the whole ingestion. Implementation: - `ColumnFamilyData::last_ingest_version_number_` holds the number of the Version that installed the latest successful ingestion, also one that assigns no new sequence number. The ingestion stores it under the DB mutex after `LogAndApply()` and before it publishes its sequence numbers. It is separate from the memtable conversion barrier, which serves scans that try to insert a converted range tombstone. The sequence number store has release ordering and the read's load has acquire ordering, so a read that sees an ingested sequence number also sees this value. - `DBImpl::SuperVersionMissesIngestion()` returns true if the SuperVersion's Version number is older than that value. A read calls it after it has its sequence number. - `DBImpl::ReplaceSuperVersionMissingIngestion()` takes the DB mutex, references the current SuperVersion and releases the old one. The ingestion holds the DB mutex from before it publishes its sequence numbers until it installs its SuperVersion, so the new SuperVersion has every ingestion whose sequence number was published before the call. - After the replacement, the read reads its sequence number again, so the pin-first rule holds for the new SuperVersion. Without this, a write and a flush between the first sequence number and the new reference could drop a key version that the old sequence number needs, and the read would miss a live key. The read repeats the check, because another ingestion can publish its sequence number between the new reference and the new read. Each repeat needs a new ingestion. - The checks that a read runs on its first SuperVersion also run on each new one, with the same errors: a read with `ReadOptions::timestamp` checks it against `full_history_ts_low`, because the new SuperVersion can have files whose older history was already collapsed; an iterator with `ReadOptions::table_filter` checks that conversion is off, because `SetOptions()` can turn it on in between. - Entry points that replace the SuperVersion (pin-first): - `NewIterator()` without a snapshot reads its sequence number in the new `DBImpl::ReadIteratorSequence()`, which runs the loop and the checks and can return an error. `NewIteratorImpl()` then builds the iterator with the sequence number that its caller passes. Its other callers already pass one: the WritePrepared and WriteUnprepared transaction DBs take a snapshot first, and multi column family `NewIterators()` gets its sequence number from `MultiCFSnapshot()`. The sync points `DBImpl::NewIterator:1` to `:4` moved with the sequence number read, so they run only for `NewIterator()` without a snapshot. - The single column family path of `MultiCFSnapshot()` (`MultiGet()`, `MultiGetEntity()`). - `ArenaWrappedDBIter::DoRefresh()`, the `Refresh()` path that rebuilds the iterator. - The multi column family retry loop of `MultiCFSnapshot()` (multi-CF `MultiGet()`, `NewIterators()`, multi-CF iterators) reads one sequence number first, so it does not replace a SuperVersion: it treats a missing ingestion as one more reason to try the whole group again. Its last try holds the DB mutex while it references the SuperVersions. That try now reads the sequence number after it takes the mutex, when the read has no snapshot. Reading it before the mutex left a window in which a flush could drop a version that the sequence number needs. This window existed before this diff, but the extra retries for an ingestion make the last try easier to reach. - Reads with a snapshot that the caller passes skip the check. Such a snapshot already existed when the SuperVersion was referenced, and a snapshot at or above S can be created only after the ingestion installs its SuperVersion. - The in-place path of `Refresh()`, which keeps its iterator tree and only moves the sequence number, needs no check here. It refreshes its memtable range tombstones before it checks the SuperVersion number again, and if it finds range tombstones that its tree has no slot for, it rebuilds the tree at once. A conversion that depends on an ingested file can only happen after the column family installs the ingestion's SuperVersion, so a refresh that sees that conversion also sees the new SuperVersion number and rebuilds. Cost: Each `NewIterator()`, `MultiGet()` and `Refresh()` without a snapshot does two loads (the column family value and the Version number of the SuperVersion) and one compare. The replacement runs only when the compare finds the SuperVersion's Version older than the Version of the latest ingestion, that is, when an ingestion installed its Version after the read referenced its SuperVersion and before the compare. An ingestion that assigns no new sequence number also counts. Each replacement takes the DB mutex once; the loop repeats only for another such ingestion. Releasing the old SuperVersion can take the DB mutex again if that was its last reference. Measured with release db_bench, base vs this change, on an AMD EPYC 9D85 host: a DB of 1M keys (16-byte keys, 100-byte values) after a full compaction, 1 GB block cache, one thread pinned to one CPU, 300,000 operations per run, 3 rounds with the two builds swapped between two CPUs in each round. | Benchmark | Instructions per op, base | Change | Time per op, base | Time per op, this change | |---|---|---|---|---| | seekrandom (a new iterator and one Seek per op) | about 16,600 | +44 to +50 (+0.3%) | 3.05 to 3.18 us | 3.01 to 3.13 us | | multireadrandom (MultiGet of 8 keys) | about 9,900 | within +-3 | 1.89 to 2.07 us | 1.88 to 2.01 us | The time per op does not change beyond the spread between runs. The cause of the extra instructions in seekrandom was not found; moving the retry into a function that is never inlined did not change it. How to read this diff: 1. db/column_family.h: `last_ingest_version_number_` and its accessors; db/db_impl/db_impl.cc `IngestExternalFiles()`, where the ingestion records it before it publishes its sequence numbers. 2. db/db_impl/db_impl.h: the overview at `SuperVersionMissesIngestion()` (the pin-first rule, the problem, the fix), then `ReplaceSuperVersionMissingIngestion()` and `ReadIteratorSequence()`. 3. db/db_impl/db_impl.cc: `NewIterator()` and `ReadIteratorSequence()`, then `MultiCFSnapshot()` (the single column family loop, then the multi column family retry and its last try). 4. db/arena_wrapped_db_iter.cc: `DoRefresh()`. 5. db/db_iterator_test.cc: the `ReadPathRangeTombstoneTest` cases listed in the Test Plan. Changes visible to existing users: the check runs for every user, also with conversion off. An iterator, `MultiGet()` or `Refresh()` that gets a SuperVersion from before an ingestion together with a sequence number from after it now takes the DB mutex, gets the current SuperVersion, reads its sequence number again, and sees the ingested files. Before, it saw the view from before the ingestion. The existing test `IngestedFileSurvivesIteratorWithOlderSuperVersion` (db/db_iterator_test.cc) changes accordingly: its iterator now sees the ingested keys and converts nothing. Differential Revision: D134584125
…ta#15741) Summary: Pull Request resolved: meta#15741 Background: with `min_tombstones_for_range_conversion`, a forward or reverse scan that steps over enough adjacent point tombstones, with no live key between them, adds one range tombstone over the keys it found deleted. The point tombstones stay; the range tombstone is redundant, and later scans use it to seek past the covered keys in older memtables and SST files. The scan inserts the range tombstone into the active memtable at the scan's read sequence number. This is safe only if the scan saw every key in that range that its snapshot includes. With `DBOptions::unordered_write`, a write publishes its sequence number before it inserts its keys into the memtable. An iterator can therefore get a read sequence number at or above a pending write's sequence number while that write's key is still absent from the memtable. Previous behavior: such a scan could convert the point tombstones around the missing key. While the first write was pending, a later write could publish a higher sequence number. An iterator opened at that higher sequence number could miss the pending key, and the converted range tombstone, inserted at the read sequence number, is newer than the pending write. When the write finished, its key was still covered by the range tombstone for every read at the scan's sequence number or higher, also after flush and compaction. This is permanent data loss, not only the relaxed snapshot guarantee that `unordered_write` documents. New behavior: the `DBIter` constructor disables read-path conversion when `unordered_write` is true, next to the existing gates for table filters, read tiers, prefix mode and timestamp visibility. Scans under `unordered_write` never insert converted range tombstones. Implementation: - `db/db_iter.cc`: add `!ioptions.unordered_write` to the condition that sets `min_tombstones_for_range_conversion_`, and explain why in the existing comment. - `include/rocksdb/advanced_options.h`: list `unordered_write` among the configurations where conversion is disabled (comment only). - `unreleased_history/bug_fixes/unordered_write_range_conversion.md`: release note. Safety and unsupported cases: other write modes are not changed. The default write path, pipelined writes, concurrent memtable writes and `two_write_queues` without `unordered_write` publish a sequence number only after the memtable insert finishes, so a scan cannot miss a key that its snapshot includes. WritePrepared and WriteUnprepared transactions keep their existing guard: a scan does not convert when its snapshot is at or above the oldest uncommitted sequence number. Known limitations: conversion is also disabled for a WritePrepared transaction DB that uses `unordered_write` (which requires `two_write_queues`), although the existing guard could make it safe there. A WritePrepared iterator carries `min_uncommitted`, a conservative lower bound on the sequence number of the oldest pending write that the transaction DB tracks, and conversion refuses a scan whose sequence number reaches that bound. This guard covers a pending write only if the write goes through the transaction DB, which registers its sequence number. A write to the base DB under the transaction DB (for example through `GetBaseDB()`) is not registered, so the guard does not cover it. So `unordered_write` turns conversion off for the whole configuration, also for a transaction DB. The lost benefit was not measured. Changes visible to existing users: DBs, including transaction DBs, that set both `unordered_write` and `min_tombstones_for_range_conversion` do not get read-path range tombstones, so their scans over long tombstone runs do not get faster. Differential Revision: D133500312
…5772) Summary: Pull Request resolved: meta#15772 ## Background A queue workload stores items under increasing keys. A consumer reads the oldest items with `Seek(queue start)` and then deletes them. The point tombstones stay in the memtable until flush, so every later scan from the queue start steps over a growing dead prefix. Read-path range tombstone conversion (`min_tombstones_for_range_conversion`) inserts a range tombstone over such a run of tombstones into the active memtable. The merging iterator then seeks the older levels over the run, but it still steps over every covered key of the memtable that holds the range tombstone, one key at a time. For a queue whose dead prefix is in the active memtable, the scan cost therefore still grows with the number of consumed items until the memtable is flushed. ## New behavior A scan that starts with `Seek()` and whose first entries are a run of point tombstones publishes a small record, a head mark, into the active memtable. A mark has two ranges: ``` claimed range [start, end): reserved for the validation walk; writers check it and shorten it usable range [start, usable_end): the part proven deleted at the mark's sequence number; a later seek may skip it start = the scan's seek key end = the end of the run (usually the first live key) S = the mark's sequence number (the publishing scan's) ingest_version = the Version number of the column family's latest ingestion when the mark was published (0 if none) ``` A new mark has an empty usable range (usable_end = start). The scan then checks the claimed range for live entries newer than S (the validation walk, step 3 below) and raises usable_end to the end of the part it checked. A later forward seek can skip to usable_end when three gates hold: its seek key is in the usable range, its sequence number is at least S, and the number of its Version is at least ingest_version. It then seeks that memtable and every older level to usable_end in one step. The Version gate is for a reader whose Version predates an ingestion that a newer scan already saw (see the ingestion paragraphs below). A key between usable_end and end can be live, so a seek never skips past usable_end. A claim is not a proof that its whole range is deleted. A scan proves only the part that it saw deleted at its own sequence number, and usable_end records how far readers may skip. For example, a later scan that stops at the live key "q0015" can raise usable_end to "q0015" and the mark's sequence number, while the claim still ends at "q0020" from the earlier scan. The forward table holds at most kMaxHeadMarks (16) marks. This limit bounds the fixed table and a writer's search; the claims never overlap. Example: a consumer `Seek("q")` at sequence number 100 steps over the tombstones "q0001" to "q0499" and returns "q0500". It publishes the mark ["q", "q0500") at 100. The next `Seek("q")` at 120 seeks to "q0500" at once. There is no new option. Marks are made only when `min_tombstones_for_range_conversion` > 0, and only by forward scans that start with `Seek()`. A new mark needs a run of at least that many tombstones. A scan whose seek was moved by a lowered mark (a writer shortened it, see step 4) may extend that mark with a shorter run, even one tombstone, while the mark is still current: the keys after the lowered end are often covered by an earlier converted range tombstone, which the scan does not count. Ordinary conversion keeps its own threshold, and the converted range tombstone is still inserted as before. ## Algorithm Terms: the claimed range [start, end) is what writers check against; the usable range [start, usable_end) is the part proven deleted at the mark's sequence number, which readers may skip. A live entry is any point entry that is not a deletion. Data model (all in the memtable arena): ``` MemTable::head_marks_ --> HeadMarkTable (immutable) min_start (the start of the first claim) cells[0..n), sorted by start, n <= 16 | v HeadMarkCell (one per claim, never moves) mark --> MemTableHeadMark (immutable) start, end, usable_end, seq, ingest_version, lowered ``` A change to a mark stores a new mark object into the same cell, so republishing the table (when a cell is added or removed) never loses a change. All changes take one mutex per memtable. Replaced marks and old tables stay in the arena until the memtable is freed, so the marks of one memtable have a byte budget: kHeadMarkBaseBudget (64 KB) plus the bytes of the memtable's entries (`data_size_`). Without writes, nothing makes a memtable flush, and repeated ingestions and scans would rebuild the same mark again and again. A new claim, an extension that allocates and a raise are optional, so each first reserves the exact bytes that it will allocate, before it allocates or stores anything. If the reservation does not fit in the budget, it is taken back and that step is refused; reads and conversion keep working. So a memtable without writes keeps its marks within the budget. A writer that lowers a mark counts its bytes without a reservation and is never refused, so a mark never stays wrong; a lowering comes with a write that grows `data_size_`. 64 KB is an estimate that lets a small memtable publish a few hundred marks with short keys before its writes add more budget. 1. Publish. Under the mutex, the scan stores its claim. If a mark E of this memtable moved the scan's seek, the scan can extend E only while the current table still holds that mark object (pointer identity): the claim is [E.start, end), capped at the next claim's start, with usable_end = E.usable_end. If E already claims the run, the claim is E itself and nothing new is stored; the walk then checks only up to the end of the scan's run. If E was replaced or removed, the publish is refused, because the scan skipped keys using the old mark. With no sender mark, the scan adds a new claim with usable_end = start (nothing usable yet), if it overlaps no other nonempty claim and the table has room. 2. Handshake. The scan atomically adds 0 to `num_entries_` (acq_rel). The count does not change, but the add orders the scan against the writers. In a memtable with marks, a write of live entries raises `max_inserted_seq_`, then adds its entry count to `num_entries_` (acq_rel), then checks the claims against its live keys. Concurrent memtable writers do this once per batch in `BatchPostProcess()`. The two adds are ordered: either the scan's validation walk sees the writer's entry, or the writer sees the claim. 3. Validation walk. If `max_inserted_seq_` > S, the scan walks the memtable's entries in [usable_end, end), or in [usable_end, end of its run) if the claim is E itself, because the scan saw only that part dead. It stops at the first live entry with a sequence number above S (at most 16384 entries). Then, if the walk got past usable_end, the memtable is still mutable, and the cell still holds its claim, it raises usable_end to the end of the checked part. The raise allocates the new mark before it takes the mutex. Allocation: a new claim allocates its keys, its cell and a new table; an extension that grows the claim allocates a new mark; a raise allocates a new mark. When the claim is E itself, nothing is allocated unless the walk gets past usable_end, so a reader at an old snapshot that repeats the same seek, and whose walk stops at the same newer entry each time, allocates nothing. 4. Write path. A live entry whose key falls in a claimed range lowers the mark to end at that key before the write's sequence number is published. Deletions never change a mark. A key outside the hull (from the first claim's start to the last claim's end) costs one or two key compares; only a key inside a claim takes the mutex. Concurrent memtable writers check their batch in `BatchPostProcess()`: each live key of a batch with at most 8 live keys, or the range [smallest, largest live key] of a larger batch. 5. Read path. `MergingIterator::SeekImpl()`, only for the seek of a DBIter user scan: before it seeks memtable level i, if a usable mark of that memtable with seq <= the read sequence number contains the current seek key, the seek key becomes the mark's usable end for level i and every older level, like the existing cascading seek over range tombstones. The reader also needs mark.ingest_version <= the number of its own Version (see the ingestion paragraph below). Why this is correct: a usable range holds only keys that a scan saw deleted at the mark's sequence number S: the scan's own run, checked by its validation walk up to usable_end. The older levels hold no entry newer than S, because a mark requires S >= the memtable's earliest sequence number (the same rule as conversion). Newer entries in the memtable are found by the walk or lower the mark (step 2). Extension is safe because every writer after E would have lowered E, which breaks the identity check. File ingestion is the one way to add older-level keys at any sequence number. While the ingestion holds the column family's `ingest_sst_lock` as a reader, it clears the marks of every memtable of the column family before it installs its Version, then records that Version's number and the ingested sequence number. Publishing takes `ingest_sst_lock` with a try-lock (as conversion does) and refuses a scan whose Version predates the latest ingestion, or whose sequence number is below the ingested one. The clear runs under the DB mutex and stores a null mark table into each memtable without taking the mark mutex. It skips the memtables if no active memtable of the column family ever had marks enabled. While the ingestion holds `ingest_sst_lock`, no scan can store a claim, so no other thread publishes a table. A raise or a writer's lowering can still run, but each stores only into a cell of the table that it loaded, which no reader can reach after the clear. So the clear never waits for the mark mutex, whose holder can be a lowering that allocates. `DeleteFilesInRanges()` (and so `DeleteFilesInRange()` and `ClipColumnFamily()`) can remove an SST file whose range tombstone hides an older key in a lower level. The key then becomes visible again, with its old sequence number, but no memtable write lowered a mark over it. For example, an L2 file holds "q0" and an L1 file holds the range tombstone ["q", "q1"). A scan from `Seek("q")` publishes a mark that starts at "q"; deleting the L1 file makes "q0" visible, and the mark would skip it. So `DeleteFilesInRanges()` takes the same steps as an ingestion, in the same order: it takes `ingest_sst_lock` as a reader before the DB mutex, clears the marks before `LogAndApply()`, records the new Version's number (the recorded sequence number does not change), installs the new SuperVersion and then releases the lock. Other ways that remove SST files keep every key that those files hide, or delete it too: compaction drops a tombstone only with the keys below it, trivial moves, `ReFitLevel()`, `PromoteL0()` and temperature changes move or copy whole files. FIFO compaction deletes old files without `ingest_sst_lock`, so marks are off with FIFO compaction. An iterator references its Version before it reads its sequence number, so it can read at or above an ingested sequence number with a Version that does not have the ingested files. Publishing refuses such a scan, because its Version number is below the recorded one. A mark that a newer scan publishes must not move such a reader's seeks either, because the reader may still see a key that an ingested file deletes. So every mark keeps the recorded Version number of the latest ingestion at its publish (`ingest_version`), and a reader uses the mark only if its own Version number is at least that. Lowering, extension and raise keep the value, because any later ingestion clears the mark. The base fix two diffs below ("Fix partial ingestion view with read-path range tombstone conversion") gives the current SuperVersion to an iterator, a `MultiGet()` and a `Refresh()` that rebuilds its iterator tree, if they read in that window. Only an in-place `Iterator::Refresh()`, which keeps its iterator tree and moves only its sequence number, can still pair an old Version with a newer sequence number, and this check covers it. A Version number also grows with every flush and compaction, so the reader's Version need not be the publisher's. ## Safety boundaries and unsupported cases - Readers use marks only without a read callback, user-defined timestamps, `table_filter`, or `ignore_range_deletions`, and only in total order or `prefix_same_as_start` scans. A reader ignores a mark if its sequence number is below the mark's S, or if its Version number is below the mark's `ingest_version`. - Marks are off for user-defined timestamps, `inplace_update_support`, `unordered_write`, `two_write_queues`, FIFO compaction (its deletion compaction removes files without `ingest_sst_lock`, so it cannot clear the marks), memtables that are not skip lists, MultiScan, and read-only, secondary and follower instances (they have no active memtable to publish into). - With marks on, every memtable insert does an acq_rel increment of `num_entries_` instead of a relaxed one (the same instruction on x86). ## Cost when the feature is off With `min_tombstones_for_range_conversion` = 0, a new memtable has marks disabled, so no mark is ever published into it. These checks still run, and no arena or heap allocation is added: - Write: each memtable insert loads the memtable's `head_marks_enabled_` flag and branches on it, twice on the serial write path and once on the concurrent path; `BatchPostProcess()` branches on it once per batch. The entry counter stays a relaxed increment. - Iterator build: one virtual `HeadMarksEnabled()` call per memtable (the active one and each immutable one). The merging iterator registers no memtable; its new list has inline room for 4 entries, so it does not allocate. - Seek: an eligible `DBIter` seek goes through the virtual `SeekWithHeadMarks()`, which finds the registered list empty and does the normal seek. `SeekImpl()` tests one more flag per level. When no level has range tombstones and the seek uses no head marks (no registered memtable, or a reseek), a child that returns TryAgain (async read) is sought again at the seek target directly, as without the feature. Otherwise each such child is recorded with its seek key, which is copied only if a range tombstone or a mark moved it. - File ingestion and `DeleteFilesInRanges()`: under the DB mutex, `ClearHeadMarks()` returns after one flag check, and `RecordFileChangeForHeadMarks()` does two compares and stores per column family. `DeleteFilesInRanges()` also takes `ingest_sst_lock` as a reader, so a scan's publish or conversion that runs at the same time is refused (its try-lock fails); nothing waits for it. - Memory: each memtable has a few new fields (a mutex, a table pointer, the flag, `max_inserted_seq_` and the mark byte counter); each column family has the ingestion state and one flag. Marks published while the option was on stay usable after it is turned off, until their memtable is freed. The Test Plan has a Put instruction count with the threshold at 0. ## Known limitations - A compaction filter that returns `kRemoveAndSkipUntil` drops every entry that it skips, also a point tombstone, with no new sequence number. An older value of that key in a level below the compaction then becomes visible again. Compaction does not clear the marks, so after such a skip a scan that uses a mark can miss a key that `Get()` returns, and a range tombstone that the scan converts can then hide it from `Get()` too. `kRemove` (which writes a deletion), `kPurge` (a SingleDelete of a live key) and `kChangeValue` never drop a tombstone, so they do not have this effect. Marks stay on with compaction filters. A later fix can clear and record the marks when a compaction that ran a skip installs its result, as `DeleteFilesInRanges()` does. - Only dead runs right after a forward `Seek()` get a mark. Reverse scans, runs in the middle of a scan, and consumers that start after the dead prefix get no benefit. - Marks live only in memtables; SST files rely on the converted range tombstones. - Extending a mark raises its S, so readers between the old and the new S lose the mark (slower, still correct). - When a publish is refused (overlap, full table, byte budget, or the try-lock is busy), ordinary conversion still runs with its own checks, including its own try-lock. A converted range tombstone hides the older point tombstones that it covers from later scans, so they stop counting toward a new mark: the queue gets a new mark only after a new run of `min_tombstones_for_range_conversion` deletions. - Any ingestion into the column family, and any `DeleteFilesInRanges()` call that deletes a file, clears all marks of its memtables, even when the files do not overlap them. - The converted range tombstones of the base feature are not changed. If `DeleteFilesInRanges()` makes an older key visible again inside a range that a scan already converted, the converted range tombstone, newer than the key, still hides it. `Get()` and scans agree on this. Marks add no new case: a mark that is still in the table after the deletion was published after it. - Two limits: at most kMaxHeadMarks (16) current marks per memtable, and the byte budget for new claims, extensions that allocate, and raises. A writer's lowering can go over the budget, and its bytes count toward the flush trigger. - Replaced marks and old tables stay in the memtable arena until the memtable is freed. Their bytes count toward the memtable's memory, the flush trigger and the write buffer manager, but the flush trigger is checked only on a write. Without writes, nothing flushes the memtable, and only the byte budget (64 KB plus the memtable's entry bytes) limits the mark bytes. Once the budget is used up, the memtable gets no new marks and no raises until writes add budget or the memtable is replaced. - A concurrent write batch with more than 8 live keys lowers every mark between its smallest and largest live key, even if none of its keys is inside the mark. - With only the active memtable and no range tombstone or SST file, the merging iterator is not built (the single memtable iterator is used), so marks are not used. The first conversion adds a range tombstone, which brings the merging iterator back. ## How to read this diff 1. `db/memtable.h`: the "Head marks" overview comment, then `MemTableHeadMark`, `HeadMarkIngestState` and the `ReadOnlyMemTable` head mark methods. 2. `db/memtable.cc`: `PublishHeadMark()` and its helpers, then the write path in `MemTable::Add()`, `HeadMarkBatchPostProcess()`, `LowerHeadMarkForKey()` (in `db/memtable.h`) and `LowerHeadMarks()`. 3. `table/internal_iterator.h`, `table/merging_iterator.{h,cc}`: `SeekWithHeadMarks()` and `SeekOverHeadMark()` in the cascading seek, and `MergeIteratorBuilder::SetHeadMarkMemTable()`. 4. `db/db_iter.{h,cc}`: the use and publish gates, `SeekInnerIterWithHeadMarks()` and `MaybePublishHeadMark()`. 5. `db/column_family.{h,cc}`, `db/memtable_list.h`, `db/db_impl/db_impl.cc`: the ingestion steps and memtable registration. 6. Tests: `db/db_range_del_test.cc` (`DBHeadMarkTest`), `db/db_memtable_test.cc` and `table/merger_test.cc`. Differential Revision: D134004281
Summary:
## Background
The previous diff in this stack adds head marks: a scan that starts with
`Seek()` on a run of point tombstones records the dead range in the active
memtable, so later scans from the same key skip it in one seek (see the "Head
marks" comment in `db/memtable.h`). Some queues are consumed from the largest
key with `SeekForPrev()`, or with `SeekToLast()` and `iterate_upper_bound`.
Those scans step backward over the same kind of dead range and get no mark.
## New behavior
A scan that starts with `SeekForPrev(t)`, or with `SeekToLast()` when
`iterate_upper_bound` is set, and whose first entries are a run of point
tombstones, tries to publish a reverse mark. The range that it offers to
claim is:
```
SeekForPrev(t), t below iterate_upper_bound U (or no U):
(K, t]
SeekToLast() with U, or SeekForPrev(t) with t at or above U:
(K, U)
K = the key where the backward scan stopped (usually the first live key)
```
Every key in the offered range is deleted at the scan's sequence number. The
publish can refuse or cap the range, and an extension can keep a longer
existing claim. A new claim is not usable at first. The validation walk then
makes it usable down to its usable end, which the usable range excludes: K if
the walk checks the whole claim, or a higher key if the walk stops at a newer
live entry or at the walk cap. A later seek that uses the mark goes to the
last entry at or before the usable end.
If a `prefix_same_as_start` scan stops at a key outside its prefix, K is the
lowest tombstone of the run instead. The scan did not see every key between
that outside key and the run, because the prefix filter of an SST can skip the
seek, so a live key of another prefix in that SST was never read.
A later reverse seek uses the marks as it visits each memtable: it checks its
current target against the usable reverse marks of that memtable. When a
mark applies, the target moves to the mark's usable end, so that memtable and
every older level are positioned at the last entry at or before it, in one
step; an older memtable's mark can move it again. A newer level's range
tombstone can also move the target, to the tombstone's start with that key
excluded. An older mark whose exclusive start is that key can then apply. `SeekToLast()`
with an upper bound works like `SeekForPrev()` at that bound. Without an upper
bound, `SeekToLast()` neither uses nor publishes marks. The conditions, the
threshold (`min_tombstones_for_range_conversion`), the Version check of a
reader after an ingestion, and the unsupported configurations are the same as
for forward marks.
## Algorithm
A reverse mark is a forward mark in descending key order: (K, t] becomes the
claim [t, K) in that order. Each direction has its own mark table
(`MemTable::head_marks_[HeadMarkDirection]`), and every table helper takes
the direction and compares keys in its order (`HeadMarkOrder`). So the
publish steps, the handshake, the writer lowering, the extension and the
ingestion rules of forward marks hold for reverse marks without new protocol
code. The differences:
- A seek clamped to `iterate_upper_bound` U does not claim U: `SeekToLast()`
with an upper bound, and `SeekForPrev()` at or above U.
`MemTableHeadMark::start_exclusive` records this, and an extension keeps the
sender's start and flag. A seek that includes U, such as `SeekForPrev(U)` on
an iterator without that upper bound, does not use such a mark, and a write
of U does not lower it.
- The validation walk goes down from the usable end with the memtable's
reverse iterator.
- The reader hook is `MergingIterator::SeekForPrevImpl()`. The new seek key
for a level and the older levels is (usable end, 0,
`kValueTypeForSeekForPrev`), the last entry at or before the usable end. A
reverse mark can move a child's seek key even when no level has range
tombstones. So with `async_io`, when a range tombstone, or a mark of a
registered memtable in this seek, can move the key, a child that returns
TryAgain is sought again at the key it was first sought to, as in
`SeekImpl()`. Otherwise it is sought again at the original target, as
without marks.
- Every live write checks both tables.
Reverse conversion clip. A reverse run's converted range tombstone ends at the
seek target (t, or U for `SeekToLast()`), and starts at the lowest tombstone
of the run. In a queue consumed from the largest key, every scan's range
therefore contains the ranges of all earlier scans. The tombstones nest, each
fragment of the memtable's range tombstone list carries one more seqno per
scan, and every new iterator re-fragments the growing lists. The clip
applies only to the first run after a reverse seek that a reverse mark E of
the active memtable moved. For that run,
`DBIter::MaybeInsertRangeTombstone()` finds the first range tombstone fragment
of the active memtable that starts at or above E's usable end. If that start
is below the original upper end of the range, the range ends there instead;
otherwise the range keeps its original upper end. The start is usually the
start of the range that the previous scan inserted. A fragment that starts
below E's usable end is skipped: clipping at such a fragment could end the
new range inside the part that this scan checked itself. The example below
is the test `ConversionIsClippedAtMark`, in user-key order: "[" and "]"
include an end, "(" and ")" exclude it.
```
keys: q0006 ... q0009 q0010 ... q0018 q0019
first scan, SeekForPrev("q0019"), stops at live q0009:
mark E = ("q0009", "q0019"], usable down to q0009
inserted [q0010 ......... q0019)
q0006 .. q0009 are deleted; the next scan is moved by E to q0009 and
stops at live q0005:
run [q0006 ... q0009]
^ E.usable_end = q0009
first fragment start >= q0009 is q0010, so it converts
[q0006 ......... q0010) instead of [q0006, q0019)
```
If a late put shortens the mark to "q0015" and that key is then deleted, the
old fragment [q0010, q0019) starts below the new usable end. The scan skips
that fragment when it picks the clip end, so the new conversion can overlap
it.
This is safe because the clipped range is a part of the unclipped range
[lowest tombstone, t), which is already redundant: the scan saw [lowest
tombstone, E.usable_end] deleted, and the rest lies in E's usable range. The clip does not depend on
whether this scan's own publish succeeds. If the clipped range is empty (the
lowest tombstone is at or above the clip end), nothing is inserted and
READ_PATH_RANGE_TOMBSTONES_DISCARDED is incremented instead of
READ_PATH_RANGE_TOMBSTONES_INSERTED. Forward conversions need no clip: a
forward scan sent by a mark starts its run at the mark's usable end, so its
range starts where the previous one ended.
## Changes to forward marks
- `MemTableHeadMark` has a new field, `start_exclusive`. It is always false
for forward marks.
- The mark table is per direction: `MemTable::head_marks_` holds two tables,
and the `ReadOnlyMemTable` head mark methods take a `HeadMarkDirection`.
Forward marks keep their behavior; their code is the same helpers with the
user comparator order.
- Cost when the feature is off: an eligible reverse seek goes through the
virtual `SeekForPrevWithHeadMarks()`, which finds no registered memtable
and does the normal `SeekForPrev()`; `SeekForPrevImpl()` tests one more
flag per level, and a TryAgain child is sought again at the original
target, as without the feature. The write and ingestion checks are those of
the lower diff (one flag check each), and nothing new is allocated.
## Known limitations
- The compaction filter limitation of forward marks (`kRemoveAndSkipUntil`)
applies to reverse marks too, and there it is easy to reach: a reverse mark
claims its seek key t, and the converted range tombstone [lowest
tombstone, t) leaves t out. If a compaction filter skip drops the point
tombstone of t, `Get(t)` returns the older value, but a `SeekForPrev(t)`
that uses the mark skips t. The test
`CompactionFilterSkipHidesKeyFromMarkedScan` shows this behavior.
- `SeekToLast()` without `iterate_upper_bound` makes no reverse mark.
- Only the tombstone run right after a scan's seek can publish a mark, as
with forward marks: a run found later in a scan makes no mark. An existing
mark still helps a later reverse seek at or above its seq whose target lies
in the mark's usable range, also below the queue's largest key, or at the
mark's exclusive start when the seek excludes that key.
- Every live write does one more acquire load, of the reverse table pointer,
and a hull check only when reverse marks exist.
- After a late put lowers a reverse mark, the lowered usable end lies inside
an earlier converted range. The clip skips that range, so the next
conversion overlaps it once: it ends at the next fragment above it, or at
the seek target if there is none.
- The clip applies only when a mark of the active memtable moved the seek.
Other reverse conversions (the first one in a memtable, or one sent by a
mark of an immutable memtable) nest as before.
## How to read this diff
1. `db/memtable.h`: the "Reverse marks" paragraph of the head mark overview,
`MemTableHeadMark::start_exclusive`, `HeadMarkDirection`, and the
`ReadOnlyMemTable` methods that now take a direction.
2. `db/memtable.cc`: `HeadMarkOrder` use in the table helpers, the reverse
walk in `ValidateHeadMarkRange()`, and the exclusive start checks in
`FindUsableHeadMark()` and `LowerHeadMarksLocked()`.
3. `table/internal_iterator.h`, `table/iterator_wrapper.h`,
`table/merging_iterator.cc`: `SeekForPrevWithHeadMarks()`,
`SeekForPrevOverHeadMark()`, and the TryAgain retry at the moved key.
4. `db/db_iter.{h,cc}`: the reverse seek, the reverse run end in
`MaybePublishHeadMark()`, and the reverse clip in
`MaybeInsertRangeTombstone()`.
5. Tests: `db/db_range_del_test.cc` (`DBReverseHeadMarkTest`),
`db/db_memtable_test.cc`, `table/merger_test.cc`.
Differential Revision: D134014898
…ingIterator
Summary:
## Background
Read-path range tombstone conversion (`min_tombstones_for_range_conversion`, EXPERIMENTAL) lets a forward or reverse scan turn a run of contiguous point tombstones into one range tombstone in the mutable memtable. Later scans then skip the deleted range instead of stepping over every tombstone. The lower diffs in this stack add head marks: a scan that finds the dead head of a queue in the mutable memtable records it, and a later seek moves over it in the memtable and in the older sorted runs.
`MergingIterator` hides some deleted point keys from `DBIter` before `DBIter` can count them. A point key covered by a range tombstone from a newer sorted run is skipped with a cascading seek, which is cheap. A point key covered by a range tombstone from the same sorted run (for example, an immutable memtable that holds both the puts and an earlier converted tombstone) is skipped with one child `Next()` or `Prev()` per key. Each such step costs about as much as scanning the key. In this summary, "dropped key" means a point key that `MergingIterator` skips in this same-sorted-run case.
## The problem
`DBIter` never sees dropped keys, so a conversion run starts only at the first point tombstone that `DBIter` does see. Example with made-up ids: immutable memtable M1 holds Put and Delete of ids 1 to 1000 and its own converted tombstone [1, 1001). The mutable memtable M2 holds new deletes from id 1001 on. Every scan steps over the 2000 entries of M1 one by one. The new conversion in M2 starts at id 1001, so it never covers M1's range from a newer sorted run. M1 stays expensive to scan until it is flushed. The problem shows up when several memtables are merged at flush (`min_write_buffer_number_to_merge` > 1), because then many immutable memtables are in memory at once.
## Previous behavior
A conversion run counted only the visible point tombstones that `DBIter` processed. Dropped keys were not part of any run.
## New behavior
In forward and reverse scans, a conversion run also includes the keys dropped between the keys that `DBIter` processes, and it can start at a dropped key. The converted tombstone in the mutable memtable is in a newer sorted run than the dropped keys, which are in older memtables or SST files. So it covers them, and later scans skip them with one cascading seek. The conversion threshold counts entries: visible point tombstones plus dropped keys.
There is no new option. The existing experimental option controls this extension: when `min_tombstones_for_range_conversion` > 0, eligible scans add dropped entries to the conversion count, and each dropped internal entry counts once. So a run can reach the threshold with fewer visible point tombstones than the threshold; the option comment says so. All existing eligibility restrictions of conversion still apply, including the one for `unordered_write`. Users who do not set that option see no change in behavior.
## Implementation
1. The drop record. `MergingIterator` counts drops in the same-sorted-run branch of `SkipNextDeleted()` and `SkipPrevDeleted()` in a small plain struct, `DroppedKeyInfo`. Besides the count, it keeps copies of two dropped keys: the one with the smallest user key, and one with the next larger user key. The second one is needed because older versions of a key are dropped right next to its visible version, so the smallest dropped user key can be a key that `DBIter` handles itself (rule 2 in Safety).
- Forward moves: every `Next()` starts a new record, so the record describes the gap right before the current key. The first drop has the smallest user key, and the first later drop with another user key has the next one; after both are copied, a drop costs no compare.
- Backward moves: `DBIter` calls `Prev()` several times per user key, so the record adds up over several moves until `DBIter` clears it. Every drop has the smallest user key so far; when its user key is new, the previous smallest moves to the second slot.
- Every public `Seek`, `SeekForPrev`, `SeekToFirst`, `SeekToLast` and every change of direction clears the record first. `SeekImpl()` and `SeekForPrevImpl()` never clear it. Keys dropped by a cascading seek, range tombstone end keys and file boundary sentinel keys are never recorded.
- `DroppedKeyInfo::want_key`, set by `DBIter`, turns the key copies off when `DBIter` cannot use them. Forward, `DBIter` needs a key only to start a run, so it asks for it only while no run is open. Backward, a live key that ends a run can move the run start down to a dropped key, so it always asks.
2. Drops in the mutable memtable are not recorded. A tombstone built from them would go into that same memtable and would not help. `MergeIteratorBuilder::AddMutableMemtableIterator()` stores the exact child index of the mutable memtable. When MultiScan prunes the mutable memtable, no child is excluded, so drops in the immutable memtable at child 0 are recorded.
3. `DBImpl::NewInternalIterator()` turns recording on only when `min_tombstones_for_range_conversion` > 0, range deletions are not ignored, and `read_tier` is `kReadAllTier`. When the `DBIter` has conversion disabled anyway (for example, a prefix seek without `total_order_seek` or `prefix_same_as_start`), it turns the key copies off, so the read pays only for the count.
4. A new `InternalIterator::GetDroppedKeyInfo()` virtual returns a pointer to the record (default: nullptr, so other iterators are unaffected). `DBIter` asks for the pointer once, when its internal iterator is set, and only when conversion is enabled. After that, the per-key check is one load and compare of the count, with no virtual call. `IteratorWrapper` forwards the call.
5. Forward: `DBIter::FindNextUserEntryInternal()` reads the record only after the upper bound check and the `prefix_same_as_start` check, so a gap before a key outside the scan is never counted. `DBIter::MaybeAddDroppedKeysToRun()` adds the dropped keys to the run. When the run is empty, it starts the run at D, the smallest dropped user key above `saved_key_` (the last user key that `DBIter` processed). D is the record's smallest key, or else the next larger one. The run starts there only if D is less than the current key and passes the prefix check. Keys are compared without timestamps. The run count saturates at the `uint32_t` maximum.
6. Reverse: at the top of each step of `DBIter::PrevInternal()`, before it handles a new user key J, `DBIter` takes the record and clears it (`TakeReverseDroppedKeys()`). The start candidate D is the smallest dropped user key above J (the smallest, or else the next larger one). It is used only if D is below K, the user key handled by the step before (`range_tomb_end_key_` in the first step), and passes the prefix check. After J is handled: if J is a visible delete, the dropped keys add to the run, which then starts at J; if J is live, the run start moves down to D (or a run [D, end) starts) before the run is flushed; if J has no visible version, the run start moves down to D.
7. `DBIter` tracks whether a run holds at least one visible tombstone. At the end of a forward scan or at a prefix boundary, the end key is the last tracked tombstone, so a forward run made only of dropped keys is not converted there. A run of dropped keys that ends at a live key is converted as usual. In reverse scans the run end is always the live key above the run, or the `SeekForPrev()` target.
8. `MaybeInsertRangeTombstone()` returns without inserting when the start key is not less than the end key, in release builds too.
9. Head marks. A seek that a head mark moved records no drops for the keys it skipped, the same as a cascading seek; the mark already makes those keys cheap to skip. After the moved seek, the run counts drops as usual, so the dropped keys of an older memtable or SST file beyond the mark can bring the run to the threshold. A forward run made only of dropped keys that is not converted (rule 7) also publishes no mark. The reverse clip, which ends a reverse range at the range that an earlier scan of the same queue inserted, lowers only the high end of the range, so a run start at a dropped key is kept; the range is discarded if its start is not below the clipped end.
## Safety
The new tombstone is inserted at the iterator's sequence number S, as before, with every existing guard.
1. `MergingIterator` drops a key only when a range tombstone covers it. That tombstone is visible at the sequence number the child iterators were built with. Rule 3 shows that it is also visible at S whenever an insert happens. So every dropped version is already deleted at S.
2. Forward: between the last key `DBIter` processed and the current key, every internal key was dropped (by the same sorted run or by a cascading seek), was skipped by a seek that a head mark moved, or was skipped by a `DBIter` reseek, which only skips versions of `saved_key_`. A scan uses a head mark only when every key that the mark skips is deleted at S, except after a compaction filter returns `kRemoveAndSkipUntil` (a known limitation of head marks). So if a dropped user key is greater than `saved_key_`, all its versions are deleted at S. The "greater than" check prevents this case: Put(X)10, DeleteRange[X, ...)2000 and Put(X)2001 in one immutable memtable; `DBIter` returns X@2001, then X@10 is dropped. Starting the run at X would delete the live X. The run then starts at the next larger dropped user key instead. `DBIter` may also have received newer versions of the dropped key that are not visible at S. Their sequence numbers are above S, so the new tombstone does not cover them. If such a version is uncommitted and has a smaller sequence number, `MaybeInsertRangeTombstone()` refuses the insert (the existing `min_uncommitted` check).
3. Excluding the mutable memtable is part of the safety argument. Dropped keys and their covering tombstones come from immutable memtables or SST files. Their sequence numbers are below the mutable memtable's earliest sequence number, which `MaybeInsertRangeTombstone()` already requires to be at or below S. This also holds after `Refresh(snapshot)` lowers S without rebuilding those iterators. A file ingested while the memtable is mutable can hold a tombstone at or above that earliest sequence number; the existing ingest seqno barrier in `MemTable::AddLogicallyRedundantRangeTombstone()` refuses any insert below the ingested sequence number.
4. Reverse: the start D must be above the current user key J and below the previous step's user key K. Every internal key between J and K was dropped, skipped by a cascading seek, skipped by a seek that a reverse head mark moved, or skipped by a `DBIter` reseek, which skips only versions of K or of J. So every version of every user key in (J, K) is deleted at S, and the run can start at D. A drop that was recorded before K was handled has a user key at or above K, so it never passes the check. After `SeekForPrev(target)`, K is the target, or the upper bound if the target is not below it: `SeekForPrev()` examined every key up to there, except keys that a reverse head mark let it skip, which are deleted at S. After `SeekToLast()` there is no K, and those drops are not used, because nothing above them was examined.
This change relies on the existing rule, released in 11.14, that read-path conversion runs only for iterators with `read_tier = kReadAllTier`.
## Changes visible to existing users
Only users who set `min_tombstones_for_range_conversion` > 0 see a change.
- The same threshold now also counts dropped keys, not only visible point tombstones. So conversions happen earlier and more often, and `READ_PATH_RANGE_TOMBSTONES_INSERTED` goes up.
- An empty range [K, K) is no longer inserted. Such a range covers nothing, so there is no effect on data.
## Cost
With conversion off, `MergingIterator` does one extra predictable branch per same-sorted-run drop, and three stores per Seek, per `Next()`, and per `Prev()` that changes direction. With conversion on, `DBIter` loads and compares one count per key it processes. Forward, `MergingIterator` copies at most two keys per gap of dropped keys, and none while a run is open. Backward, it copies every dropped key (each one is the new smallest), into a reused buffer. No DB mutex is taken on the new paths.
## Performance
This measures the case that this change targets: keys that a user `DeleteRange` hides in the same SST file. A small program on the public API puts N keys of 100-byte values, takes a snapshot, calls `DeleteRange` over all N keys, puts one live key after them, flushes, and releases the snapshot. The snapshot keeps the covered puts in the SST next to the range tombstone; without it, the flush would drop them. Then 200 scans each create an iterator, `Seek()` to the start of the range, and read the live key. Options: one 128 MB memtable, auto compaction off, `min_tombstones_for_range_conversion` = 100. "Before" is a release build of the parent commit, "after" a release build of this change. Host: AMD EPYC 9D85, 316 CPUs, load average 64 to 71 from other users. Each before run and its after run ran at the same time on two different CPUs, the CPUs rotated over 10 even cores from repeat to repeat, and before and after swapped CPUs every other repeat. There are 5 repeats per row. The time is the thread CPU time per scan.
| Covered keys N | First scan, before | First scan, after | Later scans (median), before | Later scans (median), after |
|---|---|---|---|---|
| 10,000 | 1.13 to 1.79 ms | 1.14 to 1.19 ms | 403 to 410 us | 2.4 us |
| 100,000 | 11.4 to 12.8 ms | 11.5 to 13.1 ms | 4.01 to 4.14 ms | 2.5 to 2.9 us |
- Before, every scan steps over all N covered keys, and no range tombstone is inserted, because the scan sees no point tombstone.
- After, the first scan costs the same and inserts one range tombstone in the mutable memtable. That tombstone covers the SST's keys from a newer sorted run, so every later scan skips them with a seek instead of stepping over them (a head mark that the first scan publishes can also move that seek), and its cost no longer depends on N.
- Every run returned the live key on every scan.
## Known limitations
- Conservative cases: the first gap after `SeekToFirst()` (there `saved_key_` is the first key that `MergingIterator` returns, which is after the dropped keys, so the "greater than `saved_key_`" check rejects the dropped start), a dropped key equal to the seek target, drops before the first key after `SeekToLast()`, and drops after the last key at the end of a scan (both directions). Those dropped keys can still be added to a run that a visible tombstone started.
- A `DBIter` reseek inside a reverse scan, or a forward step inside `FindValueForCurrentKeyUsingSeek()`, clears the record, so those drops are not used.
- Drops in the mutable memtable are not used, by design.
- Keys that a head mark lets a seek skip are not counted. The mark already makes them cheap to skip.
- Reverse scans copy one key per drop.
- In setups where most covered keys are in the mutable memtable, the extension does not reduce memtable steps.
## How to read this diff
1. `table/internal_iterator.h` and `table/iterator_wrapper.h`: the `DroppedKeyInfo` struct (forward and backward lifetime, the two key slots, `want_key`) and the `GetDroppedKeyInfo()` contract.
2. `table/merging_iterator.h` and `table/merging_iterator.cc`: how drops are recorded and cleared, and how the mutable memtable child is excluded.
3. `db/db_impl/db_impl.cc`: when recording is turned on, and the mutable memtable registration.
4. `db/db_iter.h` and `db/db_iter.cc`: forward `MaybeAddDroppedKeysToRun()` with its safety comment ("Dropped keys in a conversion run"), the reverse step in `PrevInternal()` with `TakeReverseDroppedKeys()` and `ExtendRunStartToDroppedKey()`, the `run_has_visible_tombstone_` rule, the release-mode start < end check, and the reverse clip comment in `MaybeInsertRangeTombstone()`.
5. `db/db_range_del_test.cc`: the tests.
Differential Revision: D133251153
|
@xingbowang has exported this pull request. If you are a Meta employee, you can view the originating Diff in D133251153. |
✅ clang-tidy: No findings on changed linesCompleted in 970.4s. |
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary:
Background
Read-path range tombstone conversion (
min_tombstones_for_range_conversion, EXPERIMENTAL) lets a forward or reverse scan turn a run of contiguous point tombstones into one range tombstone in the mutable memtable. Later scans then skip the deleted range instead of stepping over every tombstone. The lower diffs in this stack add head marks: a scan that finds the dead head of a queue in the mutable memtable records it, and a later seek moves over it in the memtable and in the older sorted runs.MergingIteratorhides some deleted point keys fromDBIterbeforeDBItercan count them. A point key covered by a range tombstone from a newer sorted run is skipped with a cascading seek, which is cheap. A point key covered by a range tombstone from the same sorted run (for example, an immutable memtable that holds both the puts and an earlier converted tombstone) is skipped with one childNext()orPrev()per key. Each such step costs about as much as scanning the key. In this summary, "dropped key" means a point key thatMergingIteratorskips in this same-sorted-run case.The problem
DBIternever sees dropped keys, so a conversion run starts only at the first point tombstone thatDBIterdoes see. Example with made-up ids: immutable memtable M1 holds Put and Delete of ids 1 to 1000 and its own converted tombstone [1, 1001). The mutable memtable M2 holds new deletes from id 1001 on. Every scan steps over the 2000 entries of M1 one by one. The new conversion in M2 starts at id 1001, so it never covers M1's range from a newer sorted run. M1 stays expensive to scan until it is flushed. The problem shows up when several memtables are merged at flush (min_write_buffer_number_to_merge> 1), because then many immutable memtables are in memory at once.Previous behavior
A conversion run counted only the visible point tombstones that
DBIterprocessed. Dropped keys were not part of any run.New behavior
In forward and reverse scans, a conversion run also includes the keys dropped between the keys that
DBIterprocesses, and it can start at a dropped key. The converted tombstone in the mutable memtable is in a newer sorted run than the dropped keys, which are in older memtables or SST files. So it covers them, and later scans skip them with one cascading seek. The conversion threshold counts entries: visible point tombstones plus dropped keys.There is no new option. The existing experimental option controls this extension: when
min_tombstones_for_range_conversion> 0, eligible scans add dropped entries to the conversion count, and each dropped internal entry counts once. So a run can reach the threshold with fewer visible point tombstones than the threshold; the option comment says so. All existing eligibility restrictions of conversion still apply, including the one forunordered_write. Users who do not set that option see no change in behavior.Implementation
MergingIteratorcounts drops in the same-sorted-run branch ofSkipNextDeleted()andSkipPrevDeleted()in a small plain struct,DroppedKeyInfo. Besides the count, it keeps copies of two dropped keys: the one with the smallest user key, and one with the next larger user key. The second one is needed because older versions of a key are dropped right next to its visible version, so the smallest dropped user key can be a key thatDBIterhandles itself (rule 2 in Safety).Next()starts a new record, so the record describes the gap right before the current key. The first drop has the smallest user key, and the first later drop with another user key has the next one; after both are copied, a drop costs no compare.DBItercallsPrev()several times per user key, so the record adds up over several moves untilDBIterclears it. Every drop has the smallest user key so far; when its user key is new, the previous smallest moves to the second slot.Seek,SeekForPrev,SeekToFirst,SeekToLastand every change of direction clears the record first.SeekImpl()andSeekForPrevImpl()never clear it. Keys dropped by a cascading seek, range tombstone end keys and file boundary sentinel keys are never recorded.DroppedKeyInfo::want_key, set byDBIter, turns the key copies off whenDBItercannot use them. Forward,DBIterneeds a key only to start a run, so it asks for it only while no run is open. Backward, a live key that ends a run can move the run start down to a dropped key, so it always asks.MergeIteratorBuilder::AddMutableMemtableIterator()stores the exact child index of the mutable memtable. When MultiScan prunes the mutable memtable, no child is excluded, so drops in the immutable memtable at child 0 are recorded.DBImpl::NewInternalIterator()turns recording on only whenmin_tombstones_for_range_conversion> 0, range deletions are not ignored, andread_tieriskReadAllTier. When theDBIterhas conversion disabled anyway (for example, a prefix seek withouttotal_order_seekorprefix_same_as_start), it turns the key copies off, so the read pays only for the count.InternalIterator::GetDroppedKeyInfo()virtual returns a pointer to the record (default: nullptr, so other iterators are unaffected).DBIterasks for the pointer once, when its internal iterator is set, and only when conversion is enabled. After that, the per-key check is one load and compare of the count, with no virtual call.IteratorWrapperforwards the call.DBIter::FindNextUserEntryInternal()reads the record only after the upper bound check and theprefix_same_as_startcheck, so a gap before a key outside the scan is never counted.DBIter::MaybeAddDroppedKeysToRun()adds the dropped keys to the run. When the run is empty, it starts the run at D, the smallest dropped user key abovesaved_key_(the last user key thatDBIterprocessed). D is the record's smallest key, or else the next larger one. The run starts there only if D is less than the current key and passes the prefix check. Keys are compared without timestamps. The run count saturates at theuint32_tmaximum.DBIter::PrevInternal(), before it handles a new user key J,DBItertakes the record and clears it (TakeReverseDroppedKeys()). The start candidate D is the smallest dropped user key above J (the smallest, or else the next larger one). It is used only if D is below K, the user key handled by the step before (range_tomb_end_key_in the first step), and passes the prefix check. After J is handled: if J is a visible delete, the dropped keys add to the run, which then starts at J; if J is live, the run start moves down to D (or a run [D, end) starts) before the run is flushed; if J has no visible version, the run start moves down to D.DBItertracks whether a run holds at least one visible tombstone. At the end of a forward scan or at a prefix boundary, the end key is the last tracked tombstone, so a forward run made only of dropped keys is not converted there. A run of dropped keys that ends at a live key is converted as usual. In reverse scans the run end is always the live key above the run, or theSeekForPrev()target.MaybeInsertRangeTombstone()returns without inserting when the start key is not less than the end key, in release builds too.Safety
The new tombstone is inserted at the iterator's sequence number S, as before, with every existing guard.
MergingIteratordrops a key only when a range tombstone covers it. That tombstone is visible at the sequence number the child iterators were built with. Rule 3 shows that it is also visible at S whenever an insert happens. So every dropped version is already deleted at S.DBIterprocessed and the current key, every internal key was dropped (by the same sorted run or by a cascading seek), was skipped by a seek that a head mark moved, or was skipped by aDBIterreseek, which only skips versions ofsaved_key_. A scan uses a head mark only when every key that the mark skips is deleted at S, except after a compaction filter returnskRemoveAndSkipUntil(a known limitation of head marks). So if a dropped user key is greater thansaved_key_, all its versions are deleted at S. The "greater than" check prevents this case: Put(X)10, DeleteRange[X, ...)2000 and Put(X)2001 in one immutable memtable;DBIterreturns X@2001, then X@10 is dropped. Starting the run at X would delete the live X. The run then starts at the next larger dropped user key instead.DBItermay also have received newer versions of the dropped key that are not visible at S. Their sequence numbers are above S, so the new tombstone does not cover them. If such a version is uncommitted and has a smaller sequence number,MaybeInsertRangeTombstone()refuses the insert (the existingmin_uncommittedcheck).MaybeInsertRangeTombstone()already requires to be at or below S. This also holds afterRefresh(snapshot)lowers S without rebuilding those iterators. A file ingested while the memtable is mutable can hold a tombstone at or above that earliest sequence number; the existing ingest seqno barrier inMemTable::AddLogicallyRedundantRangeTombstone()refuses any insert below the ingested sequence number.DBIterreseek, which skips only versions of K or of J. So every version of every user key in (J, K) is deleted at S, and the run can start at D. A drop that was recorded before K was handled has a user key at or above K, so it never passes the check. AfterSeekForPrev(target), K is the target, or the upper bound if the target is not below it:SeekForPrev()examined every key up to there, except keys that a reverse head mark let it skip, which are deleted at S. AfterSeekToLast()there is no K, and those drops are not used, because nothing above them was examined.This change relies on the existing rule, released in 11.14, that read-path conversion runs only for iterators with
read_tier = kReadAllTier.Changes visible to existing users
Only users who set
min_tombstones_for_range_conversion> 0 see a change.READ_PATH_RANGE_TOMBSTONES_INSERTEDgoes up.Cost
With conversion off,
MergingIteratordoes one extra predictable branch per same-sorted-run drop, and three stores per Seek, perNext(), and perPrev()that changes direction. With conversion on,DBIterloads and compares one count per key it processes. Forward,MergingIteratorcopies at most two keys per gap of dropped keys, and none while a run is open. Backward, it copies every dropped key (each one is the new smallest), into a reused buffer. No DB mutex is taken on the new paths.Performance
This measures the case that this change targets: keys that a user
DeleteRangehides in the same SST file. A small program on the public API puts N keys of 100-byte values, takes a snapshot, callsDeleteRangeover all N keys, puts one live key after them, flushes, and releases the snapshot. The snapshot keeps the covered puts in the SST next to the range tombstone; without it, the flush would drop them. Then 200 scans each create an iterator,Seek()to the start of the range, and read the live key. Options: one 128 MB memtable, auto compaction off,min_tombstones_for_range_conversion= 100. "Before" is a release build of the parent commit, "after" a release build of this change. Host: AMD EPYC 9D85, 316 CPUs, load average 64 to 71 from other users. Each before run and its after run ran at the same time on two different CPUs, the CPUs rotated over 10 even cores from repeat to repeat, and before and after swapped CPUs every other repeat. There are 5 repeats per row. The time is the thread CPU time per scan.Known limitations
SeekToFirst()(theresaved_key_is the first key thatMergingIteratorreturns, which is after the dropped keys, so the "greater thansaved_key_" check rejects the dropped start), a dropped key equal to the seek target, drops before the first key afterSeekToLast(), and drops after the last key at the end of a scan (both directions). Those dropped keys can still be added to a run that a visible tombstone started.DBIterreseek inside a reverse scan, or a forward step insideFindValueForCurrentKeyUsingSeek(), clears the record, so those drops are not used.How to read this diff
table/internal_iterator.handtable/iterator_wrapper.h: theDroppedKeyInfostruct (forward and backward lifetime, the two key slots,want_key) and theGetDroppedKeyInfo()contract.table/merging_iterator.handtable/merging_iterator.cc: how drops are recorded and cleared, and how the mutable memtable child is excluded.db/db_impl/db_impl.cc: when recording is turned on, and the mutable memtable registration.db/db_iter.handdb/db_iter.cc: forwardMaybeAddDroppedKeysToRun()with its safety comment ("Dropped keys in a conversion run"), the reverse step inPrevInternal()withTakeReverseDroppedKeys()andExtendRunStartToDroppedKey(), therun_has_visible_tombstone_rule, the release-mode start < end check, and the reverse clip comment inMaybeInsertRangeTombstone().db/db_range_del_test.cc: the tests.Differential Revision: D133251153