Skip to content

Skip the dead head of a queue in the memtable with head marks (#15772) - #15772

Open
xingbowang wants to merge 3 commits into
meta:mainfrom
xingbowang:export-D134004281
Open

xingbowang wants to merge 3 commits into
meta:mainfrom
xingbowang:export-D134004281

Conversation

@xingbowang

@xingbowang xingbowang commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary:

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

@meta-cla meta-cla Bot added the CLA Signed label Nov 24, 2026
@meta-codesync

meta-codesync Bot commented Nov 24, 2026

Copy link
Copy Markdown

@xingbowang has exported this pull request. If you are a Meta employee, you can view the originating Diff in D134004281.

@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

✅ clang-tidy: No findings on changed lines

Completed in 984.3s.

@xingbowang
xingbowang force-pushed the export-D134004281 branch 5 times, most recently from 2237313 to 74df96f Compare November 26, 2026 12:54
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 26, 2026
…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. `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
@meta-codesync meta-codesync Bot changed the title Skip the dead head of a queue in the memtable with head marks Skip the dead head of a queue in the memtable with head marks (#15772) Nov 26, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 26, 2026
…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. `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
@meta-codesync meta-codesync Bot changed the title Skip the dead head of a queue in the memtable with head marks (#15772) Skip the dead head of a queue in the memtable with head marks Nov 26, 2026
…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
@meta-codesync meta-codesync Bot changed the title Skip the dead head of a queue in the memtable with head marks Skip the dead head of a queue in the memtable with head marks (#15772) Nov 26, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 26, 2026
…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

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