Skip to content

Don't update in place a value that a range tombstone deletes (#15775) - #15775

Open
xingbowang wants to merge 1 commit into
meta:mainfrom
xingbowang:export-D134285230
Open

xingbowang wants to merge 1 commit into
meta:mainfrom
xingbowang:export-D134285230

Conversation

@xingbowang

@xingbowang xingbowang commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary:

Background

With ColumnFamilyOptions::inplace_update_support, a Put() to a key whose newest entry in the mutable memtable is a value of the same type, at least as large as the new value, overwrites that entry in place (MemTable::Update()). The entry keeps the sequence number of the value it overwrites. With inplace_callback, MemTable::UpdateCallback() passes that entry to the callback as the existing value, and the callback can update it in place too. WAL recovery inserts through the same functions with the options of the current DB::Open(), so it also updates in place when the DB is opened with the option, whatever options wrote the WAL.

The problem

A range tombstone hides the entries in its range that have smaller sequence numbers. It lives in the memtable's range deletion table, which in-place updates did not look at:

  1. Put(k, v1) gets sequence number 1.
  2. DeleteRange(a, z) gets sequence number 2.
  3. Put(k, v2): v2 fits in the space of v1, so the entry is overwritten in place and keeps sequence number 1.

Get(k) then returns NotFound, although the second Put() came after the deletion, and flush and compaction keep that result. The same three writes in a WAL written without the option lose v2 when the DB is reopened with it: replay updates in place, and the recovery flush makes the loss permanent. With inplace_callback, the callback also received the deleted value as the existing value. The crash test hit the replay case when runs with and without in-place updates shared a DB; #15626 then made crash test series with in-place updates write no range tombstones.

Fix

