1
0
mirror of https://github.com/facebook/rocksdb.git synced 2026-10-27 20:33:15 +03:00

9 Commits

Author SHA1 Message Date
Ranjan Banerjee
a38cd3a439 Bypass stalled cross-DB WBM flush candidates (#15331)
Summary:
Pull Request resolved: https://github.com/facebook/rocksdb/pull/15331

## Motivation

The parent diff already implements cross-DB flushable-memory accounting and a background sorter that ranks DBs outside the write path. This change does not alter how the best candidate is selected.

The remaining liveness problem occurs after the sorter selects a DB and hands it off for execution. Previously, the coordinator tracked one remote handoff as pending and waited for that DB to report completion before advancing. A selected DB could therefore monopolize coordinator progress if its job waited in Env::LOW, blocked on the DB mutex, waited behind an existing write leader or write stall, or otherwise failed to complete promptly. Other ranked DBs could be ready to reclaim memory but would not be attempted while the first handoff remained pending.

## Solution

Make cross-DB flush handoff execution bounded and bypassable.

Cross-DB attempts now run on a small four-worker executor owned by the WriteBufferManager instead of consuming Env::LOW compaction capacity. The executor is created only for kFlushLargestAcrossDBs and its workers are retired when that policy is disabled.

The coordinator distinguishes queued and executing handoffs. A candidate lease begins when an executor worker starts the callback, rather than while the callback is merely waiting in the executor queue. If an executing handoff exceeds its lease, the coordinator releases ownership of that attempt and advances to the next ranked candidate. The original callback is not cancelled and may still complete, so the executor and outstanding-handoff count provide a strict bound on concurrent stuck work.

Each registration has a per-DB outstanding-job reservation, preventing the sorter from dispatching the same DB again while an earlier callback remains alive. The coordinator also records the identity of the active candidate, so late completion from an expired attempt cannot clear or corrupt a newer candidate lease.

DB mutex acquisition, write-thread joining, memtable switching, and flush dispatch continue to happen outside registry and coordinator locks. The executor invokes the existing BackgroundCallWBMFlush path directly; actual immutable-memtable flushing still uses RocksDB normal flush infrastructure.

## Compatibility

This behavior is limited to kFlushLargestAcrossDBs. Existing policies retain their previous local flush behavior, and no WBM executor threads are started for them.

## Validation

Unit coverage exercises lease expiry, advancement to the next candidate, late completion, duplicate suppression, bounded worker capacity, policy changes with blocked callbacks, shutdown, and reranking after progress.

The end-to-end stack was also compared against the original local policy in one matched memory-pressure run with 1,000 DBs and 16 writers. The complete largest-across-DBs policy delivered 61.0% higher throughput, 55.5% fewer WBM flushes, 37.9% lower mean latency, 47.9% lower P99 latency, 5.17x larger average flushes, and 62.8% lower peak RSS. These measurements validate the full policy stack rather than isolating the performance contribution of this liveness follow-up.

Reviewed By: xingbowang

Differential Revision: D123461329

fbshipit-source-id: 4ad86102c2a43beb469f7672d722674dfbda9871
2026-10-07 14:47:58 -07:00
Ranjan Banerjee
0561153b73 Add configurable largest-memtable flush policies to WriteBufferManager (#15047)
Summary:
Motivation

A WriteBufferManager can be shared by many RocksDB instances and column families. Under the existing policy, the DB whose writer first observes memory pressure flushes its own oldest mutable memtable. That DB might own only a small fraction of the reclaimable memory, so workloads with many DBs or CFs can generate many small flushes while the largest memory consumer remains untouched. Scanning every registered DB while holding process-wide or DB mutexes would improve selection accuracy but would serialize unrelated write paths and is not viable for deployments with thousands of DBs.

Previous behavior

kFlushOldest was the only behavior: the write-group leader that noticed WBM pressure synchronously selected the oldest eligible mutable memtable in its own DB. The WBM had no per-DB view of reclaimable memory and could not direct reclamation to another DB sharing the same budget.

New behavior

This change adds configurable WriteBufferFlushPolicy modes:

- kFlushOldest preserves the existing behavior and remains the default.
- kFlushLargest selects the largest eligible flushable column family in the writing DB.
- kFlushLargestAcrossDBs selects the DB advertising the most reclaimable memory across all DBs sharing the WBM, then flushes its largest eligible CF. Atomic-flush DBs advertise and flush the aggregate eligible memory across their CFs.

High-level implementation

Each writable DB registers a lightweight FlushInitiator with the shared WBM. Per-DB accounting publishes two approximate values using atomics: total mutable memory and the largest flushable CF contribution, including eligible immutable memtables waiting for flush. Allocator reporting is batched, so the allocation hot path avoids registry scans and DB mutexes.

A dedicated WBM coordinator thread maintains an approximate ranked snapshot of registered DBs. Refreshes are driven by accounting changes, threshold crossings, and periodic pressure checks. Ranking and O(number of DBs) work happen on that coordinator thread; writers only update counters and signal the coordinator. Registration lifetime is protected independently so DB close can safely drain an in-flight handoff.

Threading and flush handoff

The coordinator reserves and pins one ranked candidate at a time, without holding a registry lock while invoking the DB. The target DB uses TryLock on its DB mutex and rejects the handoff if it is closing, paused, stopped, stalled, already handling a WBM job, or no longer has flushable memory. Rejected candidates do not block consideration of the next DB.

An accepted handoff queues one LOW-priority WBM job. The LOW worker joins the target DB write thread and revalidates eligibility before switching the memtable. The resulting ordinary flush is then scheduled through RocksDB's existing flush machinery on the HIGH-priority flush pool. Keeping the write-thread join off the requesting writer avoids making one DB's write path wait on another DB's mutex or write queue.

Only one manager-wide remote handoff is active at a time. Completion or cancellation clears the handoff and requests a rerank. If memory reaches the hard limit while remote coordination is delayed, a rate-limited local fallback lets a writer seal a local memtable to preserve forward progress. Write stalls, shutdown, WaitForCompact, policy changes, and DB deregistration explicitly drain or reject outstanding handoffs.

Compatibility

The legacy constructor and kFlushOldest behavior remain unchanged unless a new policy is explicitly selected. There are no on-disk format changes.

Pull Request resolved: https://github.com/facebook/rocksdb/pull/15047

Reviewed By: xingbowang

Differential Revision: D112396106

fbshipit-source-id: 3049adc7034dd4e00d74d7d86e1d19004292d299
2026-10-06 16:26:51 -07:00
Josh Kang
c2b86f3ec0 Lazily allocate MultiGet coroutine scratch buffers (#15298)
Summary:
Pull Request resolved: https://github.com/facebook/rocksdb/pull/15298

## Summary

BlockBasedTable::MultiGetCoroutine() embedded the synchronous 8 KiB scratch buffer in every coroutine frame, including cache-hit requests. The change uses zero coroutine stack capacity and allocates the required heap size only when I/O is needed, while preserving synchronous behavior.

## Benchmarks

| Variant | Coroutine frame allocation |
| Before | 21,048 bytes |
| After | 12,864 bytes |
| Change | -8,184 bytes (-38.9%) |

No API, format, or read-result changes.

Reviewed By: xingbowang

Differential Revision: D122810207

fbshipit-source-id: 003a8349b8da72de2eca2e62fb9f7b3d8802baed
2026-10-02 20:17:30 -07:00
Andrei Preda
507206e46b Fix stale readahead trim prefix on SeekToFirst (#15216)
Summary:
`BlockBasedTableIterator::SeekImpl()` sets
`seek_key_prefix_for_readahead_trimming_` only when given a seek key,
and `ResetBlockCacheLookupVar()` does not clear it. After a `Seek()`, a
`SeekToFirst()` on the same iterator trims readahead against the
previous seek key's prefix. `DBIter::SeekToFirst()` under
`prefix_same_as_start` takes its prefix from the first key found, so the
old prefix does not describe the keys being scanned.

With the stale prefix, `IsNextBlockOutOfReadaheadBound()` is true at
every block instead of only at the prefix boundary, and each prefetch is
clamped to the current block. The same predicate sets
`is_index_out_of_bound_`, which `FindBlockForward()` converts to
`is_out_of_bound_` and ends the scan. Under `ReadOptions::async_io` this
drops keys.

The bug needs `auto_readahead_size` and a preceding `Seek()` that reads
no data block. A `Seek()` that lands on a key leaves the prefetch buffer
anchored above the scan, and the trimming callback is not called. The
bug does not occur under `allow_mmap_reads`, where `FilePrefetchBuffer`
is constructed disabled.

The fix clears the prefix in `SeekToFirst()`, so prefix-based trimming
is disabled for that positioning. The `auto_readahead_size`
documentation in `include/rocksdb/options.h` already says prefix-based
trimming requires `Seek(key)`.

On buffered reads with `prefix_same_as_start`, `auto_readahead_size` and
`readahead_size=8192`, a cold-cache `SeekToFirst()` scan of 2M keys in a
single 222 MB file, preceded on the same iterator by a `Seek()` past the
last key, took 391 ms before and 308 ms after. The same scan with no
preceding `Seek()` takes 307 ms. Under direct IO on a local disk it went
from 33.1 s to 11.8 s. Data blocks read are unchanged; file reads drop
by 3x.

Also fixes a pre-existing test bug: `SeekParallelizationTestWithPosix`
asserts on `number_async_seek` without resetting that cumulative
thread-local, unlike its three siblings. The new tests move
`prefetch_test` from 11 shards to 13, so different tests share a
process, and the assertion fails at the parent commit under that
grouping.

Pull Request resolved: https://github.com/facebook/rocksdb/pull/15216

Test Plan:
New regression test in `PrefetchTrimReadaheadTestParam`, in sync and
`async_io` variants over the fixture's three `index_shortening` modes.
It runs two scans of the same keys from an equally cold block cache,
differing only in a preceding `Seek()`. Reverting the `clear()` fails 3
of 6 sync parameterizations on `READAHEAD_TRIMMED` (6 vs 40) and 3 of 6
`async_io` parameterizations on key count (40 vs 1).

`make check` and `ASSERT_STATUS_CHECKED=1 make check` show no new
failures. `prefetch_test` 122/122, `db_iterator_test` 249/249,
`table_test` 7629/7629, `block_based_table_reader_test` 5347/5347,
`db_basic_test` 300/300. New cases ran 1200 times under
`COERCE_CONTEXT_SWITCH=1` without failure.

Added db_stress coverage for `SeekToFirst()` after `Seek()` under
`prefix_same_as_start`. With the fix reverted and io_uring available,
the configuration in the second commit fails 8 of 8 seeds with
"Iterator diverged from control iterator"; with the fix, the same seeds
pass.

Reviewed By: rban1

Differential Revision: D120228466

Pulled By: xingbowang

fbshipit-source-id: a4935f03a0080cc8dd4c7a8c1438404e9b8f5c3a
2026-09-21 11:28:32 -07:00
Josh Kang
14ecf7f13c Route single-blob reads through BlobFetcher (#15046)
Summary:
Pull Request resolved: https://github.com/facebook/rocksdb/pull/15046

`BlobFetcher` is the policy boundary for single-blob reads, but
`Version::Get()` and primary direct-write postprocessing still called
lower-level backends directly. This duplicated backend selection and could
bypass future fetcher policy or decorators.

Route those paths through their existing `VersionBlobFetcher` and remove the
redundant Slice-based `Version::GetBlob()` overload. This is behavior-preserving:
each fetcher delegates to the same Version or direct-write backend with the same
`ReadOptions`, cache, and lifetime context.

Reviewed By: xingbowang

Differential Revision: D114616978

fbshipit-source-id: 0d94cc389138f27791de636e2cca585e51cb142a
2026-08-03 12:59:37 -07:00
Xingbo Wang
214869aacd Persist fault injection logs and fail fast on expected-state trace writes (#14651)
Summary:
- switch fault injection error recording from an in-memory ring buffer to per-run fixed-record binary logs under `TEST_TMPDIR/fault_injection_logs` (or `/tmp/fault_injection_logs`) so crash paths survive DB reopen cleanup
- keep the raw and decoded fault logs for external artifact collection/cleanup, and make `db_crashtest` print consistent blackbox/whitebox summaries after decoding
- make expected-state tracing fail fast on trace write failures and document offline trace inspection via `trace_analyzer`
- add coverage for binary log persistence/decoding/truncated-tail handling and keep info logs excluded from fault injection

Reviewed By: hx235

Differential Revision: D101973626

fbshipit-source-id: fdcb5b6370cf92a046e09b8d3391e80eecb66c23
2026-06-20 17:20:14 -07:00
Xingbo Wang
21723bbbef Add async WAL precreation
Summary:
- Add experimental immutable `DBOptions::async_wal_precreate` to reserve and open one future WAL on a background HIGH-priority task, with sanitization that disables the optimization when WAL recycling is configured.
- Split WAL creation into open/preallocate and start phases so `SwitchMemtable()` can consume a prepared WAL after writing normal WAL metadata, wait for in-flight precreation, fall back to synchronous creation, and delete an unstarted prepared WAL on start failure.
- Keep WAL numbering, close, recovery, and read-only open safe for empty future WAL files left by async precreation; `error_if_wal_file_exists=true` now rejects non-empty WALs while tolerating empty WALs.
- Add public option plumbing for the C API, options parsing/stringification, random option testing, `db_bench`, `db_stress`, and crash-test configuration.
- Add WAL precreate statistics counters plus Java `TickerType`/JNI mappings, and update C++, C, and Java read-only-open documentation for the empty-WAL behavior.
- Add focused WAL/option/C/Java tests for async precreate ready/wait/failure/recovery paths, read-only WAL detection, option sanitization, and API plumbing, plus write-flow docs and unreleased history entries for the new feature and behavior change.

PR https://github.com/facebook/rocksdb/pull/14738

Reviewed By: pdillinger

Differential Revision: D105020559

fbshipit-source-id: 5059b424702e021abb8de65ceeb6d3b975280ffc
2026-05-15 10:59:47 -07:00
Xingbo Wang
50852b5c8d db_stress: document expected-state trace/replay contract (#14612)
Summary:
- add a `docs/components/` landing page and a stress-test docs index
- document the `db_stress` expected-state trace/replay lifecycle, file invariants, and prefix-recovery contract in `expected_state_trace.md`
- align `db_stress` comments with the restore semantics: missing trace entries are fatal, while extra tail trace entries are tolerated
- keep the new docs tree trackable and point repo instructions at the new component-docs entrypoint

## Testing
- Not run (documentation and comment updates only)

Pull Request resolved: https://github.com/facebook/rocksdb/pull/14612

Reviewed By: joshkang97

Differential Revision: D100797173

Pulled By: xingbowang

fbshipit-source-id: 25be8c6239b9fdd84580818efe7520c371f9a46b
2026-04-14 09:58:20 -07:00
Xingbo Wang
24fac74206 docs: add end-to-end flow documentation (read_flow, write_flow) (#14486)
Summary:
Add comprehensive flow documentation tracing data through the full RocksDB system.

## Contents

### read_flow/ (11 chapters)
Get/MultiGet/Iterator paths through SuperVersion, MemTable, block cache, SST files (L0→Ln), bloom filters, range deletions, prefetch, async I/O.

### write_flow/ (10 chapters)
Put/Delete/Merge through WAL, MemTable, flush, compaction, delete cleanup, flow control, crash recovery, performance.

## Documentation Pattern
Each component follows a consistent structure:
- `index.md` — short overview (40-80 lines) with chapter table and key characteristics
- `NN_topic.md` — deep-dive chapters with source file references and workflow descriptions

All content validated against current codebase. No code snippets — refers to header files and struct/function names.

Part 1 of 11 in the RocksDB AI documentation series.

Pull Request resolved: https://github.com/facebook/rocksdb/pull/14486

Reviewed By: anand1976

Differential Revision: D97795679

Pulled By: xingbowang

fbshipit-source-id: 07c3be1a7f27e0a9cc1d82ccad16e8e4084f4ab0
2026-04-01 13:02:17 -07:00