mirror of
https://github.com/facebook/rocksdb.git
synced 2026-10-23 08:09:02 +03:00
Summary: This PR introduces **blob direct write v1**, a reduced-scope write-path optimization where large values (>= `min_blob_size`) are written directly to blob files during `Put()` and replaced in the memtable with compact `BlobIndex` references. This avoids holding full values in memory until flush time. ### Motivation In the existing BlobDB architecture, values are written to the WAL and memtable in their full form and separated into blob files only at flush time. This means: - Large values are held in memory twice (raw in memtable + blob file at flush) - Blob I/O is serialized through a single flush thread per column family Blob direct write addresses both: values leave the write path as small `BlobIndex` references, and multiple **partitions** (configurable via `blob_direct_write_partitions`) allow concurrent blob writes with independent locks. ### Design (v1 — single-writer, WAL-disabled, reduced scope) The v1 design intentionally keeps scope narrow for correctness and reviewability: - **Single writer thread assumption**: no concurrent writes to the same partition file. One logical writer serializes the batch. - **WAL-disabled**: direct-write blob files are only registered in MANIFEST at flush time. WAL replay cannot recover unregistered blob references, so WAL is disabled for this v1. - **Flush-on-write**: each `AddRecord` call flushes to the OS immediately. - **FIFO generation batching**: each memtable switch creates one generation batch. Direct-write files for that memtable are sealed and registered atomically when the batch is flushed to MANIFEST. - **Round-robin partitions**: blob writes are distributed across `blob_direct_write_partitions` files using an atomic counter. ### New components | Component | Description | |---|---| | `BlobFilePartitionManager` | Owns N partition files per CF. Manages open/seal/register lifecycle tied to memtable generations. | | `BlobWriteBatchTransformer` | A `WriteBatch::Handler` that rewrites qualifying `Put` values as `BlobIndex` entries before the batch enters the write group. | ### Write path integration 1. `DBImpl::WriteImpl` calls `BlobWriteBatchTransformer::TransformBatch` before entering the writer group (for default write path), or before joining the batch group (for pipelined/unordered write). 2. Values >= `min_blob_size` are written to a partition file; the key is stored with a `BlobIndex` in the transformed batch. A rollback guard marks blob bytes as initial garbage if the write fails. 3. On `SwitchMemtable`, `RotateCurrentGeneration` moves active partitions into the next immutable batch. 4. `FlushMemTableToOutputFile` / `AtomicFlushMemTablesToOutputFiles` call `PrepareFlushAdditions` to seal partition files and collect `BlobFileAddition` + `BlobFileGarbage` entries registered to MANIFEST alongside the flush. 5. Shutdown paths (`CancelAllBackgroundWork`, `WaitForCompact` with `close_db=true`) force-flush all CFs with active direct-write managers to ensure blob files are registered before close. ### Read path - **Get/MultiGet**: `MaybeResolveBlobForWritePath` resolves `BlobIndex` references found in memtable or immutable memtable via `BlobFilePartitionManager::ResolveBlobDirectWriteIndex`, which first checks manifest-visible state and falls back to direct blob-file reads via `BlobFileCache`. - **Iterator**: `DBIter::BlobReader` is extended with a `BlobFilePartitionManager*` to resolve direct-write blob indexes during iteration. The unified `ResolveBlobDirectWriteIndex` path handles both manifest-visible and not-yet-flushed files. ### New options | Option | Default | Description | |---|---|---| | `enable_blob_direct_write` | `false` | Enable write-path blob separation for this CF. Requires `enable_blob_files = true`. Not dynamically changeable. | | `blob_direct_write_partitions` | `1` | Number of parallel partition files per CF. Not dynamically changeable. | ### Feature incompatibilities (reduced v1 scope) The following features are *not supported* when `enable_blob_direct_write = true`, and are enforced both in `db_stress_tool` validation and `db_crashtest.py` sanitization: **Write model constraints:** - `threads` must be 1 (single writer assumption) - `allow_concurrent_memtable_write` = 0 - `enable_pipelined_write` = 0 (transformation done before batch group, but pipelined path supported with pre-transform) - `two_write_queues` = 0 - `unordered_write` = 0 (transformation done before batch group, but unordered path supported with pre-transform) **WAL and recovery:** - `disable_wal` = 1 (required — WAL replay of unregistered blob files is out of v1 scope) - `best_efforts_recovery` = 0 - `reopen` = 0 (no crash-restart with WAL replay) - All WAL-related stress features disabled: `manual_wal_flush_one_in`, `sync_wal_one_in`, `lock_wal_one_in`, `get_sorted_wal_files_one_in`, `get_current_wal_file_one_in`, `track_and_verify_wals`, `rate_limit_auto_wal_flush`, `recycle_log_file_num` **Blob GC and dynamic options:** - `use_blob_db` = 0 (stacked BlobDB not supported) - `allow_setting_blob_options_dynamically` = 0 - `enable_blob_garbage_collection` = 0 - `blob_compaction_readahead_size` = 0 - `blob_file_starting_level` = 0 **Unsupported value types and APIs:** - Merge (`use_merge`, `use_full_merge_v1`) — merge values pass through untransformed - Entity APIs (`use_put_entity_one_in`, `use_get_entity`, `use_multi_get_entity`, `use_attribute_group`) - `use_timed_put_one_in` - User-defined timestamps (`user_timestamp_size`, `persist_user_defined_timestamps`, `create_timestamped_snapshot_one_in`) - Transactions (`use_txn`, `use_optimistic_txn`, `test_multi_ops_txns`, `commit_bypass_memtable_one_in`) — though `WriteCommittedTxn::CommitInternal` falls back from bypass-memtable to normal path when BDW is active - `IngestWriteBatchWithIndex` returns `NotSupported` - `inplace_update_support` = 0 **Fault injection:** - All write/read/metadata fault injection disabled (`sync_fault_injection`, `write_fault_one_in`, `metadata_write_fault_one_in`, `read_fault_one_in`, `metadata_read_fault_one_in`, `open_*_fault_one_in`) **Infrastructure/snapshot APIs:** - `remote_compaction_worker_threads` = 0 - `test_secondary` = 0 - `backup_one_in` = 0 - `checkpoint_one_in` = 0 - `get_live_files_apis_one_in` = 0 - `ingest_external_file_one_in` = 0 - `ingest_wbwi_one_in` = 0 ### Tests - `db/blob/db_blob_basic_test.cc`: ~660 lines of new direct-write unit tests covering basic put/get, multi-partition, flush/compaction, recovery, and error injection. - `db/blob/blob_file_cache_test.cc`: ~96 lines of new tests for direct-write blob file cache behavior. - `db/write_batch_test.cc`: ~96 lines of tests for WriteBatch with blob index entries. - `utilities/transactions/transaction_test.cc`: verifies transaction commit path falls back correctly with direct write enabled. - `db_stress_tool/`: full stress test support with `--enable_blob_direct_write` and `--blob_direct_write_partitions` flags, integrated into `db_crashtest.py` with 10% random selection alongside regular blob params. Pull Request resolved: https://github.com/facebook/rocksdb/pull/14535 Test Plan: ``` make -j128 db_blob_basic_test && ./db_blob_basic_test make -j128 blob_file_cache_test && ./blob_file_cache_test make -j128 write_batch_test && ./write_batch_test make -j128 transaction_test && ./transaction_test make -j128 check ``` Stress test: ``` python3 tools/db_crashtest.py blackbox --enable_blob_direct_write=1 \ --enable_blob_files=1 --blob_direct_write_partitions=4 \ --disable_wal=1 --threads=1 ``` Reviewed By: pdillinger Differential Revision: D98766843 Pulled By: xingbowang fbshipit-source-id: 1577653826913a59d05680a87bce5534ac5a5e69
171 lines
6.8 KiB
C++
171 lines
6.8 KiB
C++
// Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
// This source code is licensed under both the GPLv2 (found in the
|
|
// COPYING file in the root directory) and Apache 2.0 License
|
|
// (found in the LICENSE.Apache file in the root directory).
|
|
|
|
#pragma once
|
|
|
|
#include <atomic>
|
|
#include <memory>
|
|
|
|
#include "rocksdb/rocksdb_namespace.h"
|
|
|
|
#if defined(__clang__)
|
|
#define ROCKSDB_SUPPRESS_SHARED_PTR_ATOMIC_DEPRECATION_PUSH \
|
|
_Pragma("clang diagnostic push") \
|
|
_Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
|
|
#define ROCKSDB_SUPPRESS_SHARED_PTR_ATOMIC_DEPRECATION_POP \
|
|
_Pragma("clang diagnostic pop")
|
|
#elif defined(__GNUC__)
|
|
#define ROCKSDB_SUPPRESS_SHARED_PTR_ATOMIC_DEPRECATION_PUSH \
|
|
_Pragma("GCC diagnostic push") \
|
|
_Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
|
|
#define ROCKSDB_SUPPRESS_SHARED_PTR_ATOMIC_DEPRECATION_POP \
|
|
_Pragma("GCC diagnostic pop")
|
|
#else
|
|
#define ROCKSDB_SUPPRESS_SHARED_PTR_ATOMIC_DEPRECATION_PUSH
|
|
#define ROCKSDB_SUPPRESS_SHARED_PTR_ATOMIC_DEPRECATION_POP
|
|
#endif
|
|
|
|
namespace ROCKSDB_NAMESPACE {
|
|
|
|
// Background:
|
|
// std::atomic is somewhat easy to misuse:
|
|
// * Implicit conversion to T makes it easy to use an unnecessarily strong
|
|
// memory ordering (std::memory_order_seq_cst) and to hide atomic operations
|
|
// that should be evident on reading the code.
|
|
// * Similarly, defaulting to std::memory_order_seq_cst for atomic operations
|
|
// makes it easy to use unnecessarily strong orderings. (It's always safe if
|
|
// some ordering is safe, but it's better to be intentional and thoughtful when
|
|
// carefully optimizing code with atomics.) Legitimate needs for seq_cst vs.
|
|
// acq_rel are rare, such as drawing inferences across two atomics in
|
|
// implementing hazard pointers.
|
|
// * It's easy to use nonsensical (UB) combinations like store with
|
|
// std::memory_order_acquire. Getting these right in development is an
|
|
// unnecessary cognitive overhead even if they are caught by UBSAN.
|
|
//
|
|
// For such reasons, we provide wrappers below to make clear and explicit
|
|
// usage of atomics easier.
|
|
|
|
// Wrapper around std::atomic for better code clarity (see Background above).
|
|
//
|
|
// This relaxed-only wrapper is intended for atomics that are not used to
|
|
// synchronize other data across threads (only the atomic data), so can always
|
|
// used relaxed memory ordering. For example, a cross-thread counter that never
|
|
// returns the same result can be a RelaxedAtomic.
|
|
template <typename T>
|
|
class RelaxedAtomic {
|
|
public:
|
|
explicit RelaxedAtomic(T initial = {}) : v_(initial) {}
|
|
void StoreRelaxed(T desired) { v_.store(desired, std::memory_order_relaxed); }
|
|
T LoadRelaxed() const { return v_.load(std::memory_order_relaxed); }
|
|
bool CasWeakRelaxed(T& expected, T desired) {
|
|
return v_.compare_exchange_weak(expected, desired,
|
|
std::memory_order_relaxed);
|
|
}
|
|
bool CasStrongRelaxed(T& expected, T desired) {
|
|
return v_.compare_exchange_strong(expected, desired,
|
|
std::memory_order_relaxed);
|
|
}
|
|
T ExchangeRelaxed(T desired) {
|
|
return v_.exchange(desired, std::memory_order_relaxed);
|
|
}
|
|
T FetchAddRelaxed(T operand) {
|
|
return v_.fetch_add(operand, std::memory_order_relaxed);
|
|
}
|
|
T FetchSubRelaxed(T operand) {
|
|
return v_.fetch_sub(operand, std::memory_order_relaxed);
|
|
}
|
|
T FetchAndRelaxed(T operand) {
|
|
return v_.fetch_and(operand, std::memory_order_relaxed);
|
|
}
|
|
T FetchOrRelaxed(T operand) {
|
|
return v_.fetch_or(operand, std::memory_order_relaxed);
|
|
}
|
|
T FetchXorRelaxed(T operand) {
|
|
return v_.fetch_xor(operand, std::memory_order_relaxed);
|
|
}
|
|
|
|
protected:
|
|
std::atomic<T> v_;
|
|
};
|
|
|
|
// A reasonably general-purpose wrapper around std::atomic for better code
|
|
// clarity (see Background above).
|
|
//
|
|
// Operations use std::memory_order_acq_rel by default (or just acquire or just
|
|
// release for read-only and write-only operations), but relaxed operations are
|
|
// also available and can be mixed in when appropriate.
|
|
//
|
|
// Future: add std::memory_order_seqcst variants like StoreSeqCst if/when
|
|
// there's a need for them (rare). No distinct type is needed because the
|
|
// distinction between acq_rel and seq_cst is more about where it is used in
|
|
// combination with other atomics than the atomic itself.
|
|
template <typename T>
|
|
class Atomic : public RelaxedAtomic<T> {
|
|
public:
|
|
explicit Atomic(T initial = {}) : RelaxedAtomic<T>(initial) {}
|
|
void Store(T desired) {
|
|
RelaxedAtomic<T>::v_.store(desired, std::memory_order_release);
|
|
}
|
|
T Load() const {
|
|
return RelaxedAtomic<T>::v_.load(std::memory_order_acquire);
|
|
}
|
|
bool CasWeak(T& expected, T desired) {
|
|
return RelaxedAtomic<T>::v_.compare_exchange_weak(
|
|
expected, desired, std::memory_order_acq_rel);
|
|
}
|
|
bool CasStrong(T& expected, T desired) {
|
|
return RelaxedAtomic<T>::v_.compare_exchange_strong(
|
|
expected, desired, std::memory_order_acq_rel);
|
|
}
|
|
T Exchange(T desired) {
|
|
return RelaxedAtomic<T>::v_.exchange(desired, std::memory_order_acq_rel);
|
|
}
|
|
T FetchAdd(T operand) {
|
|
return RelaxedAtomic<T>::v_.fetch_add(operand, std::memory_order_acq_rel);
|
|
}
|
|
T FetchSub(T operand) {
|
|
return RelaxedAtomic<T>::v_.fetch_sub(operand, std::memory_order_acq_rel);
|
|
}
|
|
T FetchAnd(T operand) {
|
|
return RelaxedAtomic<T>::v_.fetch_and(operand, std::memory_order_acq_rel);
|
|
}
|
|
T FetchOr(T operand) {
|
|
return RelaxedAtomic<T>::v_.fetch_or(operand, std::memory_order_acq_rel);
|
|
}
|
|
T FetchXor(T operand) {
|
|
return RelaxedAtomic<T>::v_.fetch_xor(operand, std::memory_order_acq_rel);
|
|
}
|
|
};
|
|
|
|
// Atomic shared_ptr helper wrappers.
|
|
//
|
|
// The C++20 replacement is std::atomic<std::shared_ptr<T>>, but the fbcode
|
|
// make build still uses a libstdc++ 11.x toolchain where that specialization
|
|
// is unavailable while the older free-function API is already deprecated.
|
|
// Centralize the workaround here so callers can keep a single code path until
|
|
// the build toolchain can support std::atomic<std::shared_ptr<T>> directly.
|
|
template <typename T>
|
|
inline std::shared_ptr<T> AtomicSharedPtrLoad(const std::shared_ptr<T>* ptr,
|
|
std::memory_order order) {
|
|
ROCKSDB_SUPPRESS_SHARED_PTR_ATOMIC_DEPRECATION_PUSH
|
|
auto result = std::atomic_load_explicit(ptr, order);
|
|
ROCKSDB_SUPPRESS_SHARED_PTR_ATOMIC_DEPRECATION_POP
|
|
return result;
|
|
}
|
|
|
|
template <typename T>
|
|
inline void AtomicSharedPtrStore(std::shared_ptr<T>* ptr,
|
|
std::shared_ptr<T> desired,
|
|
std::memory_order order) {
|
|
ROCKSDB_SUPPRESS_SHARED_PTR_ATOMIC_DEPRECATION_PUSH
|
|
std::atomic_store_explicit(ptr, std::move(desired), order);
|
|
ROCKSDB_SUPPRESS_SHARED_PTR_ATOMIC_DEPRECATION_POP
|
|
}
|
|
|
|
} // namespace ROCKSDB_NAMESPACE
|
|
|
|
#undef ROCKSDB_SUPPRESS_SHARED_PTR_ATOMIC_DEPRECATION_PUSH
|
|
#undef ROCKSDB_SUPPRESS_SHARED_PTR_ATOMIC_DEPRECATION_POP
|