MemTable::Update() and MemTable::UpdateCallback() treat an entry that a range tombstone in the same memtable deletes (MaxCoveringTombstoneSeqnum() above the entry's sequence number) as missing. Update() then adds the new value with its own sequence number. UpdateCallback() returns NotFound, so MemTableInserter::PutCFImpl() reads the existing value through the DB, which honors the tombstone, and the callback sees no existing value. Live writes and WAL replay go through the same check. Values already lost this way before this change stay lost.

Checking only the active memtable is enough. Entries in immutable memtables and SST files are older than every entry in the active memtable, so a tombstone there cannot fall between an entry and its in-place update. Ingested files are the exception to that ordering, but ingestion first flushes the memtables that overlap the ingested files, so no entry that an ingested tombstone covers stays in the active memtable. Tombstones that iterators insert when converting point tombstones (min_tombstones_for_range_conversion) go into the active memtable, so the check sees them.

Cost

Nothing while the memtable has no range tombstones: the check returns before creating an iterator. Otherwise every Put() that could update in place looks up the covering tombstone. It creates an iterator over the memtable's cached fragmented tombstone list, and the first such Put() after a new range tombstone rebuilds that list from all tombstones in the memtable, on the write path. During WAL replay that happens under the DB mutex, which recovery holds throughout; each new range tombstone in the recovering memtable causes at most one rebuild, over all range tombstones then in that memtable. A Put() to a key that a tombstone deletes appends a new entry; later Put()s to that key update the new entry in place. With inplace_callback, the appending Put() also reads the key through the DB.

Measured with db_bench (release build, one thread pinned to one CPU of an AMD EPYC 9D25 host): fillseq then overwrite, 200k writes each over about 100k keys, 16-byte keys, 100-byte values overwritten in place by values of the same size, WAL disabled, and a write buffer large enough that everything stays in one memtable. db_bench writes the range tombstones during both phases. Time per overwrite in ns, median of 7 runs with the builds alternating, minimum and maximum in parentheses:

Range tombstones Before With this change
None 1126 (1032-1176) 1155 (1044-1237)
One per phase, each covering 1 key 1115 (1089-1206) 1273 (1203-1393), +14%
One every 100 writes, each covering 1 key, 4000 by the end 1292 (1219-1390) 5953 (5789-6033), 4.6x
One every 100 writes, each covering 100 keys, 4000 by the end 1343 (1221-1367) 8300 (8286-8444), 6.2x

Most of the cost in the last two rows is the rebuild after every new tombstone. In this write-only benchmark nothing else rebuilds the list; when reads follow each new tombstone, the first read rebuilds it without this change too (from the code, not measured). In the last row, 37% of the overwrites hit a value that a newer tombstone deletes; without this change those writes were lost.

Only the combination that lost writes before pays this, and we know of no user that combines in-place updates with range deletions, so this change keeps the precise check; a TODO in MemTable::IsDeletedByRangeTombstone() records the cost. Skipping the lookup when the existing entry is newer than every range tombstone in the memtable would help little: an in-place update keeps the entry's sequence number, so in the last two rows almost every entry stays older than the newest tombstone. Not updating in place at all while the memtable has range tombstones would make the check one atomic load, at the cost of appending every Put() until the memtable is switched.

Alternative considered

Rejecting range deletions on column families with in-place updates was not done. WAL replay still updates in place, so rejecting new range deletions cannot protect a WAL written without the option, and it would make DeleteRange(), write batches, ingestion, ClipColumnFamily() and DB split/merge fail on such column families.

Crash test

Crash test series with in-place updates write range tombstones again: delrangepercent, test_ingest_standalone_range_deletion_one_in and min_tombstones_for_range_conversion are no longer turned off for them, and setting one of them on the command line no longer turns in-place updates off for the series.

Recovery with inplace_callback, unchanged

With inplace_callback, DB::Open() already fails with NotSupported when the WAL holds a callback Put(): during recovery PutCFImpl() does not read the DB, so the first replayed Put() of a key, which is never in the recovering memtable yet, has no existing value to pass to the callback, and WAL recovery treats the error as fatal. With paranoid_checks=false, or with wal_recovery_mode=kSkipAnyCorruptedRecords, the error is only logged and the DB opens, but each failing Put() and the records after it in the same write batch are dropped. All of this happens the same way before and after this change. So this change neither fixes nor adds a recovery failure with inplace_callback. A fix belongs in a separate change.

Reviewed By: xingbowang

Differential Revision: D134285230

@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 D134285230.

@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

✅ clang-tidy: No findings on changed lines

Completed in 107.9s.

@github-actions

Copy link
Copy Markdown

✅ Claude Code Review

Auto-triggered after CI passed — reviewing commit d7685d0


Summary

Well-designed and carefully implemented behavior change that closes a real data correctness bug. The approach of rejecting range deletions at the write path (before WAL) rather than trying to make the combination work is pragmatic and sound. The flag-based fast path ensures zero cost for DBs that don't use inplace_update_support. All major paths (write, ingestion, read-path conversion) are covered, and the acknowledged WAL recovery limitation is clearly documented.

High-severity findings (0):

No high-severity findings.

Full review (click to expand)

Findings

🔴 HIGH

None.

🟡 MEDIUM

M1. Comment added inside the min_tombstones_for_range_conversion condition -- db/db_iter.cc:140
  • Issue: The CLAUDE.md guidelines say "NEVER ADD COMMENTS unless asked." While this is a code review (not code generation), the comment // Column families with in-place updates take no range tombstones. is added inside a complex conditional expression. The PR description says "the condition is added on its own line, so that it composes with other changes to the same conversion condition." The comment adds useful context for why this condition exists, since it's not obvious from the code alone. This is a borderline nit -- the comment is helpful but could be argued either way.
  • Root cause: Style preference.
  • Suggested fix: Consider whether the comment is necessary or if the condition !ioptions.inplace_update_support is self-documenting enough in context. If kept, it's fine.
M2. Full batch scan in CheckRangeDeletionsSupported iterates all records -- db/db_impl/db_impl_write.cc:901-923
  • Issue: CheckRangeDeletionsSupported uses ReadRecordFromWriteBatch to scan ALL records in the batch, not just range deletions. For large batches (e.g., bulk loads with millions of operations), this is a full deserialization pass. This is mitigated by: (a) it only triggers when HasDeleteRange() is true AND the DB has the flag set, (b) batches with range deletions are typically small, (c) the overhead is proportional to the batch size which is already being processed.
  • Root cause: ReadRecordFromWriteBatch is the standard way to iterate batch records, and there's no index structure to jump to range deletions.
  • Suggested fix: Acceptable as-is given the gating conditions. If performance evidence shows this matters, a targeted scan could skip non-range-deletion records more efficiently, but this is premature optimization.

🟢 LOW / NIT

L1. std::find linear scan on autovector for deduplication -- db/db_impl/db_impl_write.cc:918-920
  • Issue: The deduplication of range_del_cf_ids uses std::find with O(n) lookup per range deletion. For batches with many range deletions across many distinct CFs, this is O(n*m). In practice, the number of distinct CFs with range deletions in a single batch is very small (typically 1-2), so the autovector with linear scan is appropriate.
  • Suggested fix: None needed. The autovector is the right choice here.
L2. Condition order in WriteImpl check is a slight improvement -- db/db_impl/db_impl_write.cc:993-999
  • Issue: The old code checked HasDeleteRange() first, then row_cache. The new code checks (row_cache || flag) first, then HasDeleteRange(). For the common case (no row_cache, no inplace_update), the new code short-circuits on the first condition (both are false), avoiding the HasDeleteRange() call entirely. This is actually a slight performance improvement for the common path. Good.
  • Suggested fix: None needed. The new order is better.
L3. The break removal in DropColumnFamilyWithOptionsFile is correct -- db/db_impl/db_impl.cc:5630-5655
  • Issue: The old code broke early after finding a CF without snapshot support. The new code continues iterating to also check inplace_update_support. This is correct because: (a) new_is_snapshot_supported starts true and is monotonically set to false, so continuing the loop doesn't change its final value, (b) the loop must continue to find any CF with inplace_update_support. The iteration is over all CFs which is a cold path (only on CF drop), so the performance impact is negligible.
  • Suggested fix: None needed.

Cross-Component Analysis

Context Affected? Safe? Notes
WritePreparedTxnDB NO N/A Rejects inplace_update_support at open
WriteUnpreparedTxnDB NO N/A Rejects inplace_update_support at open
WriteCommittedTxnDB YES YES Both skip_concurrency_control (db_impl_->Write()) and normal (CommitBatch->WriteImpl) paths go through WriteImpl
ReadOnly DB NO N/A No writes
Secondary Instance NO N/A No writes
WAL Recovery YES KNOWN LIMITATION Documented. Range tombstones replayed from WAL are not checked.
User-defined timestamps NO N/A No special interaction
MemPurge NO N/A No interaction with range deletion check
Ingestion YES YES Both regular ingestion and atomic_replace_range are covered
Read-path conversion YES YES min_tombstones_for_range_conversion disabled in db_iter.cc

Thread safety analysis:

  • has_inplace_update_support_cf_ uses memory_order_relaxed, matching the pattern of is_snapshot_supported_. This is safe because:
    • Setting true (CreateColumnFamily): Done under mutex_ before the handle is returned. A write through the new handle can't happen until after the handle is returned, establishing happens-before.
    • Setting false (DropColumnFamily): Done under mutex_. A brief window where concurrent writes see stale true is harmless -- they just do an unnecessary check that correctly rejects nothing (the dropped CF won't be found by GetColumnFamily).
    • False negative (flag is false but CF has inplace_update): Impossible because the flag is set before the handle is exposed.

DB Mutex impact:

  • CheckRangeDeletionsSupported acquires mutex_ briefly for CF lookups. This is on the write path but only triggers for writes with range deletions in DBs with inplace_update or row_cache. The mutex hold time is O(number of distinct CFs with range deletions in the batch), which is very small. No I/O or expensive operations under the lock.

Assumption stress test:

  • "No new range tombstones" -- Verified: write path, ingestion path, and read-path conversion are all covered. WAL recovery is the only gap, documented.
  • "Batch rejected before WAL" -- Verified: CheckRangeDeletionsSupported is called in WriteImpl's early validation section, before the batch enters the write group.
  • "inplace_update_support cannot be changed with SetOptions" -- Verified: It's in ImmutableCFOptions.

Positive Observations

  1. Zero feature-off cost: For DBs without inplace_update_support and without row_cache, the check is nullptr || false which short-circuits to false, never calling HasDeleteRange(). Better than the old code.

  2. Well-chosen rejection point: Rejecting before WAL write prevents background errors that would stop all writes.

  3. Comprehensive coverage: All three paths that could introduce range tombstones are covered, and the WAL recovery limitation is honestly documented.

  4. Thorough testing: Tests cover basic rejection, batch rejection, WAL safety, dynamic CF create/drop, read-path conversion, ingestion, atomic_replace_range, and TransactionDB.

  5. Clean separation of concerns: The flag is maintained alongside is_snapshot_supported_ in the same three places (Open, Create, Drop).


ℹ️ About this response

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

Limitations:

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

Commands:

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

)

Summary:

**Background**

With `ColumnFamilyOptions::inplace_update_support`, a `Put()` to a key whose newest entry in the mutable memtable is a value of the same type, at least as large as the new value, overwrites that entry in place (`MemTable::Update()`). The entry keeps the sequence number of the value it overwrites. With `inplace_callback`, `MemTable::UpdateCallback()` passes that entry to the callback as the existing value, and the callback can update it in place too. WAL recovery inserts through the same functions with the options of the current `DB::Open()`, so it also updates in place when the DB is opened with the option, whatever options wrote the WAL.

**The problem**

A range tombstone hides the entries in its range that have smaller sequence numbers. It lives in the memtable's range deletion table, which in-place updates did not look at:

1. `Put(k, v1)` gets sequence number 1.
2. `DeleteRange(a, z)` gets sequence number 2.
3. `Put(k, v2)`: `v2` fits in the space of `v1`, so the entry is overwritten in place and keeps sequence number 1.

`Get(k)` then returns NotFound, although the second `Put()` came after the deletion, and flush and compaction keep that result. The same three writes in a WAL written without the option lose `v2` when the DB is reopened with it: replay updates in place, and the recovery flush makes the loss permanent. With `inplace_callback`, the callback also received the deleted value as the existing value. The crash test hit the replay case when runs with and without in-place updates shared a DB; meta#15626 then made crash test series with in-place updates write no range tombstones.

**Fix**

`MemTable::Update()` and `MemTable::UpdateCallback()` treat an entry that a range tombstone in the same memtable deletes (`MaxCoveringTombstoneSeqnum()` above the entry's sequence number) as missing. `Update()` then adds the new value with its own sequence number. `UpdateCallback()` returns NotFound, so `MemTableInserter::PutCFImpl()` reads the existing value through the DB, which honors the tombstone, and the callback sees no existing value. Live writes and WAL replay go through the same check. Values already lost this way before this change stay lost.

Checking only the active memtable is enough. Entries in immutable memtables and SST files are older than every entry in the active memtable, so a tombstone there cannot fall between an entry and its in-place update. Ingested files are the exception to that ordering, but ingestion first flushes the memtables that overlap the ingested files, so no entry that an ingested tombstone covers stays in the active memtable. Tombstones that iterators insert when converting point tombstones (`min_tombstones_for_range_conversion`) go into the active memtable, so the check sees them.

**Cost**

Nothing while the memtable has no range tombstones: the check returns before creating an iterator. Otherwise every `Put()` that could update in place looks up the covering tombstone. It creates an iterator over the memtable's cached fragmented tombstone list, and the first such `Put()` after a new range tombstone rebuilds that list from all tombstones in the memtable, on the write path. During WAL replay that happens under the DB mutex, which recovery holds throughout; each new range tombstone in the recovering memtable causes at most one rebuild, over all range tombstones then in that memtable. A `Put()` to a key that a tombstone deletes appends a new entry; later `Put()`s to that key update the new entry in place. With `inplace_callback`, the appending `Put()` also reads the key through the DB.

Measured with `db_bench` (release build, one thread pinned to one CPU of an AMD EPYC 9D25 host): `fillseq` then `overwrite`, 200k writes each over about 100k keys, 16-byte keys, 100-byte values overwritten in place by values of the same size, WAL disabled, and a write buffer large enough that everything stays in one memtable. `db_bench` writes the range tombstones during both phases. Time per overwrite in ns, median of 7 runs with the builds alternating, minimum and maximum in parentheses:

| Range tombstones | Before | With this change |
|---|---|---|
| None | 1126 (1032-1176) | 1155 (1044-1237) |
| One per phase, each covering 1 key | 1115 (1089-1206) | 1273 (1203-1393), +14% |
| One every 100 writes, each covering 1 key, 4000 by the end | 1292 (1219-1390) | 5953 (5789-6033), 4.6x |
| One every 100 writes, each covering 100 keys, 4000 by the end | 1343 (1221-1367) | 8300 (8286-8444), 6.2x |

Most of the cost in the last two rows is the rebuild after every new tombstone. In this write-only benchmark nothing else rebuilds the list; when reads follow each new tombstone, the first read rebuilds it without this change too (from the code, not measured). In the last row, 37% of the overwrites hit a value that a newer tombstone deletes; without this change those writes were lost.

Only the combination that lost writes before pays this, and we know of no user that combines in-place updates with range deletions, so this change keeps the precise check; a TODO in `MemTable::IsDeletedByRangeTombstone()` records the cost. Skipping the lookup when the existing entry is newer than every range tombstone in the memtable would help little: an in-place update keeps the entry's sequence number, so in the last two rows almost every entry stays older than the newest tombstone. Not updating in place at all while the memtable has range tombstones would make the check one atomic load, at the cost of appending every `Put()` until the memtable is switched.

**Alternative considered**

Rejecting range deletions on column families with in-place updates was not done. WAL replay still updates in place, so rejecting new range deletions cannot protect a WAL written without the option, and it would make `DeleteRange()`, write batches, ingestion, `ClipColumnFamily()` and DB split/merge fail on such column families.

**Crash test**

Crash test series with in-place updates write range tombstones again: `delrangepercent`, `test_ingest_standalone_range_deletion_one_in` and `min_tombstones_for_range_conversion` are no longer turned off for them, and setting one of them on the command line no longer turns in-place updates off for the series.

**Recovery with `inplace_callback`, unchanged**

With `inplace_callback`, `DB::Open()` already fails with NotSupported when the WAL holds a callback `Put()`: during recovery `PutCFImpl()` does not read the DB, so the first replayed `Put()` of a key, which is never in the recovering memtable yet, has no existing value to pass to the callback, and WAL recovery treats the error as fatal. With `paranoid_checks=false`, or with `wal_recovery_mode=kSkipAnyCorruptedRecords`, the error is only logged and the DB opens, but each failing `Put()` and the records after it in the same write batch are dropped. All of this happens the same way before and after this change. So this change neither fixes nor adds a recovery failure with `inplace_callback`. A fix belongs in a separate change.

Reviewed By: xingbowang

Differential Revision: D134285230
@meta-codesync meta-codesync Bot changed the title Reject range deletions on column families with inplace_update_support Don't update in place a value that a range tombstone deletes (#15775) Nov 30, 2026

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