mirror of
https://github.com/facebook/rocksdb.git
synced 2026-11-06 02:52:35 -05:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
596718ba99 | ||
|
|
c9ea61b64f | ||
|
|
75fab5932a | ||
|
|
b9938ebdc8 | ||
|
|
611ba9424e | ||
|
|
cb04d40d2d | ||
|
|
6b230bc705 | ||
|
|
0847b70a1f | ||
|
|
60a6488052 | ||
|
|
dd94499191 | ||
|
|
82e726286d | ||
|
|
662a4b978c | ||
|
|
7d98aa8db0 | ||
|
|
0bed170c19 | ||
|
|
7e0e3d01e2 | ||
|
|
695e06ac63 | ||
|
|
e4d7b59293 | ||
|
|
542ccfc6f7 | ||
|
|
3094950210 | ||
|
|
65c1b084b2 | ||
|
|
29005f0b02 | ||
|
|
d4cf4cbb99 | ||
|
|
c4936f26e8 | ||
|
|
39ae58b6a0 | ||
|
|
9054045c8f | ||
|
|
b385f2452c | ||
|
|
16886b7fba | ||
|
|
3d67b5e8e5 | ||
|
|
48589b961f | ||
|
|
552bc01669 | ||
|
|
0086809601 | ||
|
|
77a1d6eafb | ||
|
|
6afde14266 | ||
|
|
12d9386a4f | ||
|
|
f6cb763409 | ||
|
|
269478ee46 | ||
|
|
b927ba5936 | ||
|
|
32fc1e6cdc | ||
|
|
bf488c3052 | ||
|
|
548aabfe5f | ||
|
|
c1a97fe1f6 | ||
|
|
089070cb36 | ||
|
|
8acf17002a | ||
|
|
51b3b7e08c | ||
|
|
f42e70bf56 | ||
|
|
cfe0e0b037 | ||
|
|
44e4ffd60d | ||
|
|
ba5897ada8 | ||
|
|
20dbf51247 | ||
|
|
c90807d103 | ||
|
|
cc254efea6 | ||
|
|
920d72e6fa | ||
|
|
0dac75d542 | ||
|
|
5b5b011cdd | ||
|
|
6997a06c63 | ||
|
|
4196ad81e3 | ||
|
|
1a9b42bbdd | ||
|
|
60de713e15 | ||
|
|
99f8820054 | ||
|
|
1c6faf3587 | ||
|
|
cff6490bc4 | ||
|
|
051cad3867 | ||
|
|
68ce5d84f6 | ||
|
|
b050751f76 | ||
|
|
3ebf10e0ac | ||
|
|
ed913513bd | ||
|
|
c4a19ed399 | ||
|
|
1e2fd343bb | ||
|
|
e1fd348b92 | ||
|
|
f2b623bcc1 | ||
|
|
47e023abbd | ||
|
|
3c27f56d0b | ||
|
|
84d335b619 | ||
|
|
39a4ff2cab | ||
|
|
3285ba7a29 | ||
|
|
3db2cf113d | ||
|
|
4b79e8c003 | ||
|
|
ef3e289b2d | ||
|
|
9d71682d1b | ||
|
|
1e63fc9925 | ||
|
|
4b123f3a54 | ||
|
|
8fc78a3a9e | ||
|
|
694e49cbb1 | ||
|
|
760ea373a8 | ||
|
|
ed5b6c0d99 | ||
|
|
e67ee46642 | ||
|
|
05183bedcc | ||
|
|
195f35c08b | ||
|
|
137cd4bb75 | ||
|
|
458acf8169 | ||
|
|
3f54b9696c | ||
|
|
6a98471ae5 | ||
|
|
392d6957cd | ||
|
|
d01b1215bd | ||
|
|
f66df58b9e | ||
|
|
fe3405e80f | ||
|
|
9bd1a6fa29 | ||
|
|
bd6a8340c3 | ||
|
|
47be3ffffb | ||
|
|
83eb7b8c2c | ||
|
|
05daa12332 | ||
|
|
fc58c7c62a | ||
|
|
ea9a5b2914 | ||
|
|
c073c2edde | ||
|
|
4234a6a301 | ||
|
|
c1e6ffc40a | ||
|
|
e373685dab | ||
|
|
0b8b17a9d1 | ||
|
|
ecbeb305a0 | ||
|
|
f36394ff20 | ||
|
|
310a242c57 | ||
|
|
ba59751430 | ||
|
|
38e9e6903e | ||
|
|
6cbb104663 | ||
|
|
d3420464c3 | ||
|
|
6353c6e2fb | ||
|
|
451316597f | ||
|
|
bc448e9c89 | ||
|
|
f833ca3878 | ||
|
|
2b6bcfe590 | ||
|
|
1303573589 | ||
|
|
5e0584bd73 | ||
|
|
2a9f3b6cc5 | ||
|
|
4b53520709 | ||
|
|
4fa2c01719 | ||
|
|
03a74411c0 | ||
|
|
a9770b185d | ||
|
|
f53018c0c8 |
No files matched your search
+24
-20
@@ -16,7 +16,8 @@ commands:
|
||||
- run:
|
||||
name: Install JDK 8 on macos
|
||||
command: |
|
||||
brew install --cask adoptopenjdk/openjdk/adoptopenjdk8
|
||||
HOMEBREW_NO_AUTO_UPDATE=1 brew tap bell-sw/liberica
|
||||
HOMEBREW_NO_AUTO_UPDATE=1 brew install --cask liberica-jdk8
|
||||
|
||||
increase-max-open-files-on-macos:
|
||||
steps:
|
||||
@@ -205,25 +206,28 @@ executors:
|
||||
# $ docker run --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -it zjay437/rocksdb:0.5 bash
|
||||
# option `--cap-add=SYS_PTRACE --security-opt seccomp=unconfined` is used to enable gdb to attach an existing process
|
||||
- image: zjay437/rocksdb:0.6
|
||||
linux-java-docker:
|
||||
docker:
|
||||
- image: evolvedbinary/rocksjava:centos6_x64-be
|
||||
|
||||
jobs:
|
||||
build-macos:
|
||||
macos:
|
||||
xcode: 12.5.1
|
||||
resource_class: large
|
||||
xcode: 14.3.1
|
||||
resource_class: macos.m1.medium.gen1
|
||||
environment:
|
||||
ROCKSDB_DISABLE_JEMALLOC: 1 # jemalloc cause env_test hang, disable it for now
|
||||
steps:
|
||||
- increase-max-open-files-on-macos
|
||||
- install-gflags-on-macos
|
||||
- pre-steps-macos
|
||||
- run: ulimit -S -n `ulimit -H -n` && OPT=-DCIRCLECI make V=1 J=32 -j32 all
|
||||
- run: ulimit -S -n `ulimit -H -n` && OPT=-DCIRCLECI make V=1 J=16 -j16 all
|
||||
- post-steps
|
||||
|
||||
build-macos-cmake:
|
||||
macos:
|
||||
xcode: 12.5.1
|
||||
resource_class: large
|
||||
xcode: 14.3.1
|
||||
resource_class: macos.m1.medium.gen1
|
||||
parameters:
|
||||
run_even_tests:
|
||||
description: run even or odd tests, used to split tests to 2 groups
|
||||
@@ -239,20 +243,20 @@ jobs:
|
||||
command: ulimit -S -n `ulimit -H -n` && mkdir build && cd build && cmake -DWITH_GFLAGS=1 ..
|
||||
- run:
|
||||
name: "Build tests"
|
||||
command: cd build && make V=1 -j32
|
||||
command: cd build && make V=1 -j16
|
||||
- when:
|
||||
condition: << parameters.run_even_tests >>
|
||||
steps:
|
||||
- run:
|
||||
name: "Run even tests"
|
||||
command: ulimit -S -n `ulimit -H -n` && cd build && ctest -j32 -I 0,,2
|
||||
command: ulimit -S -n `ulimit -H -n` && cd build && ctest -j16 -I 0,,2
|
||||
- when:
|
||||
condition:
|
||||
not: << parameters.run_even_tests >>
|
||||
steps:
|
||||
- run:
|
||||
name: "Run odd tests"
|
||||
command: ulimit -S -n `ulimit -H -n` && cd build && ctest -j32 -I 1,,2
|
||||
command: ulimit -S -n `ulimit -H -n` && cd build && ctest -j16 -I 1,,2
|
||||
- post-steps
|
||||
|
||||
build-linux:
|
||||
@@ -589,7 +593,7 @@ jobs:
|
||||
- post-steps
|
||||
|
||||
build-linux-java-static:
|
||||
executor: linux-docker
|
||||
executor: linux-java-docker
|
||||
resource_class: large
|
||||
steps:
|
||||
- pre-steps
|
||||
@@ -602,15 +606,15 @@ jobs:
|
||||
which javac && javac -version
|
||||
- run:
|
||||
name: "Build RocksDBJava Static Library"
|
||||
command: make V=1 J=8 -j8 rocksdbjavastatic
|
||||
command: scl enable devtoolset-7 'make V=1 J=8 -j8 rocksdbjavastatic'
|
||||
- post-steps
|
||||
|
||||
build-macos-java:
|
||||
macos:
|
||||
xcode: 12.5.1
|
||||
resource_class: large
|
||||
xcode: 14.3.1
|
||||
resource_class: macos.m1.medium.gen1
|
||||
environment:
|
||||
JAVA_HOME: /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home
|
||||
JAVA_HOME: /Library/Java/JavaVirtualMachines/liberica-jdk-8.jdk/Contents/Home
|
||||
ROCKSDB_DISABLE_JEMALLOC: 1 # jemalloc causes java 8 crash
|
||||
steps:
|
||||
- increase-max-open-files-on-macos
|
||||
@@ -632,10 +636,10 @@ jobs:
|
||||
|
||||
build-macos-java-static:
|
||||
macos:
|
||||
xcode: 12.5.1
|
||||
resource_class: large
|
||||
xcode: 14.3.1
|
||||
resource_class: macos.m1.medium.gen1
|
||||
environment:
|
||||
JAVA_HOME: /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home
|
||||
JAVA_HOME: /Library/Java/JavaVirtualMachines/liberica-jdk-8.jdk/Contents/Home
|
||||
steps:
|
||||
- increase-max-open-files-on-macos
|
||||
- install-gflags-on-macos
|
||||
@@ -657,10 +661,10 @@ jobs:
|
||||
|
||||
build-macos-java-static-universal:
|
||||
macos:
|
||||
xcode: 12.5.1
|
||||
resource_class: large
|
||||
xcode: 14.3.1
|
||||
resource_class: macos.m1.medium.gen1
|
||||
environment:
|
||||
JAVA_HOME: /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home
|
||||
JAVA_HOME: /Library/Java/JavaVirtualMachines/liberica-jdk-8.jdk/Contents/Home
|
||||
steps:
|
||||
- increase-max-open-files-on-macos
|
||||
- install-gflags-on-macos
|
||||
|
||||
@@ -85,6 +85,7 @@ fbcode/
|
||||
fbcode
|
||||
buckifier/*.pyc
|
||||
buckifier/__pycache__
|
||||
.arcconfig
|
||||
|
||||
compile_commands.json
|
||||
clang-format-diff.py
|
||||
|
||||
+13
-9
@@ -254,7 +254,7 @@ if(CMAKE_SYSTEM_PROCESSOR MATCHES "loongarch64")
|
||||
endif(CMAKE_SYSTEM_PROCESSOR MATCHES "loongarch64")
|
||||
|
||||
set(PORTABLE 0 CACHE STRING "Minimum CPU arch to support, or 0 = current CPU, 1 = baseline CPU")
|
||||
if(PORTABLE STREQUAL 1)
|
||||
if(PORTABLE MATCHES "1|ON|YES|TRUE|Y")
|
||||
# Usually nothing to do; compiler default is typically the most general
|
||||
if(NOT MSVC)
|
||||
if(CMAKE_SYSTEM_PROCESSOR MATCHES "^s390x")
|
||||
@@ -264,14 +264,7 @@ if(PORTABLE STREQUAL 1)
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=loongarch64")
|
||||
endif()
|
||||
endif()
|
||||
elseif(PORTABLE MATCHES [^0]+)
|
||||
# Name of a CPU arch spec or feature set to require
|
||||
if(MSVC)
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /arch:${PORTABLE}")
|
||||
else()
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=${PORTABLE}")
|
||||
endif()
|
||||
else()
|
||||
elseif(PORTABLE MATCHES "0|OFF|NO|FALSE|N")
|
||||
if(MSVC)
|
||||
# NOTE: No auto-detection of current CPU, but instead assume some useful
|
||||
# level of optimization is supported
|
||||
@@ -285,6 +278,13 @@ else()
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=native")
|
||||
endif()
|
||||
endif()
|
||||
else()
|
||||
# Name of a CPU arch spec or feature set to require
|
||||
if(MSVC)
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /arch:${PORTABLE}")
|
||||
else()
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=${PORTABLE}")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
include(CheckCXXSourceCompiles)
|
||||
@@ -632,6 +632,7 @@ set(SOURCES
|
||||
cache/secondary_cache.cc
|
||||
cache/secondary_cache_adapter.cc
|
||||
cache/sharded_cache.cc
|
||||
cache/tiered_secondary_cache.cc
|
||||
db/arena_wrapped_db_iter.cc
|
||||
db/blob/blob_contents.cc
|
||||
db/blob/blob_fetcher.cc
|
||||
@@ -714,6 +715,7 @@ set(SOURCES
|
||||
db/wal_manager.cc
|
||||
db/wide/wide_column_serialization.cc
|
||||
db/wide/wide_columns.cc
|
||||
db/wide/wide_columns_helper.cc
|
||||
db/write_batch.cc
|
||||
db/write_batch_base.cc
|
||||
db/write_controller.cc
|
||||
@@ -1262,6 +1264,7 @@ if(WITH_TESTS)
|
||||
cache/cache_test.cc
|
||||
cache/compressed_secondary_cache_test.cc
|
||||
cache/lru_cache_test.cc
|
||||
cache/tiered_secondary_cache_test.cc
|
||||
db/blob/blob_counting_iterator_test.cc
|
||||
db/blob/blob_file_addition_test.cc
|
||||
db/blob/blob_file_builder_test.cc
|
||||
@@ -1357,6 +1360,7 @@ if(WITH_TESTS)
|
||||
db/wal_edit_test.cc
|
||||
db/wide/db_wide_basic_test.cc
|
||||
db/wide/wide_column_serialization_test.cc
|
||||
db/wide/wide_columns_helper_test.cc
|
||||
db/write_batch_test.cc
|
||||
db/write_callback_test.cc
|
||||
db/write_controller_test.cc
|
||||
|
||||
+89
@@ -1,6 +1,95 @@
|
||||
# Rocksdb Change Log
|
||||
> NOTE: Entries for next release do not go here. Follow instructions in `unreleased_history/README.txt`
|
||||
|
||||
## 8.7.3 (10/30/2023)
|
||||
### Behavior Changes
|
||||
* Deleting stale files upon recovery are delegated to SstFileManger if available so they can be rate limited.
|
||||
|
||||
## 8.7.2 (10/25/2023)
|
||||
### Public API Changes
|
||||
* Add new Cache APIs GetSecondaryCacheCapacity() and GetSecondaryCachePinnedUsage() to return the configured capacity, and cache reservation charged to the secondary cache.
|
||||
|
||||
### Bug Fixes
|
||||
* Fixed a possible underflow when computing the compressed secondary cache share of memory reservations while updating the compressed secondary to total block cache ratio.
|
||||
* Fix an assertion failure when UpdeteTieredCache() is called in an idempotent manner.
|
||||
|
||||
## 8.7.1 (10/20/2023)
|
||||
### Bug Fixes
|
||||
* Fix a bug in auto_readahead_size where first_internal_key of index blocks wasn't copied properly resulting in corruption error when first_internal_key was used for comparison.
|
||||
* Add bounds check in WBWIIteratorImpl and make BaseDeltaIterator, WriteUnpreparedTxn and WritePreparedTxn respect the upper bound and lower bound in ReadOption. See 11680.
|
||||
|
||||
## 8.7.0 (09/22/2023)
|
||||
### New Features
|
||||
* Added an experimental new "automatic" variant of HyperClockCache that does not require a prior estimate of the average size of cache entries. This variant is activated when HyperClockCacheOptions::estimated\_entry\_charge = 0 and has essentially the same concurrency benefits as the existing HyperClockCache.
|
||||
* Add a new statistic `COMPACTION_CPU_TOTAL_TIME` that records cumulative compaction cpu time. This ticker is updated regularly while a compaction is running.
|
||||
* Add `GetEntity()` API for ReadOnly DB and Secondary DB.
|
||||
* Add a new iterator API `Iterator::Refresh(const Snapshot *)` that allows iterator to be refreshed while using the input snapshot to read.
|
||||
* Added a new read option `merge_operand_count_threshold`. When the number of merge operands applied during a successful point lookup exceeds this threshold, the query will return a special OK status with a new subcode `kMergeOperandThresholdExceeded`. Applications might use this signal to take action to reduce the number of merge operands for the affected key(s), for example by running a compaction.
|
||||
* For `NewRibbonFilterPolicy()`, made the `bloom_before_level` option mutable through the Configurable interface and the SetOptions API, allowing dynamic switching between all-Bloom and all-Ribbon configurations, and configurations in between. See comments on `NewRibbonFilterPolicy()`
|
||||
* RocksDB now allows the block cache to be stacked on top of a compressed secondary cache and a non-volatile secondary cache, thus creating a three-tier cache. To set it up, use the `NewTieredCache()` API in rocksdb/cache.h..
|
||||
* Added a new wide-column aware full merge API called `FullMergeV3` to `MergeOperator`. `FullMergeV3` supports wide columns both as base value and merge result, which enables the application to perform more general transformations during merges. For backward compatibility, the default implementation implements the earlier logic of applying the merge operation to the default column of any wide-column entities. Specifically, if there is no base value or the base value is a plain key-value, the default implementation falls back to `FullMergeV2`. If the base value is a wide-column entity, the default implementation invokes `FullMergeV2` to perform the merge on the default column, and leaves any other columns unchanged.
|
||||
* Add wide column support to ldb commands (scan, dump, idump, dump_wal) and sst_dump tool's scan command
|
||||
|
||||
### Public API Changes
|
||||
* Expose more information about input files used in table creation (if any) in `CompactionFilter::Context`. See `CompactionFilter::Context::input_start_level`,`CompactionFilter::Context::input_table_properties` for more.
|
||||
* `Options::compaction_readahead_size` 's default value is changed from 0 to 2MB.
|
||||
* When using LZ4 compression, the `acceleration` parameter is configurable by setting the negated value in `CompressionOptions::level`. For example, `CompressionOptions::level=-10` will set `acceleration=10`
|
||||
* The `NewTieredCache` API has been changed to take the total cache capacity (inclusive of both the primary and the compressed secondary cache) and the ratio of total capacity to allocate to the compressed cache. These are specified in `TieredCacheOptions`. Any capacity specified in `LRUCacheOptions`, `HyperClockCacheOptions` and `CompressedSecondaryCacheOptions` is ignored. A new API, `UpdateTieredCache` is provided to dynamically update the total capacity, ratio of compressed cache, and admission policy.
|
||||
* The `NewTieredVolatileCache()` API in rocksdb/cache.h has been renamed to `NewTieredCache()`.
|
||||
|
||||
### Behavior Changes
|
||||
* Compaction read performance will regress when `Options::compaction_readahead_size` is explicitly set to 0
|
||||
* Universal size amp compaction will conditionally exclude some of the newest L0 files when selecting input with a small negative impact to size amp. This is to prevent a large number of L0 files from being locked by a size amp compaction, potentially leading to write stop with a few more flushes.
|
||||
* Change ldb scan command delimiter from ':' to '==>'.
|
||||
* For non direct IO, eliminate the file system prefetching attempt for compaction read when `Options::compaction_readahead_size` is 0
|
||||
|
||||
### Bug Fixes
|
||||
* Fix a bug where if there is an error reading from offset 0 of a file from L1+ and that the file is not the first file in the sorted run, data can be lost in compaction and read/scan can return incorrect results.
|
||||
* Fix a bug where iterator may return incorrect result for DeleteRange() users if there was an error reading from a file.
|
||||
* Fix a bug with atomic_flush=true that can cause DB to stuck after a flush fails (#11872).
|
||||
* Fix a bug where RocksDB (with atomic_flush=false) can delete output SST files of pending flushes when a previous concurrent flush fails (#11865). This can result in DB entering read-only state with error message like `IO error: No such file or directory: While open a file for random read: /tmp/rocksdbtest-501/db_flush_test_87732_4230653031040984171/000013.sst`.
|
||||
* Fix an assertion fault during seek with async_io when readahead trimming is enabled.
|
||||
* When the compressed secondary cache capacity is reduced to 0, it should be completely disabled. Before this fix, inserts and lookups would still go to the backing `LRUCache` before returning, thus incurring locking overhead. With this fix, inserts and lookups are no-ops and do not add any overhead.
|
||||
* Updating the tiered cache (cache allocated using NewTieredCache()) by calling SetCapacity() on it was not working properly. The initial creation would set the primary cache capacity to the combined primary and compressed secondary cache capacity. But SetCapacity() would just set the primary cache capacity. With this fix, the user always specifies the total budget and compressed secondary cache ratio on creation. Subsequently, SetCapacity() will distribute the new capacity across the two caches by the same ratio.
|
||||
* Fixed a bug in `MultiGet` for cleaning up SuperVersion acquired with locking db mutex.
|
||||
* Fix a bug where row cache can falsely return kNotFound even though row cache entry is hit.
|
||||
* Fixed a race condition in `GenericRateLimiter` that could cause it to stop granting requests
|
||||
* Fix a bug (Issue #10257) where DB can hang after write stall since no compaction is scheduled (#11764).
|
||||
* Add a fix for async_io where during seek, when reading a block for seeking a target key in a file without any readahead, the iterator aligned the read on a page boundary and reading more than necessary. This increased the storage read bandwidth usage.
|
||||
* Fix an issue in sst dump tool to handle bounds specified for data with user-defined timestamps.
|
||||
* When auto_readahead_size is enabled, update readahead upper bound during readahead trimming when reseek changes iterate_upper_bound dynamically.
|
||||
* Fixed a bug where `rocksdb.file.read.verify.file.checksums.micros` is not populated
|
||||
* Fixed a bug where compaction read under non direct IO still falls back to RocksDB internal prefetching after file system's prefetching returns non-OK status other than `Status::NotSupported()`
|
||||
|
||||
### Performance Improvements
|
||||
* Added additional improvements in tuning readahead_size during Scans when auto_readahead_size is enabled. However it's not recommended for backward scans and might impact the performance. More details in options.h.
|
||||
* During async_io, the Seek happens in 2 phases. Phase 1 starts an asynchronous read on a block cache miss, and phase 2 waits for it to complete and finishes the seek. In both phases, it tries to lookup the block cache for the data block first before looking in the prefetch buffer. It's optimized by doing the block cache lookup only in the first phase that would save some CPU.
|
||||
|
||||
## 8.6.0 (08/18/2023)
|
||||
### New Features
|
||||
* Added enhanced data integrity checking on SST files with new format_version=6. Performance impact is very small or negligible. Previously if SST data was misplaced or re-arranged by the storage layer, it could pass block checksum with higher than 1 in 4 billion probability. With format_version=6, block checksums depend on what file they are in and location within the file. This way, misplaced SST data is no more likely to pass checksum verification than randomly corrupted data. Also in format_version=6, SST footers are checksum-protected.
|
||||
* Add a new feature to trim readahead_size during scans upto upper_bound when iterate_upper_bound is specified. It's enabled through ReadOptions.auto_readahead_size. Users must also specify ReadOptions.iterate_upper_bound.
|
||||
* RocksDB will compare the number of input keys to the number of keys processed after each compaction. Compaction will fail and report Corruption status if the verification fails. Option `compaction_verify_record_count` is introduced for this purpose and is enabled by default.
|
||||
* Add a CF option `bottommost_file_compaction_delay` to allow specifying the delay of bottommost level single-file compactions.
|
||||
* Add support to allow enabling / disabling user-defined timestamps feature for an existing column family in combination with the in-Memtable only feature.
|
||||
* Implement a new admission policy for the compressed secondary cache that admits blocks evicted from the primary cache with the hit bit set. This policy can be specified in TieredVolatileCacheOptions by setting the newly added adm_policy option.
|
||||
* Add a column family option `memtable_max_range_deletions` that limits the number of range deletions in a memtable. RocksDB will try to do an automatic flush after the limit is reached. (#11358)
|
||||
* Add PutEntity API in sst_file_writer
|
||||
* Add `timeout` in microsecond option to `WaitForCompactOptions` to allow timely termination of prolonged waiting in scenarios like recurring recoverable errors, such as out-of-space situations and continuous write streams that sustain ongoing flush and compactions
|
||||
* New statistics `rocksdb.file.read.{get|multiget|db.iterator|verify.checksum|verify.file.checksums}.micros` measure read time of block-based SST tables or blob files during db open, `Get()`, `MultiGet()`, using db iterator, `VerifyFileChecksums()` and `VerifyChecksum()`. They require stats level greater than `StatsLevel::kExceptDetailedTimers`.
|
||||
* Add close_db option to `WaitForCompactOptions` to call Close() after waiting is done.
|
||||
* Add a new compression option `CompressionOptions::checksum` for enabling ZSTD's checksum feature to detect corruption during decompression.
|
||||
|
||||
### Public API Changes
|
||||
* Mark `Options::access_hint_on_compaction_start` related APIs as deprecated. See #11631 for alternative behavior.
|
||||
|
||||
### Behavior Changes
|
||||
* Statistics `rocksdb.sst.read.micros` now includes time spent on multi read and async read into the file
|
||||
* For Universal Compaction users, periodic compaction (option `periodic_compaction_seconds`) will be set to 30 days by default if block based table is used.
|
||||
|
||||
### Bug Fixes
|
||||
* Fix a bug in FileTTLBooster that can cause users with a large number of levels (more than 65) to see errors like "runtime error: shift exponent .. is too large.." (#11673).
|
||||
|
||||
## 8.5.0 (07/21/2023)
|
||||
### Public API Changes
|
||||
* Removed recently added APIs `GeneralCache` and `MakeSharedGeneralCache()` as our plan changed to stop exposing a general-purpose cache interface. The old forms of these APIs, `Cache` and `NewLRUCache()`, are still available, although general-purpose caching support will be dropped eventually.
|
||||
|
||||
@@ -1885,6 +1885,9 @@ compressed_secondary_cache_test: $(OBJ_DIR)/cache/compressed_secondary_cache_tes
|
||||
lru_cache_test: $(OBJ_DIR)/cache/lru_cache_test.o $(TEST_LIBRARY) $(LIBRARY)
|
||||
$(AM_LINK)
|
||||
|
||||
tiered_secondary_cache_test: $(OBJ_DIR)/cache/tiered_secondary_cache_test.o $(TEST_LIBRARY) $(LIBRARY)
|
||||
$(AM_LINK)
|
||||
|
||||
range_del_aggregator_test: $(OBJ_DIR)/db/range_del_aggregator_test.o $(TEST_LIBRARY) $(LIBRARY)
|
||||
$(AM_LINK)
|
||||
|
||||
@@ -1984,6 +1987,9 @@ cache_reservation_manager_test: $(OBJ_DIR)/cache/cache_reservation_manager_test.
|
||||
wide_column_serialization_test: $(OBJ_DIR)/db/wide/wide_column_serialization_test.o $(TEST_LIBRARY) $(LIBRARY)
|
||||
$(AM_LINK)
|
||||
|
||||
wide_columns_helper_test: $(OBJ_DIR)/db/wide/wide_columns_helper_test.o $(TEST_LIBRARY) $(LIBRARY)
|
||||
$(AM_LINK)
|
||||
|
||||
#-------------------------------------------------
|
||||
# make install related stuff
|
||||
PREFIX ?= /usr/local
|
||||
@@ -2088,8 +2094,8 @@ ROCKSDB_JAVADOCS_JAR = rocksdbjni-$(ROCKSDB_JAVA_VERSION)-javadoc.jar
|
||||
ROCKSDB_SOURCES_JAR = rocksdbjni-$(ROCKSDB_JAVA_VERSION)-sources.jar
|
||||
SHA256_CMD = sha256sum
|
||||
|
||||
ZLIB_VER ?= 1.2.13
|
||||
ZLIB_SHA256 ?= b3a24de97a8fdbc835b9833169501030b8977031bcb54b3b3ac13740f846ab30
|
||||
ZLIB_VER ?= 1.3
|
||||
ZLIB_SHA256 ?= ff0ba4c292013dbc27530b3a81e1f9a813cd39de01ca5e0f8bf355702efa593e
|
||||
ZLIB_DOWNLOAD_BASE ?= http://zlib.net
|
||||
BZIP2_VER ?= 1.0.8
|
||||
BZIP2_SHA256 ?= ab5a03176ee106d3f0fa90e381da478ddae405918153cca248e682cd0c4a2269
|
||||
@@ -2097,11 +2103,11 @@ BZIP2_DOWNLOAD_BASE ?= http://sourceware.org/pub/bzip2
|
||||
SNAPPY_VER ?= 1.1.8
|
||||
SNAPPY_SHA256 ?= 16b677f07832a612b0836178db7f374e414f94657c138e6993cbfc5dcc58651f
|
||||
SNAPPY_DOWNLOAD_BASE ?= https://github.com/google/snappy/archive
|
||||
LZ4_VER ?= 1.9.3
|
||||
LZ4_SHA256 ?= 030644df4611007ff7dc962d981f390361e6c97a34e5cbc393ddfbe019ffe2c1
|
||||
LZ4_VER ?= 1.9.4
|
||||
LZ4_SHA256 ?= 0b0e3aa07c8c063ddf40b082bdf7e37a1562bda40a0ff5272957f3e987e0e54b
|
||||
LZ4_DOWNLOAD_BASE ?= https://github.com/lz4/lz4/archive
|
||||
ZSTD_VER ?= 1.4.9
|
||||
ZSTD_SHA256 ?= acf714d98e3db7b876e5b540cbf6dee298f60eb3c0723104f6d3f065cd60d6a8
|
||||
ZSTD_VER ?= 1.5.5
|
||||
ZSTD_SHA256 ?= 98e9c3d949d1b924e28e01eccb7deed865eefebf25c2f21c702e5cd5b63b85e1
|
||||
ZSTD_DOWNLOAD_BASE ?= https://github.com/facebook/zstd/archive
|
||||
CURL_SSL_OPTS ?= --tlsv1
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ cpp_library_wrapper(name="rocksdb_lib", srcs=[
|
||||
"cache/secondary_cache.cc",
|
||||
"cache/secondary_cache_adapter.cc",
|
||||
"cache/sharded_cache.cc",
|
||||
"cache/tiered_secondary_cache.cc",
|
||||
"db/arena_wrapped_db_iter.cc",
|
||||
"db/blob/blob_contents.cc",
|
||||
"db/blob/blob_fetcher.cc",
|
||||
@@ -103,6 +104,7 @@ cpp_library_wrapper(name="rocksdb_lib", srcs=[
|
||||
"db/wal_manager.cc",
|
||||
"db/wide/wide_column_serialization.cc",
|
||||
"db/wide/wide_columns.cc",
|
||||
"db/wide/wide_columns_helper.cc",
|
||||
"db/write_batch.cc",
|
||||
"db/write_batch_base.cc",
|
||||
"db/write_controller.cc",
|
||||
@@ -5474,6 +5476,12 @@ cpp_unittest_wrapper(name="tiered_compaction_test",
|
||||
extra_compiler_flags=[])
|
||||
|
||||
|
||||
cpp_unittest_wrapper(name="tiered_secondary_cache_test",
|
||||
srcs=["cache/tiered_secondary_cache_test.cc"],
|
||||
deps=[":rocksdb_test_lib"],
|
||||
extra_compiler_flags=[])
|
||||
|
||||
|
||||
cpp_unittest_wrapper(name="timer_queue_test",
|
||||
srcs=["util/timer_queue_test.cc"],
|
||||
deps=[":rocksdb_test_lib"],
|
||||
@@ -5552,6 +5560,12 @@ cpp_unittest_wrapper(name="wide_column_serialization_test",
|
||||
extra_compiler_flags=[])
|
||||
|
||||
|
||||
cpp_unittest_wrapper(name="wide_columns_helper_test",
|
||||
srcs=["db/wide/wide_columns_helper_test.cc"],
|
||||
deps=[":rocksdb_test_lib"],
|
||||
extra_compiler_flags=[])
|
||||
|
||||
|
||||
cpp_unittest_wrapper(name="work_queue_test",
|
||||
srcs=["util/work_queue_test.cc"],
|
||||
deps=[":rocksdb_test_lib"],
|
||||
|
||||
@@ -161,5 +161,9 @@ LzLabs is using RocksDB as a storage engine in their multi-database distributed
|
||||
## Solana Labs
|
||||
[Solana](https://github.com/solana-labs/solana) is a fast, secure, scalable, and decentralized blockchain. It uses RocksDB as the underlying storage for its ledger store.
|
||||
|
||||
## Apache Kvrocks
|
||||
|
||||
[Apache Kvrocks](https://github.com/apache/kvrocks) is an open-source distributed key-value NoSQL database built on top of RocksDB. It serves as a cost-saving and capacity-increasing alternative drop-in replacement for Redis.
|
||||
|
||||
## Others
|
||||
More databases using RocksDB can be found at [dbdb.io](https://dbdb.io/browse?embeds=rocksdb).
|
||||
@@ -23,7 +23,7 @@ def pretty_list(lst, indent=8):
|
||||
return res
|
||||
|
||||
|
||||
class TARGETSBuilder(object):
|
||||
class TARGETSBuilder:
|
||||
def __init__(self, path, extra_argv):
|
||||
self.path = path
|
||||
header = targets_cfg.rocksdb_target_header_template.format(
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ import sys
|
||||
import time
|
||||
|
||||
|
||||
class ColorString(object):
|
||||
class ColorString:
|
||||
"""Generate colorful strings on terminal"""
|
||||
|
||||
HEADER = "\033[95m"
|
||||
|
||||
@@ -674,7 +674,7 @@ else
|
||||
fi
|
||||
|
||||
if [[ "${PLATFORM}" == "OS_MACOSX" ]]; then
|
||||
# For portability compile for macOS 10.14 or newer
|
||||
# For portability compile for macOS 10.14 (2018) or newer
|
||||
COMMON_FLAGS="$COMMON_FLAGS -mmacosx-version-min=10.14"
|
||||
PLATFORM_LDFLAGS="$PLATFORM_LDFLAGS -mmacosx-version-min=10.14"
|
||||
# -mmacosx-version-min must come first here.
|
||||
|
||||
@@ -15,7 +15,7 @@ import re
|
||||
import sys
|
||||
|
||||
|
||||
class ErrorParserBase(object):
|
||||
class ErrorParserBase:
|
||||
def parse_error(self, line):
|
||||
"""Parses a line of test output. If it contains an error, returns a
|
||||
formatted message describing the error; otherwise, returns None.
|
||||
|
||||
Vendored
+35
@@ -66,6 +66,41 @@ static std::unordered_map<std::string, OptionTypeInfo>
|
||||
OptionTypeFlags::kMutable}},
|
||||
};
|
||||
|
||||
namespace {
|
||||
static void NoopDelete(Cache::ObjectPtr /*obj*/,
|
||||
MemoryAllocator* /*allocator*/) {
|
||||
assert(false);
|
||||
}
|
||||
|
||||
static size_t SliceSize(Cache::ObjectPtr obj) {
|
||||
return static_cast<Slice*>(obj)->size();
|
||||
}
|
||||
|
||||
static Status SliceSaveTo(Cache::ObjectPtr from_obj, size_t from_offset,
|
||||
size_t length, char* out) {
|
||||
const Slice& slice = *static_cast<Slice*>(from_obj);
|
||||
std::memcpy(out, slice.data() + from_offset, length);
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
static Status NoopCreate(const Slice& /*data*/, CompressionType /*type*/,
|
||||
CacheTier /*source*/, Cache::CreateContext* /*ctx*/,
|
||||
MemoryAllocator* /*allocator*/,
|
||||
Cache::ObjectPtr* /*out_obj*/,
|
||||
size_t* /*out_charge*/) {
|
||||
assert(false);
|
||||
return Status::NotSupported();
|
||||
}
|
||||
|
||||
static Cache::CacheItemHelper kBasicCacheItemHelper(CacheEntryRole::kMisc,
|
||||
&NoopDelete);
|
||||
} // namespace
|
||||
|
||||
const Cache::CacheItemHelper kSliceCacheItemHelper{
|
||||
CacheEntryRole::kMisc, &NoopDelete, &SliceSize,
|
||||
&SliceSaveTo, &NoopCreate, &kBasicCacheItemHelper,
|
||||
};
|
||||
|
||||
Status SecondaryCache::CreateFromString(
|
||||
const ConfigOptions& config_options, const std::string& value,
|
||||
std::shared_ptr<SecondaryCache>* result) {
|
||||
|
||||
Vendored
+74
-15
@@ -3,7 +3,6 @@
|
||||
// COPYING file in the root directory) and Apache 2.0 License
|
||||
// (found in the LICENSE.Apache file in the root directory).
|
||||
|
||||
#include "cache_key.h"
|
||||
#ifdef GFLAGS
|
||||
#include <cinttypes>
|
||||
#include <cstddef>
|
||||
@@ -13,9 +12,12 @@
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
|
||||
#include "cache/cache_key.h"
|
||||
#include "cache/sharded_cache.h"
|
||||
#include "db/db_impl/db_impl.h"
|
||||
#include "monitoring/histogram.h"
|
||||
#include "port/port.h"
|
||||
#include "port/stack_trace.h"
|
||||
#include "rocksdb/advanced_cache.h"
|
||||
#include "rocksdb/convenience.h"
|
||||
#include "rocksdb/db.h"
|
||||
@@ -44,7 +46,8 @@ static constexpr uint64_t GiB = MiB << 10;
|
||||
DEFINE_uint32(threads, 16, "Number of concurrent threads to run.");
|
||||
DEFINE_uint64(cache_size, 1 * GiB,
|
||||
"Number of bytes to use as a cache of uncompressed data.");
|
||||
DEFINE_uint32(num_shard_bits, 6, "shard_bits.");
|
||||
DEFINE_int32(num_shard_bits, -1,
|
||||
"ShardedCacheOptions::shard_bits. Default = auto");
|
||||
|
||||
DEFINE_double(resident_ratio, 0.25,
|
||||
"Ratio of keys fitting in cache to keyspace.");
|
||||
@@ -54,6 +57,9 @@ DEFINE_uint32(value_bytes_estimate, 0,
|
||||
"If > 0, overrides estimated_entry_charge or "
|
||||
"min_avg_entry_charge depending on cache_type.");
|
||||
|
||||
DEFINE_int32(
|
||||
degenerate_hash_bits, 0,
|
||||
"With HCC, fix this many hash bits to increase table hash collisions");
|
||||
DEFINE_uint32(skew, 5, "Degree of skew in key selection. 0 = no skew");
|
||||
DEFINE_bool(populate_cache, true, "Populate cache before operations");
|
||||
|
||||
@@ -76,6 +82,8 @@ DEFINE_uint32(
|
||||
DEFINE_uint32(gather_stats_entries_per_lock, 256,
|
||||
"For Cache::ApplyToAllEntries");
|
||||
|
||||
DEFINE_uint32(usleep, 0, "Sleep up to this many microseconds after each op.");
|
||||
|
||||
DEFINE_bool(lean, false,
|
||||
"If true, no additional computation is performed besides cache "
|
||||
"operations.");
|
||||
@@ -97,6 +105,17 @@ static class std::shared_ptr<ROCKSDB_NAMESPACE::SecondaryCache> secondary_cache;
|
||||
|
||||
DEFINE_string(cache_type, "lru_cache", "Type of block cache.");
|
||||
|
||||
DEFINE_bool(use_jemalloc_no_dump_allocator, false,
|
||||
"Whether to use JemallocNoDumpAllocator");
|
||||
|
||||
DEFINE_uint32(jemalloc_no_dump_allocator_num_arenas,
|
||||
ROCKSDB_NAMESPACE::JemallocAllocatorOptions().num_arenas,
|
||||
"JemallocNodumpAllocator::num_arenas");
|
||||
|
||||
DEFINE_bool(jemalloc_no_dump_allocator_limit_tcache_size,
|
||||
ROCKSDB_NAMESPACE::JemallocAllocatorOptions().limit_tcache_size,
|
||||
"JemallocNodumpAllocator::limit_tcache_size");
|
||||
|
||||
// ## BEGIN stress_cache_key sub-tool options ##
|
||||
// See class StressCacheKey below.
|
||||
DEFINE_bool(stress_cache_key, false,
|
||||
@@ -226,6 +245,20 @@ struct KeyGen {
|
||||
raw = std::min(raw, rnd.Next());
|
||||
}
|
||||
uint64_t key = FastRange64(raw, max_key);
|
||||
if (FLAGS_degenerate_hash_bits) {
|
||||
uint64_t key_hash =
|
||||
Hash64(reinterpret_cast<const char*>(&key), sizeof(key));
|
||||
// HCC uses the high 64 bits and a lower bit mask for starting probe
|
||||
// location, so we fix hash bits starting at the bottom of that word.
|
||||
auto hi_hash = uint64_t{0x9e3779b97f4a7c13U} ^
|
||||
(key_hash << 1 << (FLAGS_degenerate_hash_bits - 1));
|
||||
uint64_t un_hi, un_lo;
|
||||
BijectiveUnhash2x64(hi_hash, key_hash, &un_hi, &un_lo);
|
||||
un_lo ^= BitwiseAnd(FLAGS_seed, INT32_MAX);
|
||||
EncodeFixed64(key_data, un_lo);
|
||||
EncodeFixed64(key_data + 8, un_hi);
|
||||
return Slice(key_data, kCacheKeySize);
|
||||
}
|
||||
// Variable size and alignment
|
||||
size_t off = key % 8;
|
||||
key_data[0] = char{42};
|
||||
@@ -239,8 +272,8 @@ struct KeyGen {
|
||||
}
|
||||
};
|
||||
|
||||
Cache::ObjectPtr createValue(Random64& rnd) {
|
||||
char* rv = new char[FLAGS_value_bytes];
|
||||
Cache::ObjectPtr createValue(Random64& rnd, MemoryAllocator* alloc) {
|
||||
char* rv = AllocateBlock(FLAGS_value_bytes, alloc).release();
|
||||
// Fill with some filler data, and take some CPU time
|
||||
for (uint32_t i = 0; i < FLAGS_value_bytes; i += 8) {
|
||||
EncodeFixed64(rv + i, rnd.Next());
|
||||
@@ -257,7 +290,8 @@ Status SaveToFn(Cache::ObjectPtr from_obj, size_t /*from_offset*/,
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status CreateFn(const Slice& data, Cache::CreateContext* /*context*/,
|
||||
Status CreateFn(const Slice& data, CompressionType /*type*/,
|
||||
CacheTier /*source*/, Cache::CreateContext* /*context*/,
|
||||
MemoryAllocator* /*allocator*/, Cache::ObjectPtr* out_obj,
|
||||
size_t* out_charge) {
|
||||
*out_obj = new char[data.size()];
|
||||
@@ -266,8 +300,8 @@ Status CreateFn(const Slice& data, Cache::CreateContext* /*context*/,
|
||||
return Status::OK();
|
||||
};
|
||||
|
||||
void DeleteFn(Cache::ObjectPtr value, MemoryAllocator* /*alloc*/) {
|
||||
delete[] static_cast<char*>(value);
|
||||
void DeleteFn(Cache::ObjectPtr value, MemoryAllocator* alloc) {
|
||||
CustomDeleter{alloc}(static_cast<char*>(value));
|
||||
}
|
||||
|
||||
Cache::CacheItemHelper helper1_wos(CacheEntryRole::kDataBlock, DeleteFn);
|
||||
@@ -302,6 +336,15 @@ class CacheBench {
|
||||
exit(1);
|
||||
}
|
||||
|
||||
std::shared_ptr<MemoryAllocator> allocator;
|
||||
if (FLAGS_use_jemalloc_no_dump_allocator) {
|
||||
JemallocAllocatorOptions opts;
|
||||
opts.num_arenas = FLAGS_jemalloc_no_dump_allocator_num_arenas;
|
||||
opts.limit_tcache_size =
|
||||
FLAGS_jemalloc_no_dump_allocator_limit_tcache_size;
|
||||
Status s = NewJemallocNodumpAllocator(opts, &allocator);
|
||||
assert(s.ok());
|
||||
}
|
||||
if (FLAGS_cache_type == "clock_cache") {
|
||||
fprintf(stderr, "Old clock cache implementation has been removed.\n");
|
||||
exit(1);
|
||||
@@ -309,6 +352,7 @@ class CacheBench {
|
||||
HyperClockCacheOptions opts(
|
||||
FLAGS_cache_size, /*estimated_entry_charge=*/0, FLAGS_num_shard_bits);
|
||||
opts.hash_seed = BitwiseAnd(FLAGS_seed, INT32_MAX);
|
||||
opts.memory_allocator = allocator;
|
||||
if (FLAGS_cache_type == "fixed_hyper_clock_cache" ||
|
||||
FLAGS_cache_type == "hyper_clock_cache") {
|
||||
opts.estimated_entry_charge = FLAGS_value_bytes_estimate > 0
|
||||
@@ -319,7 +363,7 @@ class CacheBench {
|
||||
opts.min_avg_entry_charge = FLAGS_value_bytes_estimate;
|
||||
}
|
||||
} else {
|
||||
fprintf(stderr, "Cache type not supported.");
|
||||
fprintf(stderr, "Cache type not supported.\n");
|
||||
exit(1);
|
||||
}
|
||||
cache_ = opts.MakeSharedCache();
|
||||
@@ -328,6 +372,7 @@ class CacheBench {
|
||||
false /* strict_capacity_limit */,
|
||||
0.5 /* high_pri_pool_ratio */);
|
||||
opts.hash_seed = BitwiseAnd(FLAGS_seed, INT32_MAX);
|
||||
opts.memory_allocator = allocator;
|
||||
if (!FLAGS_secondary_cache_uri.empty()) {
|
||||
Status s = SecondaryCache::CreateFromString(
|
||||
ConfigOptions(), FLAGS_secondary_cache_uri, &secondary_cache);
|
||||
@@ -343,7 +388,7 @@ class CacheBench {
|
||||
|
||||
cache_ = NewLRUCache(opts);
|
||||
} else {
|
||||
fprintf(stderr, "Cache type not supported.");
|
||||
fprintf(stderr, "Cache type not supported.\n");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
@@ -373,7 +418,8 @@ class CacheBench {
|
||||
keys_since_last_not_found = 0;
|
||||
|
||||
Status s =
|
||||
cache_->Insert(key, createValue(rnd), &helper1, FLAGS_value_bytes);
|
||||
cache_->Insert(key, createValue(rnd, cache_->memory_allocator()),
|
||||
&helper1, FLAGS_value_bytes);
|
||||
assert(s.ok());
|
||||
|
||||
handle = cache_->Lookup(key);
|
||||
@@ -610,6 +656,7 @@ class CacheBench {
|
||||
const auto clock = SystemClock::Default().get();
|
||||
uint64_t start_time = clock->NowMicros();
|
||||
StopWatchNano timer(clock);
|
||||
auto system_clock = SystemClock::Default();
|
||||
|
||||
for (uint64_t i = 0; i < FLAGS_ops_per_thread; i++) {
|
||||
Slice key = gen.GetRand(thread->rnd, max_key_, FLAGS_skew);
|
||||
@@ -637,8 +684,9 @@ class CacheBench {
|
||||
} else {
|
||||
++lookup_misses;
|
||||
// do insert
|
||||
Status s = cache_->Insert(key, createValue(thread->rnd), &helper2,
|
||||
FLAGS_value_bytes, &handle);
|
||||
Status s = cache_->Insert(
|
||||
key, createValue(thread->rnd, cache_->memory_allocator()),
|
||||
&helper2, FLAGS_value_bytes, &handle);
|
||||
assert(s.ok());
|
||||
}
|
||||
} else if (random_op < insert_threshold_) {
|
||||
@@ -647,8 +695,9 @@ class CacheBench {
|
||||
handle = nullptr;
|
||||
}
|
||||
// do insert
|
||||
Status s = cache_->Insert(key, createValue(thread->rnd), &helper3,
|
||||
FLAGS_value_bytes, &handle);
|
||||
Status s = cache_->Insert(
|
||||
key, createValue(thread->rnd, cache_->memory_allocator()), &helper3,
|
||||
FLAGS_value_bytes, &handle);
|
||||
assert(s.ok());
|
||||
} else if (random_op < lookup_threshold_) {
|
||||
if (handle) {
|
||||
@@ -679,6 +728,13 @@ class CacheBench {
|
||||
thread->latency_ns_hist.Add(timer.ElapsedNanos());
|
||||
}
|
||||
thread->shared->AddLookupStats(lookup_hits, lookup_misses);
|
||||
if (FLAGS_usleep > 0) {
|
||||
unsigned us =
|
||||
static_cast<unsigned>(thread->rnd.Uniform(FLAGS_usleep + 1));
|
||||
if (us > 0) {
|
||||
system_clock->SleepForMicroseconds(us);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (FLAGS_early_exit) {
|
||||
MutexLock l(thread->shared->GetMutex());
|
||||
@@ -712,7 +768,9 @@ class CacheBench {
|
||||
printf("Ops per thread : %" PRIu64 "\n", FLAGS_ops_per_thread);
|
||||
printf("Cache size : %s\n",
|
||||
BytesToHumanString(FLAGS_cache_size).c_str());
|
||||
printf("Num shard bits : %u\n", FLAGS_num_shard_bits);
|
||||
printf("Num shard bits : %d\n",
|
||||
static_cast_with_check<ShardedCacheBase>(cache_.get())
|
||||
->GetNumShardBits());
|
||||
printf("Max key : %" PRIu64 "\n", max_key_);
|
||||
printf("Resident ratio : %g\n", FLAGS_resident_ratio);
|
||||
printf("Skew degree : %u\n", FLAGS_skew);
|
||||
@@ -1032,6 +1090,7 @@ class StressCacheKey {
|
||||
};
|
||||
|
||||
int cache_bench_tool(int argc, char** argv) {
|
||||
ROCKSDB_NAMESPACE::port::InstallStackTraceHandler();
|
||||
ParseCommandLineFlags(&argc, &argv, true);
|
||||
|
||||
if (FLAGS_stress_cache_key) {
|
||||
|
||||
Vendored
+2
-1
@@ -25,7 +25,8 @@ Status WarmInCache(Cache* cache, const Slice& key, const Slice& saved,
|
||||
assert(helper->create_cb);
|
||||
Cache::ObjectPtr value;
|
||||
size_t charge;
|
||||
Status st = helper->create_cb(saved, create_context,
|
||||
Status st = helper->create_cb(saved, CompressionType::kNoCompression,
|
||||
CacheTier::kVolatileTier, create_context,
|
||||
cache->memory_allocator(), &value, &charge);
|
||||
if (st.ok()) {
|
||||
st =
|
||||
|
||||
Vendored
+4
-3
@@ -273,9 +273,10 @@ class ConcurrentCacheReservationManager
|
||||
std::size_t total_mem_used = cache_res_mgr_->GetTotalMemoryUsed();
|
||||
Status s;
|
||||
if (!increase) {
|
||||
assert(total_mem_used >= memory_used_delta);
|
||||
s = cache_res_mgr_->UpdateCacheReservation(total_mem_used -
|
||||
memory_used_delta);
|
||||
s = cache_res_mgr_->UpdateCacheReservation(
|
||||
(total_mem_used > memory_used_delta)
|
||||
? (total_mem_used - memory_used_delta)
|
||||
: 0);
|
||||
} else {
|
||||
s = cache_res_mgr_->UpdateCacheReservation(total_mem_used +
|
||||
memory_used_delta);
|
||||
|
||||
Vendored
+16
-4
@@ -175,7 +175,7 @@ class LRUCacheTest : public CacheTest {};
|
||||
TEST_P(CacheTest, UsageTest) {
|
||||
// cache is std::shared_ptr and will be automatically cleaned up.
|
||||
const size_t kCapacity = 100000;
|
||||
auto cache = NewCache(kCapacity, 8, false, kDontChargeCacheMetadata);
|
||||
auto cache = NewCache(kCapacity, 6, false, kDontChargeCacheMetadata);
|
||||
auto precise_cache = NewCache(kCapacity, 0, false, kFullChargeCacheMetadata);
|
||||
ASSERT_EQ(0, cache->GetUsage());
|
||||
size_t baseline_meta_usage = precise_cache->GetUsage();
|
||||
@@ -193,9 +193,13 @@ TEST_P(CacheTest, UsageTest) {
|
||||
ASSERT_OK(precise_cache->Insert(key, value, &kDumbHelper, kv_size));
|
||||
usage += kv_size;
|
||||
ASSERT_EQ(usage, cache->GetUsage());
|
||||
if (IsHyperClock()) {
|
||||
if (GetParam() == kFixedHyperClock) {
|
||||
ASSERT_EQ(baseline_meta_usage + usage, precise_cache->GetUsage());
|
||||
} else {
|
||||
// AutoHyperClockCache meta usage grows in proportion to lifetime
|
||||
// max number of entries. LRUCache in proportion to resident number of
|
||||
// entries, though there is an untracked component proportional to
|
||||
// lifetime max number of entries.
|
||||
ASSERT_LT(usage, precise_cache->GetUsage());
|
||||
}
|
||||
}
|
||||
@@ -203,7 +207,11 @@ TEST_P(CacheTest, UsageTest) {
|
||||
cache->EraseUnRefEntries();
|
||||
precise_cache->EraseUnRefEntries();
|
||||
ASSERT_EQ(0, cache->GetUsage());
|
||||
ASSERT_EQ(baseline_meta_usage, precise_cache->GetUsage());
|
||||
if (GetParam() != kAutoHyperClock) {
|
||||
// NOTE: AutoHyperClockCache meta usage grows in proportion to lifetime
|
||||
// max number of entries.
|
||||
ASSERT_EQ(baseline_meta_usage, precise_cache->GetUsage());
|
||||
}
|
||||
|
||||
// make sure the cache will be overloaded
|
||||
for (size_t i = 1; i < kCapacity; ++i) {
|
||||
@@ -318,7 +326,11 @@ TEST_P(CacheTest, PinnedUsageTest) {
|
||||
cache->EraseUnRefEntries();
|
||||
precise_cache->EraseUnRefEntries();
|
||||
ASSERT_EQ(0, cache->GetUsage());
|
||||
ASSERT_EQ(baseline_meta_usage, precise_cache->GetUsage());
|
||||
if (GetParam() != kAutoHyperClock) {
|
||||
// NOTE: AutoHyperClockCache meta usage grows in proportion to lifetime
|
||||
// max number of entries.
|
||||
ASSERT_EQ(baseline_meta_usage, precise_cache->GetUsage());
|
||||
}
|
||||
}
|
||||
|
||||
TEST_P(CacheTest, HitAndMiss) {
|
||||
|
||||
Vendored
+4
-2
@@ -19,8 +19,10 @@ ChargedCache::ChargedCache(std::shared_ptr<Cache> cache,
|
||||
|
||||
Status ChargedCache::Insert(const Slice& key, ObjectPtr obj,
|
||||
const CacheItemHelper* helper, size_t charge,
|
||||
Handle** handle, Priority priority) {
|
||||
Status s = target_->Insert(key, obj, helper, charge, handle, priority);
|
||||
Handle** handle, Priority priority,
|
||||
const Slice& compressed_val, CompressionType type) {
|
||||
Status s = target_->Insert(key, obj, helper, charge, handle, priority,
|
||||
compressed_val, type);
|
||||
if (s.ok()) {
|
||||
// Insert may cause the cache entry eviction if the cache is full. So we
|
||||
// directly call the reservation manager to update the total memory used
|
||||
|
||||
Vendored
+5
-3
@@ -22,9 +22,11 @@ class ChargedCache : public CacheWrapper {
|
||||
ChargedCache(std::shared_ptr<Cache> cache,
|
||||
std::shared_ptr<Cache> block_cache);
|
||||
|
||||
Status Insert(const Slice& key, ObjectPtr obj, const CacheItemHelper* helper,
|
||||
size_t charge, Handle** handle = nullptr,
|
||||
Priority priority = Priority::LOW) override;
|
||||
Status Insert(
|
||||
const Slice& key, ObjectPtr obj, const CacheItemHelper* helper,
|
||||
size_t charge, Handle** handle = nullptr,
|
||||
Priority priority = Priority::LOW, const Slice& compressed_val = Slice(),
|
||||
CompressionType type = CompressionType::kNoCompression) override;
|
||||
|
||||
Cache::Handle* Lookup(const Slice& key, const CacheItemHelper* helper,
|
||||
CreateContext* create_context,
|
||||
|
||||
Vendored
+1992
-14
File diff suppressed because it is too large.
Load diff
Vendored
+349
-23
@@ -20,6 +20,7 @@
|
||||
#include "cache/sharded_cache.h"
|
||||
#include "port/lang.h"
|
||||
#include "port/malloc.h"
|
||||
#include "port/mmap.h"
|
||||
#include "port/port.h"
|
||||
#include "rocksdb/cache.h"
|
||||
#include "rocksdb/secondary_cache.h"
|
||||
@@ -39,24 +40,31 @@ class ClockCacheTest;
|
||||
//
|
||||
// Benefits
|
||||
// --------
|
||||
// * Fully lock free (no waits or spins) for efficiency under high concurrency
|
||||
// * Lock/wait free (no waits or spins) for efficiency under high concurrency
|
||||
// * Fixed version (estimated_entry_charge > 0) is fully lock/wait free
|
||||
// * Automatic version (estimated_entry_charge = 0) has rare waits among
|
||||
// certain insertion or erase operations that involve the same very small
|
||||
// set of entries.
|
||||
// * Optimized for hot path reads. For concurrency control, most Lookup() and
|
||||
// essentially all Release() are a single atomic add operation.
|
||||
// * Eviction on insertion is fully parallel and lock-free.
|
||||
// * Eviction on insertion is fully parallel.
|
||||
// * Uses a generalized + aging variant of CLOCK eviction that might outperform
|
||||
// LRU in some cases. (For background, see
|
||||
// https://en.wikipedia.org/wiki/Page_replacement_algorithm)
|
||||
//
|
||||
// Costs
|
||||
// -----
|
||||
// * Hash table is not resizable (for lock-free efficiency) so capacity is not
|
||||
// dynamically changeable. Rely on an estimated average value (block) size for
|
||||
// * FixedHyperClockCache (estimated_entry_charge > 0) - Hash table is not
|
||||
// resizable (for lock-free efficiency) so capacity is not dynamically
|
||||
// changeable. Rely on an estimated average value (block) size for
|
||||
// space+time efficiency. (See estimated_entry_charge option details.)
|
||||
// EXPERIMENTAL - This limitation is fixed in AutoHyperClockCache, activated
|
||||
// with estimated_entry_charge == 0.
|
||||
// * Insert usually does not (but might) overwrite a previous entry associated
|
||||
// with a cache key. This is OK for RocksDB uses of Cache.
|
||||
// with a cache key. This is OK for RocksDB uses of Cache, though it does mess
|
||||
// up our REDUNDANT block cache insertion statistics.
|
||||
// * Only supports keys of exactly 16 bytes, which is what RocksDB uses for
|
||||
// block cache (not row cache or table cache).
|
||||
// * SecondaryCache is not supported.
|
||||
// block cache (but not row cache or table cache).
|
||||
// * Cache priorities are less aggressively enforced. Unlike LRUCache, enough
|
||||
// transient LOW or BOTTOM priority items can evict HIGH priority entries that
|
||||
// are not referenced recently (or often) enough.
|
||||
@@ -139,7 +147,8 @@ class ClockCacheTest;
|
||||
// * Empty - slot is not in use and unowned. All other metadata and data is
|
||||
// in an undefined state.
|
||||
// * Construction - slot is exclusively owned by one thread, the thread
|
||||
// successfully entering this state, for populating or freeing data.
|
||||
// successfully entering this state, for populating or freeing data
|
||||
// (de-construction, same state marker).
|
||||
// * Shareable (group) - slot holds an entry with counted references for
|
||||
// pinning and reading, including
|
||||
// * Visible - slot holds an entry that can be returned by Lookup
|
||||
@@ -187,15 +196,19 @@ class ClockCacheTest;
|
||||
// know from our "redundant" stats that overwrites are very rare for the block
|
||||
// cache, so we should not spend much to make them effective.
|
||||
//
|
||||
// So instead we Insert as soon as we find an empty slot in the probing
|
||||
// sequence without seeing an existing (visible) entry for the same key. This
|
||||
// way we only insert if we can improve the probing performance, and we don't
|
||||
// need to probe beyond our insert position, assuming we are willing to let
|
||||
// the previous entry for the same key die of old age (eventual eviction from
|
||||
// not being used). We can reach a similar state with concurrent insertions,
|
||||
// where one will pass over the other while it is "under construction."
|
||||
// This temporary duplication is acceptable for RocksDB block cache because
|
||||
// we know redundant insertion is rare.
|
||||
// FixedHyperClockCache: Instead we Insert as soon as we find an empty slot in
|
||||
// the probing sequence without seeing an existing (visible) entry for the same
|
||||
// key. This way we only insert if we can improve the probing performance, and
|
||||
// we don't need to probe beyond our insert position, assuming we are willing
|
||||
// to let the previous entry for the same key die of old age (eventual eviction
|
||||
// from not being used). We can reach a similar state with concurrent
|
||||
// insertions, where one will pass over the other while it is "under
|
||||
// construction." This temporary duplication is acceptable for RocksDB block
|
||||
// cache because we know redundant insertion is rare.
|
||||
// AutoHyperClockCache: Similar, except we only notice and return an existing
|
||||
// match if it is found in the search for a suitable empty slot (starting with
|
||||
// the same slot as the head pointer), not by following the existing chain of
|
||||
// entries. Insertions are always made to the head of the chain.
|
||||
//
|
||||
// Another problem to solve is what to return to the caller when we find an
|
||||
// existing entry whose probing position we cannot improve on, or when the
|
||||
@@ -322,7 +335,6 @@ struct ClockHandle : public ClockHandleBasicData {
|
||||
// For setting the hit bit
|
||||
static constexpr uint8_t kHitBitShift = 2U * kCounterNumBits;
|
||||
static constexpr uint64_t kHitBitMask = uint64_t{1} << kHitBitShift;
|
||||
;
|
||||
|
||||
// For reading or updating the state marker in meta word
|
||||
static constexpr uint8_t kStateShift = kHitBitShift + 1;
|
||||
@@ -395,6 +407,8 @@ class BaseClockTable {
|
||||
|
||||
uint32_t GetHashSeed() const { return hash_seed_; }
|
||||
|
||||
uint64_t GetYieldCount() const { return yield_count_.load(); }
|
||||
|
||||
struct EvictionData {
|
||||
size_t freed_charge = 0;
|
||||
size_t freed_count = 0;
|
||||
@@ -448,6 +462,9 @@ class BaseClockTable {
|
||||
// Clock algorithm sweep pointer.
|
||||
std::atomic<uint64_t> clock_pointer_{};
|
||||
|
||||
// Counter for number of times we yield to wait on another thread.
|
||||
std::atomic<uint64_t> yield_count_{};
|
||||
|
||||
// TODO: is this separation needed if we don't do background evictions?
|
||||
ALIGN_AS(CACHE_LINE_SIZE)
|
||||
// Number of elements in the table.
|
||||
@@ -472,6 +489,10 @@ class BaseClockTable {
|
||||
const uint32_t& hash_seed_;
|
||||
};
|
||||
|
||||
// Hash table for cache entries with size determined at creation time.
|
||||
// Uses open addressing and double hashing. Since entries cannot be moved,
|
||||
// the "displacements" count ensures probing sequences find entries even when
|
||||
// entries earlier in the probing sequence have been removed.
|
||||
class FixedHyperClockTable : public BaseClockTable {
|
||||
public:
|
||||
// Target size to be exactly a common cache line size (see static_assert in
|
||||
@@ -626,11 +647,314 @@ class FixedHyperClockTable : public BaseClockTable {
|
||||
const std::unique_ptr<HandleImpl[]> array_;
|
||||
}; // class FixedHyperClockTable
|
||||
|
||||
// Placeholder for future automatic table variant
|
||||
// For now, just use FixedHyperClockTable.
|
||||
class AutoHyperClockTable : public FixedHyperClockTable {
|
||||
// Hash table for cache entries that resizes automatically based on occupancy.
|
||||
// However, it depends on a contiguous memory region to grow into
|
||||
// incrementally, using linear hashing, so uses an anonymous mmap so that
|
||||
// only the used portion of the memory region is mapped to physical memory
|
||||
// (part of RSS).
|
||||
//
|
||||
// This table implementation uses the same "low-level protocol" for managing
|
||||
// the contens of an entry slot as FixedHyperClockTable does, captured in the
|
||||
// ClockHandle struct. The provides most of the essential data safety, but
|
||||
// AutoHyperClockTable is another "high-level protocol" for organizing entries
|
||||
// into a hash table, with automatic resizing.
|
||||
//
|
||||
// This implementation is not fully wait-free but we can call it "essentially
|
||||
// wait-free," and here's why. First, like FixedHyperClockCache, there is no
|
||||
// locking nor other forms of waiting at the cache or shard level. Also like
|
||||
// FixedHCC there is essentially an entry-level read-write lock implemented
|
||||
// with atomics, but our relaxed atomicity/consistency guarantees (e.g.
|
||||
// duplicate inserts are possible) mean we do not need to wait for entry
|
||||
// locking. Lookups, non-erasing Releases, and non-evicting non-growing Inserts
|
||||
// are all fully wait-free. Of course, these waits are not dependent on any
|
||||
// external factors such as I/O.
|
||||
//
|
||||
// For operations that remove entries from a chain or grow the table by
|
||||
// splitting a chain, there is a chain-level locking mechanism that we call a
|
||||
// "rewrite" lock, and the only waits are for these locks. On average, each
|
||||
// chain lock is relevant to < 2 entries each. (The average would be less than
|
||||
// one entry each, but we do not lock when there's no entry to remove or
|
||||
// migrate.) And a given thread can only hold two such chain locks at a time,
|
||||
// more typically just one. So in that sense alone, the waiting that does exist
|
||||
// is very localized.
|
||||
//
|
||||
// If we look closer at the operations utilizing that locking mechanism, we
|
||||
// can see why it's "essentially wait-free."
|
||||
// * Grow operations to increase the size of the table: each operation splits
|
||||
// an existing chain into two, and chains for splitting are chosen in table
|
||||
// order. Grow operations are fully parallel except for the chain locking, but
|
||||
// for one Grow operation to wait on another, it has to be feeding into the
|
||||
// other, which means the table has doubled in size already from other Grow
|
||||
// operations without the original one finishing. So Grow operations are very
|
||||
// low latency (unlike LRUCache doubling the table size in one operation) and
|
||||
// very parallelizeable. (We use some tricks to break up dependencies in
|
||||
// updating metadata on the usable size of the table.) And obviously Grow
|
||||
// operations are very rare after the initial population of the table.
|
||||
// * Evict operations (part of many Inserts): clock updates and evictions
|
||||
// sweep through the structure in table order, so like Grow operations,
|
||||
// parallel Evict can only wait on each other if an Evict has lingered (slept)
|
||||
// long enough that the clock pointer has wrapped around the entire structure.
|
||||
// * Random erasures (Erase, Release with erase_if_last_ref, etc.): these
|
||||
// operations are rare and not really considered performance critical.
|
||||
// Currently they're mostly used for removing placeholder cache entries, e.g.
|
||||
// for memory tracking, though that could use standalone entries instead to
|
||||
// avoid potential contention in table operations. It's possible that future
|
||||
// enhancements could pro-actively remove cache entries from obsolete files,
|
||||
// but that's not yet implemented.
|
||||
class AutoHyperClockTable : public BaseClockTable {
|
||||
public:
|
||||
using FixedHyperClockTable::FixedHyperClockTable;
|
||||
// Target size to be exactly a common cache line size (see static_assert in
|
||||
// clock_cache.cc)
|
||||
struct ALIGN_AS(64U) HandleImpl : public ClockHandle {
|
||||
// To orgainize AutoHyperClockTable entries into a hash table while
|
||||
// allowing the table size to grow without existing entries being moved,
|
||||
// a version of chaining is used. Rather than being heap allocated (and
|
||||
// incurring overheads to ensure memory safety) entries must go into
|
||||
// Handles ("slots") in the pre-allocated array. To improve CPU cache
|
||||
// locality, the chain head pointers are interleved with the entries;
|
||||
// specifically, a Handle contains
|
||||
// * A head pointer for a chain of entries with this "home" location.
|
||||
// * A ClockHandle, for an entry that may or may not be in the chain
|
||||
// starting from that head (but for performance ideally is on that
|
||||
// chain).
|
||||
// * A next pointer for the continuation of the chain containing this
|
||||
// entry.
|
||||
//
|
||||
// The pointers are not raw pointers, but are indices into the array,
|
||||
// and are decorated in two ways to help detect and recover from
|
||||
// relevant concurrent modifications during Lookup, so that Lookup is
|
||||
// fully wait-free:
|
||||
// * Each "with_shift" pointer contains a shift count that indicates
|
||||
// how many hash bits were used in chosing the home address for the
|
||||
// chain--specifically the next entry in the chain.
|
||||
// * The end of a chain is given a special "end" marker and refers back
|
||||
// to the head of the chain.
|
||||
//
|
||||
// Why do we need shift on each pointer? To make Lookup wait-free, we need
|
||||
// to be able to query a chain without missing anything, and preferably
|
||||
// avoid synchronously double-checking the length_info. Without the shifts,
|
||||
// there is a risk that we start down a chain and while paused on an entry
|
||||
// that goes to a new home, we then follow the rest of the
|
||||
// partially-migrated chain to see the shared ending with the old home, but
|
||||
// for a time were following the chain for the new home, missing some
|
||||
// entries for the old home.
|
||||
//
|
||||
// Why do we need the end of the chain to loop back? If Lookup pauses
|
||||
// at an "under construction" entry, and sees that "next" is null after
|
||||
// waking up, we need something to tell whether the "under construction"
|
||||
// entry was freed and reused for another chain. Otherwise, we could
|
||||
// miss entries still on the original chain due in the presence of a
|
||||
// concurrent modification. Until an entry is fully erased from a chain,
|
||||
// it is normal to see "under construction" entries on the chain, and it
|
||||
// is not safe to read their hashed key without either a read reference
|
||||
// on the entry or a rewrite lock on the chain.
|
||||
|
||||
// Marker in a "with_shift" head pointer for some thread owning writes
|
||||
// to the chain structure (except for inserts), but only if not an
|
||||
// "end" pointer. Also called the "rewrite lock."
|
||||
static constexpr uint64_t kHeadLocked = uint64_t{1} << 7;
|
||||
|
||||
// Marker in a "with_shift" pointer for the end of a chain. Must also
|
||||
// point back to the head of the chain (with end marker removed).
|
||||
// Also includes the "locked" bit so that attempting to lock an empty
|
||||
// chain has no effect (not needed, as the lock is only needed for
|
||||
// removals).
|
||||
static constexpr uint64_t kNextEndFlags = (uint64_t{1} << 6) | kHeadLocked;
|
||||
|
||||
static inline bool IsEnd(uint64_t next_with_shift) {
|
||||
// Assuming certain values never used, suffices to check this one bit
|
||||
constexpr auto kCheckBit = kNextEndFlags ^ kHeadLocked;
|
||||
return next_with_shift & kCheckBit;
|
||||
}
|
||||
|
||||
// Bottom bits to right shift away to get an array index from a
|
||||
// "with_shift" pointer.
|
||||
static constexpr int kNextShift = 8;
|
||||
|
||||
// A bit mask for the "shift" associated with each "with_shift" pointer.
|
||||
// Always bottommost bits.
|
||||
static constexpr int kShiftMask = 63;
|
||||
|
||||
// A marker for head_next_with_shift that indicates this HandleImpl is
|
||||
// heap allocated (standalone) rather than in the table.
|
||||
static constexpr uint64_t kStandaloneMarker = UINT64_MAX;
|
||||
|
||||
// A marker for head_next_with_shift indicating the head is not yet part
|
||||
// of the usable table, or for chain_next_with_shift indicating that the
|
||||
// entry is not present or is not yet part of a chain (must not be
|
||||
// "shareable" state).
|
||||
static constexpr uint64_t kUnusedMarker = 0;
|
||||
|
||||
// See above. The head pointer is logically independent of the rest of
|
||||
// the entry, including the chain next pointer.
|
||||
std::atomic<uint64_t> head_next_with_shift{kUnusedMarker};
|
||||
std::atomic<uint64_t> chain_next_with_shift{kUnusedMarker};
|
||||
|
||||
// For supporting CreateStandalone and some fallback cases.
|
||||
inline bool IsStandalone() const {
|
||||
return head_next_with_shift.load(std::memory_order_acquire) ==
|
||||
kStandaloneMarker;
|
||||
}
|
||||
|
||||
inline void SetStandalone() {
|
||||
head_next_with_shift.store(kStandaloneMarker, std::memory_order_release);
|
||||
}
|
||||
}; // struct HandleImpl
|
||||
|
||||
struct Opts {
|
||||
explicit Opts(size_t _min_avg_value_size)
|
||||
: min_avg_value_size(_min_avg_value_size) {}
|
||||
|
||||
explicit Opts(const HyperClockCacheOptions& opts) {
|
||||
assert(opts.estimated_entry_charge == 0);
|
||||
min_avg_value_size = opts.min_avg_entry_charge;
|
||||
}
|
||||
size_t min_avg_value_size;
|
||||
};
|
||||
|
||||
AutoHyperClockTable(size_t capacity, bool strict_capacity_limit,
|
||||
CacheMetadataChargePolicy metadata_charge_policy,
|
||||
MemoryAllocator* allocator,
|
||||
const Cache::EvictionCallback* eviction_callback,
|
||||
const uint32_t* hash_seed, const Opts& opts);
|
||||
~AutoHyperClockTable();
|
||||
|
||||
// For BaseClockTable::Insert
|
||||
struct InsertState {
|
||||
uint64_t saved_length_info = 0;
|
||||
size_t likely_empty_slot = 0;
|
||||
};
|
||||
|
||||
void StartInsert(InsertState& state);
|
||||
|
||||
// Does initial check for whether there's hash table room for another
|
||||
// inserted entry, possibly growing if needed. Returns true iff (after
|
||||
// the call) there is room for the proposed number of entries.
|
||||
bool GrowIfNeeded(size_t new_occupancy, InsertState& state);
|
||||
|
||||
HandleImpl* DoInsert(const ClockHandleBasicData& proto,
|
||||
uint64_t initial_countdown, bool take_ref,
|
||||
InsertState& state);
|
||||
|
||||
// Runs the clock eviction algorithm trying to reclaim at least
|
||||
// requested_charge. Returns how much is evicted, which could be less
|
||||
// if it appears impossible to evict the requested amount without blocking.
|
||||
void Evict(size_t requested_charge, InsertState& state, EvictionData* data);
|
||||
|
||||
HandleImpl* Lookup(const UniqueId64x2& hashed_key);
|
||||
|
||||
bool Release(HandleImpl* handle, bool useful, bool erase_if_last_ref);
|
||||
|
||||
void Erase(const UniqueId64x2& hashed_key);
|
||||
|
||||
void EraseUnRefEntries();
|
||||
|
||||
size_t GetTableSize() const;
|
||||
|
||||
size_t GetOccupancyLimit() const;
|
||||
|
||||
const HandleImpl* HandlePtr(size_t idx) const { return &array_[idx]; }
|
||||
|
||||
#ifndef NDEBUG
|
||||
size_t& TEST_MutableOccupancyLimit() {
|
||||
return *reinterpret_cast<size_t*>(&occupancy_limit_);
|
||||
}
|
||||
|
||||
// Release N references
|
||||
void TEST_ReleaseN(HandleImpl* handle, size_t n);
|
||||
#endif
|
||||
|
||||
// Maximum ratio of number of occupied slots to number of usable slots. The
|
||||
// actual load factor should float pretty close to this number, which should
|
||||
// be a nice space/time trade-off, though large swings in WriteBufferManager
|
||||
// memory could lead to low (but very much safe) load factors (only after
|
||||
// seeing high load factors). Linear hashing along with (modified) linear
|
||||
// probing to find an available slot increases potential risks of high
|
||||
// load factors, so are disallowed.
|
||||
static constexpr double kMaxLoadFactor = 0.60;
|
||||
|
||||
private: // functions
|
||||
// Returns true iff increased usable length. Due to load factor
|
||||
// considerations, GrowIfNeeded might call this more than once to make room
|
||||
// for one more entry.
|
||||
bool Grow(InsertState& state);
|
||||
|
||||
// Operational details of splitting a chain into two for Grow().
|
||||
void SplitForGrow(size_t grow_home, size_t old_home, int old_shift);
|
||||
|
||||
// Takes an "under construction" entry and ensures it is no longer connected
|
||||
// to its home chain (in preparaion for completing erasure and freeing the
|
||||
// slot). Note that previous operations might have already noticed it being
|
||||
// "under (de)construction" and removed it from its chain.
|
||||
void Remove(HandleImpl* h);
|
||||
|
||||
// Try to take ownership of an entry and erase+remove it from the table.
|
||||
// Returns true if successful. Could fail if
|
||||
// * There are other references to the entry
|
||||
// * Some other thread has exclusive ownership or has freed it.
|
||||
bool TryEraseHandle(HandleImpl* h, bool holding_ref, bool mark_invisible);
|
||||
|
||||
// Calculates the appropriate maximum table size, for creating the memory
|
||||
// mapping.
|
||||
static size_t CalcMaxUsableLength(
|
||||
size_t capacity, size_t min_avg_value_size,
|
||||
CacheMetadataChargePolicy metadata_charge_policy);
|
||||
|
||||
// Shared helper function that implements removing entries from a chain
|
||||
// with proper handling to ensure all existing data is seen even in the
|
||||
// presence of concurrent insertions, etc. (See implementation.)
|
||||
template <class OpData>
|
||||
void PurgeImpl(OpData* op_data, size_t home = SIZE_MAX);
|
||||
|
||||
// An RAII wrapper for locking a chain of entries for removals. See
|
||||
// implementation.
|
||||
class ChainRewriteLock;
|
||||
|
||||
// Helper function for PurgeImpl while holding a ChainRewriteLock. See
|
||||
// implementation.
|
||||
template <class OpData>
|
||||
void PurgeImplLocked(OpData* op_data, ChainRewriteLock& rewrite_lock,
|
||||
size_t home);
|
||||
|
||||
// Update length_info_ as much as possible without waiting, given a known
|
||||
// usable (ready for inserts and lookups) grow_home. (Previous grow_homes
|
||||
// might not be usable yet, but we can check if they are by looking at
|
||||
// the corresponding old home.)
|
||||
void CatchUpLengthInfoNoWait(size_t known_usable_grow_home);
|
||||
|
||||
private: // data
|
||||
// mmaped area holding handles
|
||||
const TypedMemMapping<HandleImpl> array_;
|
||||
|
||||
// Metadata for table size under linear hashing.
|
||||
//
|
||||
// Lowest 8 bits are the minimum number of lowest hash bits to use
|
||||
// ("min shift"). The upper 56 bits are a threshold. If that minumum number
|
||||
// of bits taken from a hash value is < this threshold, then one more bit of
|
||||
// hash value is taken and used.
|
||||
//
|
||||
// Other mechanisms (shift amounts on pointers) ensure complete availability
|
||||
// of data already in the table even if a reader only sees a completely
|
||||
// out-of-date version of this value. In the worst case, it could take
|
||||
// log time to find the correct chain, but normally this value enables
|
||||
// readers to find the correct chain on the first try.
|
||||
//
|
||||
// NOTES: length_info_ is only updated at the end of a Grow operation,
|
||||
// so that waiting in Grow operations isn't done while entries are pinned
|
||||
// for internal operation purposes. Thus, Lookup and Insert have to
|
||||
// detect and support cases where length_info hasn't caught up to updated
|
||||
// chains. Winning grow thread is the one that transitions
|
||||
// head_next_with_shift from zeros. Grow threads can spin/yield wait for
|
||||
// preconditions and postconditions to be met.
|
||||
std::atomic<uint64_t> length_info_;
|
||||
|
||||
// An already-computed version of the usable length times the max load
|
||||
// factor. Could be slightly out of date but GrowIfNeeded()/Grow() handle
|
||||
// that internally.
|
||||
std::atomic<size_t> occupancy_limit_;
|
||||
|
||||
// See explanation in AutoHyperClockTable::Evict
|
||||
std::atomic<size_t> clock_pointer_mask_;
|
||||
}; // class AutoHyperClockTable
|
||||
|
||||
// A single shard of sharded cache.
|
||||
@@ -785,7 +1109,6 @@ class FixedHyperClockCache
|
||||
const std::shared_ptr<Logger>& /*info_log*/) const override;
|
||||
}; // class FixedHyperClockCache
|
||||
|
||||
// Placeholder for future automatic HCC variant
|
||||
class AutoHyperClockCache
|
||||
#ifdef NDEBUG
|
||||
final
|
||||
@@ -795,6 +1118,9 @@ class AutoHyperClockCache
|
||||
using BaseHyperClockCache::BaseHyperClockCache;
|
||||
|
||||
const char* Name() const override { return "AutoHyperClockCache"; }
|
||||
|
||||
void ReportProblems(
|
||||
const std::shared_ptr<Logger>& /*info_log*/) const override;
|
||||
}; // class AutoHyperClockCache
|
||||
|
||||
} // namespace clock_cache
|
||||
|
||||
Vendored
+129
-48
@@ -11,6 +11,7 @@
|
||||
|
||||
#include "memory/memory_allocator_impl.h"
|
||||
#include "monitoring/perf_context_imp.h"
|
||||
#include "util/coding.h"
|
||||
#include "util/compression.h"
|
||||
#include "util/string_util.h"
|
||||
|
||||
@@ -22,17 +23,20 @@ CompressedSecondaryCache::CompressedSecondaryCache(
|
||||
cache_options_(opts),
|
||||
cache_res_mgr_(std::make_shared<ConcurrentCacheReservationManager>(
|
||||
std::make_shared<CacheReservationManagerImpl<CacheEntryRole::kMisc>>(
|
||||
cache_))) {}
|
||||
cache_))),
|
||||
disable_cache_(opts.capacity == 0) {}
|
||||
|
||||
CompressedSecondaryCache::~CompressedSecondaryCache() {
|
||||
assert(cache_res_mgr_->GetTotalReservedCacheSize() == 0);
|
||||
}
|
||||
CompressedSecondaryCache::~CompressedSecondaryCache() {}
|
||||
|
||||
std::unique_ptr<SecondaryCacheResultHandle> CompressedSecondaryCache::Lookup(
|
||||
const Slice& key, const Cache::CacheItemHelper* helper,
|
||||
Cache::CreateContext* create_context, bool /*wait*/, bool advise_erase,
|
||||
bool& kept_in_sec_cache) {
|
||||
assert(helper);
|
||||
if (disable_cache_) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::unique_ptr<SecondaryCacheResultHandle> handle;
|
||||
kept_in_sec_cache = false;
|
||||
Cache::Handle* lru_handle = cache_->Lookup(key);
|
||||
@@ -49,40 +53,65 @@ std::unique_ptr<SecondaryCacheResultHandle> CompressedSecondaryCache::Lookup(
|
||||
CacheAllocationPtr* ptr{nullptr};
|
||||
CacheAllocationPtr merged_value;
|
||||
size_t handle_value_charge{0};
|
||||
const char* data_ptr = nullptr;
|
||||
CacheTier source = CacheTier::kVolatileCompressedTier;
|
||||
CompressionType type = cache_options_.compression_type;
|
||||
if (cache_options_.enable_custom_split_merge) {
|
||||
CacheValueChunk* value_chunk_ptr =
|
||||
reinterpret_cast<CacheValueChunk*>(handle_value);
|
||||
merged_value = MergeChunksIntoValue(value_chunk_ptr, handle_value_charge);
|
||||
ptr = &merged_value;
|
||||
data_ptr = ptr->get();
|
||||
} else {
|
||||
uint32_t type_32 = static_cast<uint32_t>(type);
|
||||
uint32_t source_32 = static_cast<uint32_t>(source);
|
||||
ptr = reinterpret_cast<CacheAllocationPtr*>(handle_value);
|
||||
handle_value_charge = cache_->GetCharge(lru_handle);
|
||||
data_ptr = ptr->get();
|
||||
data_ptr = GetVarint32Ptr(data_ptr, data_ptr + 1,
|
||||
static_cast<uint32_t*>(&type_32));
|
||||
type = static_cast<CompressionType>(type_32);
|
||||
data_ptr = GetVarint32Ptr(data_ptr, data_ptr + 1,
|
||||
static_cast<uint32_t*>(&source_32));
|
||||
source = static_cast<CacheTier>(source_32);
|
||||
handle_value_charge -= (data_ptr - ptr->get());
|
||||
}
|
||||
MemoryAllocator* allocator = cache_options_.memory_allocator.get();
|
||||
|
||||
Status s;
|
||||
Cache::ObjectPtr value{nullptr};
|
||||
size_t charge{0};
|
||||
if (cache_options_.compression_type == kNoCompression ||
|
||||
cache_options_.do_not_compress_roles.Contains(helper->role)) {
|
||||
s = helper->create_cb(Slice(ptr->get(), handle_value_charge),
|
||||
create_context, allocator, &value, &charge);
|
||||
} else {
|
||||
UncompressionContext uncompression_context(cache_options_.compression_type);
|
||||
UncompressionInfo uncompression_info(uncompression_context,
|
||||
UncompressionDict::GetEmptyDict(),
|
||||
cache_options_.compression_type);
|
||||
if (source == CacheTier::kVolatileCompressedTier) {
|
||||
if (cache_options_.compression_type == kNoCompression ||
|
||||
cache_options_.do_not_compress_roles.Contains(helper->role)) {
|
||||
s = helper->create_cb(Slice(data_ptr, handle_value_charge),
|
||||
kNoCompression, CacheTier::kVolatileTier,
|
||||
create_context, allocator, &value, &charge);
|
||||
} else {
|
||||
UncompressionContext uncompression_context(
|
||||
cache_options_.compression_type);
|
||||
UncompressionInfo uncompression_info(uncompression_context,
|
||||
UncompressionDict::GetEmptyDict(),
|
||||
cache_options_.compression_type);
|
||||
|
||||
size_t uncompressed_size{0};
|
||||
CacheAllocationPtr uncompressed = UncompressData(
|
||||
uncompression_info, (char*)ptr->get(), handle_value_charge,
|
||||
&uncompressed_size, cache_options_.compress_format_version, allocator);
|
||||
size_t uncompressed_size{0};
|
||||
CacheAllocationPtr uncompressed =
|
||||
UncompressData(uncompression_info, (char*)data_ptr,
|
||||
handle_value_charge, &uncompressed_size,
|
||||
cache_options_.compress_format_version, allocator);
|
||||
|
||||
if (!uncompressed) {
|
||||
cache_->Release(lru_handle, /*erase_if_last_ref=*/true);
|
||||
return nullptr;
|
||||
if (!uncompressed) {
|
||||
cache_->Release(lru_handle, /*erase_if_last_ref=*/true);
|
||||
return nullptr;
|
||||
}
|
||||
s = helper->create_cb(Slice(uncompressed.get(), uncompressed_size),
|
||||
kNoCompression, CacheTier::kVolatileTier,
|
||||
create_context, allocator, &value, &charge);
|
||||
}
|
||||
s = helper->create_cb(Slice(uncompressed.get(), uncompressed_size),
|
||||
} else {
|
||||
// The item was not compressed by us. Let the helper create_cb
|
||||
// uncompress it
|
||||
s = helper->create_cb(Slice(data_ptr, handle_value_charge), type, source,
|
||||
create_context, allocator, &value, &charge);
|
||||
}
|
||||
|
||||
@@ -107,41 +136,56 @@ std::unique_ptr<SecondaryCacheResultHandle> CompressedSecondaryCache::Lookup(
|
||||
return handle;
|
||||
}
|
||||
|
||||
Status CompressedSecondaryCache::Insert(const Slice& key,
|
||||
Cache::ObjectPtr value,
|
||||
const Cache::CacheItemHelper* helper,
|
||||
bool force_insert) {
|
||||
if (value == nullptr) {
|
||||
return Status::InvalidArgument();
|
||||
bool CompressedSecondaryCache::MaybeInsertDummy(const Slice& key) {
|
||||
auto internal_helper = GetHelper(cache_options_.enable_custom_split_merge);
|
||||
Cache::Handle* lru_handle = cache_->Lookup(key);
|
||||
if (lru_handle == nullptr) {
|
||||
PERF_COUNTER_ADD(compressed_sec_cache_insert_dummy_count, 1);
|
||||
// Insert a dummy handle if the handle is evicted for the first time.
|
||||
cache_->Insert(key, /*obj=*/nullptr, internal_helper, /*charge=*/0)
|
||||
.PermitUncheckedError();
|
||||
return true;
|
||||
} else {
|
||||
cache_->Release(lru_handle, /*erase_if_last_ref=*/false);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
Status CompressedSecondaryCache::InsertInternal(
|
||||
const Slice& key, Cache::ObjectPtr value,
|
||||
const Cache::CacheItemHelper* helper, CompressionType type,
|
||||
CacheTier source) {
|
||||
if (source != CacheTier::kVolatileCompressedTier &&
|
||||
cache_options_.enable_custom_split_merge) {
|
||||
// We don't support custom split/merge for the tiered case
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
auto internal_helper = GetHelper(cache_options_.enable_custom_split_merge);
|
||||
if (!force_insert) {
|
||||
Cache::Handle* lru_handle = cache_->Lookup(key);
|
||||
if (lru_handle == nullptr) {
|
||||
PERF_COUNTER_ADD(compressed_sec_cache_insert_dummy_count, 1);
|
||||
// Insert a dummy handle if the handle is evicted for the first time.
|
||||
return cache_->Insert(key, /*obj=*/nullptr, internal_helper,
|
||||
/*charge=*/0);
|
||||
} else {
|
||||
cache_->Release(lru_handle, /*erase_if_last_ref=*/false);
|
||||
}
|
||||
}
|
||||
char header[10];
|
||||
char* payload = header;
|
||||
payload = EncodeVarint32(payload, static_cast<uint32_t>(type));
|
||||
payload = EncodeVarint32(payload, static_cast<uint32_t>(source));
|
||||
|
||||
size_t size = (*helper->size_cb)(value);
|
||||
size_t header_size = payload - header;
|
||||
size_t data_size = (*helper->size_cb)(value);
|
||||
size_t total_size = data_size + header_size;
|
||||
CacheAllocationPtr ptr =
|
||||
AllocateBlock(size, cache_options_.memory_allocator.get());
|
||||
AllocateBlock(total_size, cache_options_.memory_allocator.get());
|
||||
char* data_ptr = ptr.get() + header_size;
|
||||
|
||||
Status s = (*helper->saveto_cb)(value, 0, size, ptr.get());
|
||||
Status s = (*helper->saveto_cb)(value, 0, data_size, data_ptr);
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
Slice val(ptr.get(), size);
|
||||
Slice val(data_ptr, data_size);
|
||||
|
||||
std::string compressed_val;
|
||||
if (cache_options_.compression_type != kNoCompression &&
|
||||
type == kNoCompression &&
|
||||
!cache_options_.do_not_compress_roles.Contains(helper->role)) {
|
||||
PERF_COUNTER_ADD(compressed_sec_cache_uncompressed_bytes, size);
|
||||
PERF_COUNTER_ADD(compressed_sec_cache_uncompressed_bytes, data_size);
|
||||
CompressionOptions compression_opts;
|
||||
CompressionContext compression_context(cache_options_.compression_type,
|
||||
compression_opts);
|
||||
@@ -159,12 +203,14 @@ Status CompressedSecondaryCache::Insert(const Slice& key,
|
||||
}
|
||||
|
||||
val = Slice(compressed_val);
|
||||
size = compressed_val.size();
|
||||
PERF_COUNTER_ADD(compressed_sec_cache_compressed_bytes, size);
|
||||
data_size = compressed_val.size();
|
||||
total_size = header_size + data_size;
|
||||
PERF_COUNTER_ADD(compressed_sec_cache_compressed_bytes, data_size);
|
||||
|
||||
if (!cache_options_.enable_custom_split_merge) {
|
||||
ptr = AllocateBlock(size, cache_options_.memory_allocator.get());
|
||||
memcpy(ptr.get(), compressed_val.data(), size);
|
||||
ptr = AllocateBlock(total_size, cache_options_.memory_allocator.get());
|
||||
data_ptr = ptr.get() + header_size;
|
||||
memcpy(data_ptr, compressed_val.data(), data_size);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,17 +221,52 @@ Status CompressedSecondaryCache::Insert(const Slice& key,
|
||||
SplitValueIntoChunks(val, cache_options_.compression_type, charge);
|
||||
return cache_->Insert(key, value_chunks_head, internal_helper, charge);
|
||||
} else {
|
||||
std::memcpy(ptr.get(), header, header_size);
|
||||
CacheAllocationPtr* buf = new CacheAllocationPtr(std::move(ptr));
|
||||
return cache_->Insert(key, buf, internal_helper, size);
|
||||
return cache_->Insert(key, buf, internal_helper, total_size);
|
||||
}
|
||||
}
|
||||
|
||||
Status CompressedSecondaryCache::Insert(const Slice& key,
|
||||
Cache::ObjectPtr value,
|
||||
const Cache::CacheItemHelper* helper,
|
||||
bool force_insert) {
|
||||
if (value == nullptr) {
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
|
||||
if (!force_insert && MaybeInsertDummy(key)) {
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
return InsertInternal(key, value, helper, kNoCompression,
|
||||
CacheTier::kVolatileCompressedTier);
|
||||
}
|
||||
|
||||
Status CompressedSecondaryCache::InsertSaved(
|
||||
const Slice& key, const Slice& saved, CompressionType type = kNoCompression,
|
||||
CacheTier source = CacheTier::kVolatileTier) {
|
||||
if (type == kNoCompression) {
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
auto slice_helper = &kSliceCacheItemHelper;
|
||||
if (MaybeInsertDummy(key)) {
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
return InsertInternal(
|
||||
key, static_cast<Cache::ObjectPtr>(const_cast<Slice*>(&saved)),
|
||||
slice_helper, type, source);
|
||||
}
|
||||
|
||||
void CompressedSecondaryCache::Erase(const Slice& key) { cache_->Erase(key); }
|
||||
|
||||
Status CompressedSecondaryCache::SetCapacity(size_t capacity) {
|
||||
MutexLock l(&capacity_mutex_);
|
||||
cache_options_.capacity = capacity;
|
||||
cache_->SetCapacity(capacity);
|
||||
disable_cache_ = capacity == 0;
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
Vendored
+10
@@ -80,6 +80,9 @@ class CompressedSecondaryCache : public SecondaryCache {
|
||||
const Cache::CacheItemHelper* helper,
|
||||
bool force_insert) override;
|
||||
|
||||
Status InsertSaved(const Slice& key, const Slice& saved, CompressionType type,
|
||||
CacheTier source) override;
|
||||
|
||||
std::unique_ptr<SecondaryCacheResultHandle> Lookup(
|
||||
const Slice& key, const Cache::CacheItemHelper* helper,
|
||||
Cache::CreateContext* create_context, bool /*wait*/, bool advise_erase,
|
||||
@@ -130,12 +133,19 @@ class CompressedSecondaryCache : public SecondaryCache {
|
||||
CacheAllocationPtr MergeChunksIntoValue(const void* chunks_head,
|
||||
size_t& charge);
|
||||
|
||||
bool MaybeInsertDummy(const Slice& key);
|
||||
|
||||
Status InsertInternal(const Slice& key, Cache::ObjectPtr value,
|
||||
const Cache::CacheItemHelper* helper,
|
||||
CompressionType type, CacheTier source);
|
||||
|
||||
// TODO: clean up to use cleaner interfaces in typed_cache.h
|
||||
const Cache::CacheItemHelper* GetHelper(bool enable_custom_split_merge) const;
|
||||
std::shared_ptr<Cache> cache_;
|
||||
CompressedSecondaryCacheOptions cache_options_;
|
||||
mutable port::Mutex capacity_mutex_;
|
||||
std::shared_ptr<ConcurrentCacheReservationManager> cache_res_mgr_;
|
||||
bool disable_cache_;
|
||||
};
|
||||
|
||||
} // namespace ROCKSDB_NAMESPACE
|
||||
+182
-7
@@ -989,11 +989,11 @@ class CompressedSecCacheTestWithTiered
|
||||
CompressedSecCacheTestWithTiered() {
|
||||
LRUCacheOptions lru_opts;
|
||||
HyperClockCacheOptions hcc_opts(
|
||||
/*_capacity=*/70 << 20,
|
||||
/*_capacity=*/0,
|
||||
/*_estimated_entry_charge=*/256 << 10,
|
||||
/*_num_shard_bits=*/0);
|
||||
TieredVolatileCacheOptions opts;
|
||||
lru_opts.capacity = 70 << 20;
|
||||
TieredCacheOptions opts;
|
||||
lru_opts.capacity = 0;
|
||||
lru_opts.num_shard_bits = 0;
|
||||
lru_opts.high_pri_pool_ratio = 0;
|
||||
opts.cache_type = std::get<0>(GetParam());
|
||||
@@ -1004,9 +1004,11 @@ class CompressedSecCacheTestWithTiered
|
||||
}
|
||||
opts.adm_policy = std::get<1>(GetParam());
|
||||
;
|
||||
opts.comp_cache_opts.capacity = 30 << 20;
|
||||
opts.comp_cache_opts.capacity = 0;
|
||||
opts.comp_cache_opts.num_shard_bits = 0;
|
||||
cache_ = NewTieredVolatileCache(opts);
|
||||
opts.total_capacity = 100 << 20;
|
||||
opts.compressed_secondary_ratio = 0.3;
|
||||
cache_ = NewTieredCache(opts);
|
||||
cache_res_mgr_ =
|
||||
std::make_shared<CacheReservationManagerImpl<CacheEntryRole::kMisc>>(
|
||||
cache_);
|
||||
@@ -1023,7 +1025,7 @@ class CompressedSecCacheTestWithTiered
|
||||
protected:
|
||||
CacheReservationManager* cache_res_mgr() { return cache_res_mgr_.get(); }
|
||||
|
||||
Cache* GetTieredCache() { return cache_.get(); }
|
||||
std::shared_ptr<Cache> GetTieredCache() { return cache_; }
|
||||
|
||||
Cache* GetCache() {
|
||||
return static_cast_with_check<CacheWithSecondaryAdapter, Cache>(
|
||||
@@ -1110,7 +1112,7 @@ TEST_P(CompressedSecCacheTestWithTiered, AdmissionPolicy) {
|
||||
return;
|
||||
}
|
||||
|
||||
Cache* tiered_cache = GetTieredCache();
|
||||
Cache* tiered_cache = GetTieredCache().get();
|
||||
Cache* cache = GetCache();
|
||||
std::vector<CacheKey> keys;
|
||||
std::vector<std::string> vals;
|
||||
@@ -1165,6 +1167,179 @@ TEST_P(CompressedSecCacheTestWithTiered, AdmissionPolicy) {
|
||||
ASSERT_EQ(handle1, nullptr);
|
||||
}
|
||||
|
||||
TEST_P(CompressedSecCacheTestWithTiered, DynamicUpdate) {
|
||||
CompressedSecondaryCache* sec_cache =
|
||||
reinterpret_cast<CompressedSecondaryCache*>(GetSecondaryCache());
|
||||
std::shared_ptr<Cache> tiered_cache = GetTieredCache();
|
||||
|
||||
// Use EXPECT_PRED3 instead of EXPECT_NEAR to void too many size_t to
|
||||
// double explicit casts
|
||||
EXPECT_PRED3(CacheUsageWithinBounds, GetCache()->GetUsage(), (30 << 20),
|
||||
GetPercent(30 << 20, 1));
|
||||
size_t sec_capacity;
|
||||
ASSERT_OK(sec_cache->GetCapacity(sec_capacity));
|
||||
ASSERT_EQ(sec_capacity, (30 << 20));
|
||||
|
||||
ASSERT_OK(UpdateTieredCache(tiered_cache, 130 << 20));
|
||||
EXPECT_PRED3(CacheUsageWithinBounds, GetCache()->GetUsage(), (39 << 20),
|
||||
GetPercent(39 << 20, 1));
|
||||
ASSERT_OK(sec_cache->GetCapacity(sec_capacity));
|
||||
ASSERT_EQ(sec_capacity, (39 << 20));
|
||||
|
||||
ASSERT_OK(UpdateTieredCache(tiered_cache, 70 << 20));
|
||||
EXPECT_PRED3(CacheUsageWithinBounds, GetCache()->GetUsage(), (21 << 20),
|
||||
GetPercent(21 << 20, 1));
|
||||
ASSERT_OK(sec_cache->GetCapacity(sec_capacity));
|
||||
ASSERT_EQ(sec_capacity, (21 << 20));
|
||||
|
||||
ASSERT_OK(UpdateTieredCache(tiered_cache, 100 << 20));
|
||||
EXPECT_PRED3(CacheUsageWithinBounds, GetCache()->GetUsage(), (30 << 20),
|
||||
GetPercent(30 << 20, 1));
|
||||
ASSERT_OK(sec_cache->GetCapacity(sec_capacity));
|
||||
ASSERT_EQ(sec_capacity, (30 << 20));
|
||||
|
||||
ASSERT_OK(UpdateTieredCache(tiered_cache, -1, 0.4));
|
||||
EXPECT_PRED3(CacheUsageWithinBounds, GetCache()->GetUsage(), (40 << 20),
|
||||
GetPercent(40 << 20, 1));
|
||||
ASSERT_OK(sec_cache->GetCapacity(sec_capacity));
|
||||
ASSERT_EQ(sec_capacity, (40 << 20));
|
||||
|
||||
ASSERT_OK(UpdateTieredCache(tiered_cache, -1, 0.2));
|
||||
EXPECT_PRED3(CacheUsageWithinBounds, GetCache()->GetUsage(), (20 << 20),
|
||||
GetPercent(20 << 20, 1));
|
||||
ASSERT_OK(sec_cache->GetCapacity(sec_capacity));
|
||||
ASSERT_EQ(sec_capacity, (20 << 20));
|
||||
|
||||
ASSERT_OK(UpdateTieredCache(tiered_cache, -1, 1.0));
|
||||
EXPECT_PRED3(CacheUsageWithinBounds, GetCache()->GetUsage(), (100 << 20),
|
||||
GetPercent(100 << 20, 1));
|
||||
ASSERT_OK(sec_cache->GetCapacity(sec_capacity));
|
||||
ASSERT_EQ(sec_capacity, 100 << 20);
|
||||
|
||||
ASSERT_OK(UpdateTieredCache(tiered_cache, -1, 0.0));
|
||||
// Only check usage for LRU cache. HCC shows a 64KB usage for some reason
|
||||
if (std::get<0>(GetParam()) == PrimaryCacheType::kCacheTypeLRU) {
|
||||
ASSERT_EQ(GetCache()->GetUsage(), 0);
|
||||
}
|
||||
ASSERT_OK(sec_cache->GetCapacity(sec_capacity));
|
||||
ASSERT_EQ(sec_capacity, 0);
|
||||
|
||||
ASSERT_NOK(UpdateTieredCache(tiered_cache, -1, 0.3));
|
||||
// Only check usage for LRU cache. HCC shows a 64KB usage for some reason
|
||||
if (std::get<0>(GetParam()) == PrimaryCacheType::kCacheTypeLRU) {
|
||||
ASSERT_EQ(GetCache()->GetUsage(), 0);
|
||||
}
|
||||
ASSERT_OK(sec_cache->GetCapacity(sec_capacity));
|
||||
ASSERT_EQ(sec_capacity, 0);
|
||||
}
|
||||
|
||||
TEST_P(CompressedSecCacheTestWithTiered, DynamicUpdateWithReservation) {
|
||||
CompressedSecondaryCache* sec_cache =
|
||||
reinterpret_cast<CompressedSecondaryCache*>(GetSecondaryCache());
|
||||
std::shared_ptr<Cache> tiered_cache = GetTieredCache();
|
||||
|
||||
ASSERT_OK(cache_res_mgr()->UpdateCacheReservation(10 << 20));
|
||||
// Use EXPECT_PRED3 instead of EXPECT_NEAR to void too many size_t to
|
||||
// double explicit casts
|
||||
EXPECT_PRED3(CacheUsageWithinBounds, GetCache()->GetUsage(), (37 << 20),
|
||||
GetPercent(37 << 20, 1));
|
||||
EXPECT_PRED3(CacheUsageWithinBounds, sec_cache->TEST_GetUsage(), (3 << 20),
|
||||
GetPercent(3 << 20, 1));
|
||||
size_t sec_capacity;
|
||||
ASSERT_OK(sec_cache->GetCapacity(sec_capacity));
|
||||
ASSERT_EQ(sec_capacity, (30 << 20));
|
||||
|
||||
ASSERT_OK(UpdateTieredCache(tiered_cache, 70 << 20));
|
||||
// Only check usage for LRU cache. HCC is slightly off for some reason
|
||||
if (std::get<0>(GetParam()) == PrimaryCacheType::kCacheTypeLRU) {
|
||||
EXPECT_PRED3(CacheUsageWithinBounds, GetCache()->GetUsage(), (28 << 20),
|
||||
GetPercent(28 << 20, 1));
|
||||
}
|
||||
EXPECT_PRED3(CacheUsageWithinBounds, sec_cache->TEST_GetUsage(), (3 << 20),
|
||||
GetPercent(3 << 20, 1));
|
||||
ASSERT_OK(sec_cache->GetCapacity(sec_capacity));
|
||||
ASSERT_EQ(sec_capacity, (21 << 20));
|
||||
|
||||
ASSERT_OK(UpdateTieredCache(tiered_cache, 130 << 20));
|
||||
EXPECT_PRED3(CacheUsageWithinBounds, GetCache()->GetUsage(), (46 << 20),
|
||||
GetPercent(46 << 20, 1));
|
||||
EXPECT_PRED3(CacheUsageWithinBounds, sec_cache->TEST_GetUsage(), (3 << 20),
|
||||
GetPercent(3 << 20, 1));
|
||||
ASSERT_OK(sec_cache->GetCapacity(sec_capacity));
|
||||
ASSERT_EQ(sec_capacity, (39 << 20));
|
||||
|
||||
ASSERT_OK(UpdateTieredCache(tiered_cache, 100 << 20));
|
||||
EXPECT_PRED3(CacheUsageWithinBounds, GetCache()->GetUsage(), (37 << 20),
|
||||
GetPercent(37 << 20, 1));
|
||||
EXPECT_PRED3(CacheUsageWithinBounds, sec_cache->TEST_GetUsage(), (3 << 20),
|
||||
GetPercent(3 << 20, 1));
|
||||
ASSERT_OK(sec_cache->GetCapacity(sec_capacity));
|
||||
ASSERT_EQ(sec_capacity, (30 << 20));
|
||||
|
||||
ASSERT_OK(tiered_cache->GetSecondaryCacheCapacity(sec_capacity));
|
||||
ASSERT_EQ(sec_capacity, 30 << 20);
|
||||
size_t sec_usage;
|
||||
ASSERT_OK(tiered_cache->GetSecondaryCachePinnedUsage(sec_usage));
|
||||
EXPECT_PRED3(CacheUsageWithinBounds, sec_usage, 3 << 20,
|
||||
GetPercent(3 << 20, 1));
|
||||
|
||||
ASSERT_OK(UpdateTieredCache(tiered_cache, -1, 0.39));
|
||||
EXPECT_PRED3(CacheUsageWithinBounds, GetCache()->GetUsage(), (45 << 20),
|
||||
GetPercent(45 << 20, 1));
|
||||
EXPECT_PRED3(CacheUsageWithinBounds, sec_cache->TEST_GetUsage(), (4 << 20),
|
||||
GetPercent(4 << 20, 1));
|
||||
ASSERT_OK(sec_cache->GetCapacity(sec_capacity));
|
||||
ASSERT_EQ(sec_capacity, (39 << 20));
|
||||
|
||||
ASSERT_OK(UpdateTieredCache(tiered_cache, -1, 0.2));
|
||||
// Only check usage for LRU cache. HCC is slightly off for some reason
|
||||
if (std::get<0>(GetParam()) == PrimaryCacheType::kCacheTypeLRU) {
|
||||
EXPECT_PRED3(CacheUsageWithinBounds, GetCache()->GetUsage(), (28 << 20),
|
||||
GetPercent(28 << 20, 1));
|
||||
}
|
||||
EXPECT_PRED3(CacheUsageWithinBounds, sec_cache->TEST_GetUsage(), (2 << 20),
|
||||
GetPercent(2 << 20, 1));
|
||||
ASSERT_OK(sec_cache->GetCapacity(sec_capacity));
|
||||
ASSERT_EQ(sec_capacity, (20 << 20));
|
||||
|
||||
ASSERT_OK(UpdateTieredCache(tiered_cache, -1, 1.0));
|
||||
EXPECT_PRED3(CacheUsageWithinBounds, GetCache()->GetUsage(), (100 << 20),
|
||||
GetPercent(100 << 20, 1));
|
||||
EXPECT_PRED3(CacheUsageWithinBounds, sec_cache->TEST_GetUsage(), (10 << 20),
|
||||
GetPercent(10 << 20, 1));
|
||||
ASSERT_OK(sec_cache->GetCapacity(sec_capacity));
|
||||
ASSERT_EQ(sec_capacity, 100 << 20);
|
||||
|
||||
ASSERT_OK(UpdateTieredCache(tiered_cache, -1, 0.0));
|
||||
EXPECT_PRED3(CacheUsageWithinBounds, GetCache()->GetUsage(), (10 << 20),
|
||||
GetPercent(10 << 20, 1));
|
||||
ASSERT_OK(sec_cache->GetCapacity(sec_capacity));
|
||||
ASSERT_EQ(sec_capacity, 0);
|
||||
|
||||
ASSERT_OK(cache_res_mgr()->UpdateCacheReservation(0));
|
||||
}
|
||||
|
||||
TEST_P(CompressedSecCacheTestWithTiered,
|
||||
DynamicUpdateWithReservationUnderflow) {
|
||||
std::shared_ptr<Cache> tiered_cache = GetTieredCache();
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
|
||||
{{"CacheWithSecondaryAdapter::Release:ChargeSecCache1",
|
||||
"CacheWithSecondaryAdapter::UpdateCacheReservationRatio:Begin"},
|
||||
{"CacheWithSecondaryAdapter::UpdateCacheReservationRatio:End",
|
||||
"CacheWithSecondaryAdapter::Release:ChargeSecCache2"}});
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
|
||||
|
||||
port::Thread reserve_release_thread([&]() {
|
||||
EXPECT_EQ(cache_res_mgr()->UpdateCacheReservation(50), Status::OK());
|
||||
EXPECT_EQ(cache_res_mgr()->UpdateCacheReservation(0), Status::OK());
|
||||
});
|
||||
ASSERT_OK(UpdateTieredCache(tiered_cache, 100 << 20, 0.01));
|
||||
reserve_release_thread.join();
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
|
||||
|
||||
ASSERT_OK(UpdateTieredCache(tiered_cache, 100 << 20, 0.3));
|
||||
}
|
||||
|
||||
INSTANTIATE_TEST_CASE_P(
|
||||
CompressedSecCacheTests, CompressedSecCacheTestWithTiered,
|
||||
::testing::Values(
|
||||
|
||||
Vendored
+31
-14
@@ -534,7 +534,7 @@ TYPED_TEST(ClockCacheTest, Limits) {
|
||||
// (Cleverly using mostly zero-charge entries, but some non-zero to
|
||||
// verify usage tracking on detached entries.)
|
||||
{
|
||||
size_t n = shard.GetTableAddressCount() + 1;
|
||||
size_t n = kCapacity * 5 + 1;
|
||||
std::unique_ptr<HandleImpl* []> ha { new HandleImpl* [n] {} };
|
||||
Status s;
|
||||
for (size_t i = 0; i < n && s.ok(); ++i) {
|
||||
@@ -560,6 +560,8 @@ TYPED_TEST(ClockCacheTest, Limits) {
|
||||
EXPECT_OK(s);
|
||||
}
|
||||
|
||||
EXPECT_EQ(shard.GetOccupancyCount(), shard.GetOccupancyLimit());
|
||||
|
||||
// Regardless, we didn't allow table to actually get full
|
||||
EXPECT_LT(shard.GetOccupancyCount(), shard.GetTableAddressCount());
|
||||
|
||||
@@ -981,13 +983,14 @@ class TestSecondaryCache : public SecondaryCache {
|
||||
|
||||
using ResultMap = std::unordered_map<std::string, ResultType>;
|
||||
|
||||
explicit TestSecondaryCache(size_t capacity)
|
||||
explicit TestSecondaryCache(size_t capacity, bool insert_saved = false)
|
||||
: cache_(NewLRUCache(capacity, 0, false, 0.5 /* high_pri_pool_ratio */,
|
||||
nullptr, kDefaultToAdaptiveMutex,
|
||||
kDontChargeCacheMetadata)),
|
||||
num_inserts_(0),
|
||||
num_lookups_(0),
|
||||
inject_failure_(false) {}
|
||||
inject_failure_(false),
|
||||
insert_saved_(insert_saved) {}
|
||||
|
||||
const char* Name() const override { return "TestSecondaryCache"; }
|
||||
|
||||
@@ -1018,6 +1021,17 @@ class TestSecondaryCache : public SecondaryCache {
|
||||
return cache_.Insert(key, buf, size);
|
||||
}
|
||||
|
||||
Status InsertSaved(const Slice& key, const Slice& saved,
|
||||
CompressionType /*type*/ = kNoCompression,
|
||||
CacheTier /*source*/ = CacheTier::kVolatileTier) override {
|
||||
if (insert_saved_) {
|
||||
return Insert(key, const_cast<Slice*>(&saved), &kSliceCacheItemHelper,
|
||||
/*force_insert=*/true);
|
||||
} else {
|
||||
return Status::OK();
|
||||
}
|
||||
}
|
||||
|
||||
std::unique_ptr<SecondaryCacheResultHandle> Lookup(
|
||||
const Slice& key, const Cache::CacheItemHelper* helper,
|
||||
Cache::CreateContext* create_context, bool /*wait*/,
|
||||
@@ -1046,7 +1060,8 @@ class TestSecondaryCache : public SecondaryCache {
|
||||
char* ptr = cache_.Value(handle);
|
||||
size_t size = DecodeFixed64(ptr);
|
||||
ptr += sizeof(uint64_t);
|
||||
s = helper->create_cb(Slice(ptr, size), create_context,
|
||||
s = helper->create_cb(Slice(ptr, size), kNoCompression,
|
||||
CacheTier::kVolatileTier, create_context,
|
||||
/*alloc*/ nullptr, &value, &charge);
|
||||
}
|
||||
if (s.ok()) {
|
||||
@@ -1135,6 +1150,7 @@ class TestSecondaryCache : public SecondaryCache {
|
||||
uint32_t num_inserts_;
|
||||
uint32_t num_lookups_;
|
||||
bool inject_failure_;
|
||||
bool insert_saved_;
|
||||
std::string ckey_prefix_;
|
||||
ResultMap result_map_;
|
||||
};
|
||||
@@ -1165,7 +1181,7 @@ INSTANTIATE_TEST_CASE_P(DBSecondaryCacheTest, DBSecondaryCacheTest,
|
||||
|
||||
TEST_P(BasicSecondaryCacheTest, BasicTest) {
|
||||
std::shared_ptr<TestSecondaryCache> secondary_cache =
|
||||
std::make_shared<TestSecondaryCache>(4096);
|
||||
std::make_shared<TestSecondaryCache>(4096, true);
|
||||
std::shared_ptr<Cache> cache =
|
||||
NewCache(1024 /* capacity */, 0 /* num_shard_bits */,
|
||||
false /* strict_capacity_limit */, secondary_cache);
|
||||
@@ -1222,7 +1238,7 @@ TEST_P(BasicSecondaryCacheTest, BasicTest) {
|
||||
|
||||
TEST_P(BasicSecondaryCacheTest, StatsTest) {
|
||||
std::shared_ptr<TestSecondaryCache> secondary_cache =
|
||||
std::make_shared<TestSecondaryCache>(4096);
|
||||
std::make_shared<TestSecondaryCache>(4096, true);
|
||||
std::shared_ptr<Cache> cache =
|
||||
NewCache(1024 /* capacity */, 0 /* num_shard_bits */,
|
||||
false /* strict_capacity_limit */, secondary_cache);
|
||||
@@ -1276,7 +1292,7 @@ TEST_P(BasicSecondaryCacheTest, StatsTest) {
|
||||
|
||||
TEST_P(BasicSecondaryCacheTest, BasicFailTest) {
|
||||
std::shared_ptr<TestSecondaryCache> secondary_cache =
|
||||
std::make_shared<TestSecondaryCache>(2048);
|
||||
std::make_shared<TestSecondaryCache>(2048, true);
|
||||
std::shared_ptr<Cache> cache =
|
||||
NewCache(1024 /* capacity */, 0 /* num_shard_bits */,
|
||||
false /* strict_capacity_limit */, secondary_cache);
|
||||
@@ -1318,7 +1334,7 @@ TEST_P(BasicSecondaryCacheTest, BasicFailTest) {
|
||||
|
||||
TEST_P(BasicSecondaryCacheTest, SaveFailTest) {
|
||||
std::shared_ptr<TestSecondaryCache> secondary_cache =
|
||||
std::make_shared<TestSecondaryCache>(2048);
|
||||
std::make_shared<TestSecondaryCache>(2048, true);
|
||||
std::shared_ptr<Cache> cache =
|
||||
NewCache(1024 /* capacity */, 0 /* num_shard_bits */,
|
||||
false /* strict_capacity_limit */, secondary_cache);
|
||||
@@ -1359,7 +1375,7 @@ TEST_P(BasicSecondaryCacheTest, SaveFailTest) {
|
||||
|
||||
TEST_P(BasicSecondaryCacheTest, CreateFailTest) {
|
||||
std::shared_ptr<TestSecondaryCache> secondary_cache =
|
||||
std::make_shared<TestSecondaryCache>(2048);
|
||||
std::make_shared<TestSecondaryCache>(2048, true);
|
||||
std::shared_ptr<Cache> cache =
|
||||
NewCache(1024 /* capacity */, 0 /* num_shard_bits */,
|
||||
false /* strict_capacity_limit */, secondary_cache);
|
||||
@@ -1400,7 +1416,7 @@ TEST_P(BasicSecondaryCacheTest, CreateFailTest) {
|
||||
TEST_P(BasicSecondaryCacheTest, FullCapacityTest) {
|
||||
for (bool strict_capacity_limit : {false, true}) {
|
||||
std::shared_ptr<TestSecondaryCache> secondary_cache =
|
||||
std::make_shared<TestSecondaryCache>(2048);
|
||||
std::make_shared<TestSecondaryCache>(2048, true);
|
||||
std::shared_ptr<Cache> cache =
|
||||
NewCache(1024 /* capacity */, 0 /* num_shard_bits */,
|
||||
strict_capacity_limit, secondary_cache);
|
||||
@@ -2019,8 +2035,9 @@ class CacheWithStats : public CacheWrapper {
|
||||
|
||||
Status Insert(const Slice& key, Cache::ObjectPtr value,
|
||||
const CacheItemHelper* helper, size_t charge,
|
||||
Handle** handle = nullptr,
|
||||
Priority priority = Priority::LOW) override {
|
||||
Handle** handle = nullptr, Priority priority = Priority::LOW,
|
||||
const Slice& /*compressed*/ = Slice(),
|
||||
CompressionType /*type*/ = kNoCompression) override {
|
||||
insert_count_++;
|
||||
return target_->Insert(key, value, helper, charge, handle, priority);
|
||||
}
|
||||
@@ -2113,7 +2130,7 @@ TEST_P(DBSecondaryCacheTest, LRUCacheDumpLoadBasic) {
|
||||
// we have a new cache it is empty, then, before we do the Get, we do the
|
||||
// dumpload
|
||||
std::shared_ptr<TestSecondaryCache> secondary_cache =
|
||||
std::make_shared<TestSecondaryCache>(2048 * 1024);
|
||||
std::make_shared<TestSecondaryCache>(2048 * 1024, true);
|
||||
// This time with secondary cache
|
||||
base_cache = NewCache(1024 * 1024 /* capacity */, 0 /* num_shard_bits */,
|
||||
false /* strict_capacity_limit */, secondary_cache);
|
||||
@@ -2269,7 +2286,7 @@ TEST_P(DBSecondaryCacheTest, LRUCacheDumpLoadWithFilter) {
|
||||
// we have a new cache it is empty, then, before we do the Get, we do the
|
||||
// dumpload
|
||||
std::shared_ptr<TestSecondaryCache> secondary_cache =
|
||||
std::make_shared<TestSecondaryCache>(2048 * 1024);
|
||||
std::make_shared<TestSecondaryCache>(2048 * 1024, true);
|
||||
// This time with secondary_cache
|
||||
base_cache = NewCache(1024 * 1024 /* capacity */, 0 /* num_shard_bits */,
|
||||
false /* strict_capacity_limit */, secondary_cache);
|
||||
|
||||
Vendored
-33
@@ -9,37 +9,4 @@
|
||||
|
||||
namespace ROCKSDB_NAMESPACE {
|
||||
|
||||
namespace {
|
||||
|
||||
void NoopDelete(Cache::ObjectPtr, MemoryAllocator*) {}
|
||||
|
||||
size_t SliceSize(Cache::ObjectPtr obj) {
|
||||
return static_cast<Slice*>(obj)->size();
|
||||
}
|
||||
|
||||
Status SliceSaveTo(Cache::ObjectPtr from_obj, size_t from_offset, size_t length,
|
||||
char* out) {
|
||||
const Slice& slice = *static_cast<Slice*>(from_obj);
|
||||
std::memcpy(out, slice.data() + from_offset, length);
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status FailCreate(const Slice&, Cache::CreateContext*, MemoryAllocator*,
|
||||
Cache::ObjectPtr*, size_t*) {
|
||||
return Status::NotSupported("Only for dumping data into SecondaryCache");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Status SecondaryCache::InsertSaved(const Slice& key, const Slice& saved) {
|
||||
static Cache::CacheItemHelper helper_no_secondary{CacheEntryRole::kMisc,
|
||||
&NoopDelete};
|
||||
static Cache::CacheItemHelper helper{
|
||||
CacheEntryRole::kMisc, &NoopDelete, &SliceSize,
|
||||
&SliceSaveTo, &FailCreate, &helper_no_secondary};
|
||||
// NOTE: depends on Insert() being synchronous, not keeping pointer `&saved`
|
||||
return Insert(key, const_cast<Slice*>(&saved), &helper,
|
||||
/*force_insert=*/true);
|
||||
}
|
||||
|
||||
} // namespace ROCKSDB_NAMESPACE
|
||||
Vendored
+293
-17
@@ -5,7 +5,11 @@
|
||||
|
||||
#include "cache/secondary_cache_adapter.h"
|
||||
|
||||
#include <atomic>
|
||||
|
||||
#include "cache/tiered_secondary_cache.h"
|
||||
#include "monitoring/perf_context_imp.h"
|
||||
#include "test_util/sync_point.h"
|
||||
#include "util/cast_util.h"
|
||||
|
||||
namespace ROCKSDB_NAMESPACE {
|
||||
@@ -17,6 +21,7 @@ struct Dummy {
|
||||
};
|
||||
const Dummy kDummy{};
|
||||
Cache::ObjectPtr const kDummyObj = const_cast<Dummy*>(&kDummy);
|
||||
const char* kTieredCacheName = "TieredCache";
|
||||
} // namespace
|
||||
|
||||
// When CacheWithSecondaryAdapter is constructed with the distribute_cache_res
|
||||
@@ -98,7 +103,8 @@ CacheWithSecondaryAdapter::CacheWithSecondaryAdapter(
|
||||
// secondary cache is freed from the reservation.
|
||||
s = pri_cache_res_->UpdateCacheReservation(sec_capacity);
|
||||
assert(s.ok());
|
||||
sec_cache_res_ratio_ = (double)sec_capacity / target_->GetCapacity();
|
||||
sec_cache_res_ratio_.store((double)sec_capacity / target_->GetCapacity(),
|
||||
std::memory_order_relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,11 +113,11 @@ CacheWithSecondaryAdapter::~CacheWithSecondaryAdapter() {
|
||||
// use after free
|
||||
target_->SetEvictionCallback({});
|
||||
#ifndef NDEBUG
|
||||
if (distribute_cache_res_) {
|
||||
if (distribute_cache_res_ && !ratio_changed_) {
|
||||
size_t sec_capacity = 0;
|
||||
Status s = secondary_cache_->GetCapacity(sec_capacity);
|
||||
assert(s.ok());
|
||||
assert(pri_cache_res_->GetTotalReservedCacheSize() == sec_capacity);
|
||||
assert(pri_cache_res_->GetTotalMemoryUsed() == sec_capacity);
|
||||
}
|
||||
#endif // NDEBUG
|
||||
}
|
||||
@@ -119,7 +125,8 @@ CacheWithSecondaryAdapter::~CacheWithSecondaryAdapter() {
|
||||
bool CacheWithSecondaryAdapter::EvictionHandler(const Slice& key,
|
||||
Handle* handle, bool was_hit) {
|
||||
auto helper = GetCacheItemHelper(handle);
|
||||
if (helper->IsSecondaryCacheCompatible()) {
|
||||
if (helper->IsSecondaryCacheCompatible() &&
|
||||
adm_policy_ != TieredAdmissionPolicy::kAdmPolicyThreeQueue) {
|
||||
auto obj = target_->Value(handle);
|
||||
// Ignore dummy entry
|
||||
if (obj != kDummyObj) {
|
||||
@@ -225,15 +232,25 @@ Cache::Handle* CacheWithSecondaryAdapter::Promote(
|
||||
Status CacheWithSecondaryAdapter::Insert(const Slice& key, ObjectPtr value,
|
||||
const CacheItemHelper* helper,
|
||||
size_t charge, Handle** handle,
|
||||
Priority priority) {
|
||||
Priority priority,
|
||||
const Slice& compressed_value,
|
||||
CompressionType type) {
|
||||
Status s = target_->Insert(key, value, helper, charge, handle, priority);
|
||||
if (s.ok() && value == nullptr && distribute_cache_res_) {
|
||||
size_t sec_charge = static_cast<size_t>(charge * (sec_cache_res_ratio_));
|
||||
size_t sec_charge = static_cast<size_t>(
|
||||
charge * (sec_cache_res_ratio_.load(std::memory_order_relaxed)));
|
||||
s = secondary_cache_->Deflate(sec_charge);
|
||||
assert(s.ok());
|
||||
s = pri_cache_res_->UpdateCacheReservation(sec_charge, /*increase=*/false);
|
||||
assert(s.ok());
|
||||
}
|
||||
// Warm up the secondary cache with the compressed block. The secondary
|
||||
// cache may choose to ignore it based on the admission policy.
|
||||
if (value != nullptr && !compressed_value.empty() &&
|
||||
adm_policy_ == TieredAdmissionPolicy::kAdmPolicyThreeQueue) {
|
||||
Status status = secondary_cache_->InsertSaved(key, compressed_value, type);
|
||||
assert(status.ok() || status.IsNotSupported());
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
@@ -270,7 +287,10 @@ bool CacheWithSecondaryAdapter::Release(Handle* handle,
|
||||
ObjectPtr v = target_->Value(handle);
|
||||
if (v == nullptr && distribute_cache_res_) {
|
||||
size_t charge = target_->GetCharge(handle);
|
||||
size_t sec_charge = static_cast<size_t>(charge * (sec_cache_res_ratio_));
|
||||
size_t sec_charge = static_cast<size_t>(
|
||||
charge * (sec_cache_res_ratio_.load(std::memory_order_relaxed)));
|
||||
TEST_SYNC_POINT("CacheWithSecondaryAdapter::Release:ChargeSecCache1");
|
||||
TEST_SYNC_POINT("CacheWithSecondaryAdapter::Release:ChargeSecCache2");
|
||||
Status s = secondary_cache_->Inflate(sec_charge);
|
||||
assert(s.ok());
|
||||
s = pri_cache_res_->UpdateCacheReservation(sec_charge, /*increase=*/true);
|
||||
@@ -406,19 +426,240 @@ std::string CacheWithSecondaryAdapter::GetPrintableOptions() const {
|
||||
}
|
||||
|
||||
const char* CacheWithSecondaryAdapter::Name() const {
|
||||
// To the user, at least for now, configure the underlying cache with
|
||||
// a secondary cache. So we pretend to be that cache
|
||||
return target_->Name();
|
||||
if (distribute_cache_res_) {
|
||||
return kTieredCacheName;
|
||||
} else {
|
||||
// To the user, at least for now, configure the underlying cache with
|
||||
// a secondary cache. So we pretend to be that cache
|
||||
return target_->Name();
|
||||
}
|
||||
}
|
||||
|
||||
std::shared_ptr<Cache> NewTieredVolatileCache(
|
||||
TieredVolatileCacheOptions& opts) {
|
||||
if (!opts.cache_opts) {
|
||||
// Update the total cache capacity. If we're distributing cache reservations
|
||||
// to both primary and secondary, then update the pri_cache_res_reservation
|
||||
// as well. At the moment, we don't have a good way of handling the case
|
||||
// where the new capacity < total cache reservations.
|
||||
void CacheWithSecondaryAdapter::SetCapacity(size_t capacity) {
|
||||
size_t sec_capacity = static_cast<size_t>(
|
||||
capacity * (distribute_cache_res_
|
||||
? sec_cache_res_ratio_.load(std::memory_order_relaxed)
|
||||
: 0.0));
|
||||
size_t old_sec_capacity = 0;
|
||||
|
||||
if (distribute_cache_res_) {
|
||||
MutexLock m(&mutex_);
|
||||
|
||||
Status s = secondary_cache_->GetCapacity(old_sec_capacity);
|
||||
if (!s.ok()) {
|
||||
return;
|
||||
}
|
||||
if (old_sec_capacity > sec_capacity) {
|
||||
// We're shrinking the cache. We do things in the following order to
|
||||
// avoid a temporary spike in usage over the configured capacity -
|
||||
// 1. Lower the secondary cache capacity
|
||||
// 2. Credit an equal amount (by decreasing pri_cache_res_) to the
|
||||
// primary cache
|
||||
// 3. Decrease the primary cache capacity to the total budget
|
||||
s = secondary_cache_->SetCapacity(sec_capacity);
|
||||
if (s.ok()) {
|
||||
s = pri_cache_res_->UpdateCacheReservation(
|
||||
old_sec_capacity - sec_capacity,
|
||||
/*increase=*/false);
|
||||
assert(s.ok());
|
||||
target_->SetCapacity(capacity);
|
||||
}
|
||||
} else {
|
||||
// We're expanding the cache. Do it in the following order to avoid
|
||||
// unnecessary evictions -
|
||||
// 1. Increase the primary cache capacity to total budget
|
||||
// 2. Reserve additional memory in primary on behalf of secondary (by
|
||||
// increasing pri_cache_res_ reservation)
|
||||
// 3. Increase secondary cache capacity
|
||||
target_->SetCapacity(capacity);
|
||||
s = pri_cache_res_->UpdateCacheReservation(
|
||||
sec_capacity - old_sec_capacity,
|
||||
/*increase=*/true);
|
||||
assert(s.ok());
|
||||
s = secondary_cache_->SetCapacity(sec_capacity);
|
||||
assert(s.ok());
|
||||
}
|
||||
} else {
|
||||
// No cache reservation distribution. Just set the primary cache capacity.
|
||||
target_->SetCapacity(capacity);
|
||||
}
|
||||
}
|
||||
|
||||
Status CacheWithSecondaryAdapter::GetSecondaryCacheCapacity(
|
||||
size_t& size) const {
|
||||
return secondary_cache_->GetCapacity(size);
|
||||
}
|
||||
|
||||
Status CacheWithSecondaryAdapter::GetSecondaryCachePinnedUsage(
|
||||
size_t& size) const {
|
||||
Status s;
|
||||
if (distribute_cache_res_) {
|
||||
MutexLock m(&mutex_);
|
||||
size_t capacity = 0;
|
||||
s = secondary_cache_->GetCapacity(capacity);
|
||||
if (s.ok()) {
|
||||
size = capacity - pri_cache_res_->GetTotalMemoryUsed();
|
||||
} else {
|
||||
size = 0;
|
||||
}
|
||||
} else {
|
||||
size = 0;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
// Update the secondary/primary allocation ratio (remember, the primary
|
||||
// capacity is the total memory budget when distribute_cache_res_ is true).
|
||||
// When the ratio changes, we may accumulate some error in the calculations
|
||||
// for secondary cache inflate/deflate and pri_cache_res_ reservations.
|
||||
// This is due to the rounding of the reservation amount.
|
||||
//
|
||||
// We rely on the current pri_cache_res_ total memory used to estimate the
|
||||
// new secondary cache reservation after the ratio change. For this reason,
|
||||
// once the ratio is lowered to 0.0 (effectively disabling the secondary
|
||||
// cache and pri_cache_res_ total mem used going down to 0), we cannot
|
||||
// increase the ratio and re-enable it, We might remove this limitation
|
||||
// in the future.
|
||||
Status CacheWithSecondaryAdapter::UpdateCacheReservationRatio(
|
||||
double compressed_secondary_ratio) {
|
||||
if (!distribute_cache_res_ ||
|
||||
sec_cache_res_ratio_.load(std::memory_order_relaxed) == 0.0) {
|
||||
return Status::NotSupported();
|
||||
}
|
||||
|
||||
MutexLock m(&mutex_);
|
||||
size_t pri_capacity = target_->GetCapacity();
|
||||
size_t sec_capacity =
|
||||
static_cast<size_t>(pri_capacity * compressed_secondary_ratio);
|
||||
size_t old_sec_capacity;
|
||||
Status s = secondary_cache_->GetCapacity(old_sec_capacity);
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
|
||||
TEST_SYNC_POINT(
|
||||
"CacheWithSecondaryAdapter::UpdateCacheReservationRatio:Begin");
|
||||
|
||||
// There's a possible race condition here. Since the read of pri_cache_res_
|
||||
// memory used (secondary cache usage charged to primary cache), and the
|
||||
// change to sec_cache_res_ratio_ are not guarded by a mutex, its possible
|
||||
// that an Insert/Release in another thread might decrease/increase the
|
||||
// pri_cache_res_ reservation by the wrong amount. This should not be a
|
||||
// problem because updating the sec/pri ratio is a rare operation, and
|
||||
// the worst that can happen is we may over/under charge the secondary
|
||||
// cache usage by a little bit. But we do need to protect against
|
||||
// underflow of old_sec_reserved.
|
||||
// TODO: Make the accounting more accurate by tracking the total memory
|
||||
// reservation on the primary cache. This will also allow us to remove
|
||||
// the restriction of not being able to change the sec/pri ratio from
|
||||
// 0.0 to higher.
|
||||
size_t sec_charge_to_pri = pri_cache_res_->GetTotalMemoryUsed();
|
||||
size_t old_sec_reserved = (old_sec_capacity > sec_charge_to_pri)
|
||||
? (old_sec_capacity - sec_charge_to_pri)
|
||||
: 0;
|
||||
// Calculate the new secondary cache reservation
|
||||
size_t sec_reserved = static_cast<size_t>(
|
||||
old_sec_reserved *
|
||||
(double)(compressed_secondary_ratio /
|
||||
sec_cache_res_ratio_.load(std::memory_order_relaxed)));
|
||||
sec_cache_res_ratio_.store(compressed_secondary_ratio,
|
||||
std::memory_order_relaxed);
|
||||
if (sec_capacity > old_sec_capacity) {
|
||||
// We're increasing the ratio, thus ending up with a larger secondary
|
||||
// cache and a smaller usable primary cache capacity. Similar to
|
||||
// SetCapacity(), we try to avoid a temporary increase in total usage
|
||||
// beyond teh configured capacity -
|
||||
// 1. A higher secondary cache ratio means it gets a higher share of
|
||||
// cache reservations. So first account for that by deflating the
|
||||
// secondary cache
|
||||
// 2. Increase pri_cache_res_ reservation to reflect the new secondary
|
||||
// cache utilization (increase in capacity - increase in share of cache
|
||||
// reservation)
|
||||
// 3. Increase secondary cache capacity
|
||||
s = secondary_cache_->Deflate(sec_reserved - old_sec_reserved);
|
||||
assert(s.ok());
|
||||
s = pri_cache_res_->UpdateCacheReservation(
|
||||
(sec_capacity - old_sec_capacity) - (sec_reserved - old_sec_reserved),
|
||||
/*increase=*/true);
|
||||
assert(s.ok());
|
||||
s = secondary_cache_->SetCapacity(sec_capacity);
|
||||
assert(s.ok());
|
||||
} else {
|
||||
// We're shrinking the ratio. Try to avoid unnecessary evictions -
|
||||
// 1. Lower the secondary cache capacity
|
||||
// 2. Decrease pri_cache_res_ reservation to relect lower secondary
|
||||
// cache utilization (decrease in capacity - decrease in share of cache
|
||||
// reservations)
|
||||
// 3. Inflate the secondary cache to give it back the reduction in its
|
||||
// share of cache reservations
|
||||
s = secondary_cache_->SetCapacity(sec_capacity);
|
||||
if (s.ok()) {
|
||||
s = pri_cache_res_->UpdateCacheReservation(
|
||||
(old_sec_capacity - sec_capacity) - (old_sec_reserved - sec_reserved),
|
||||
/*increase=*/false);
|
||||
assert(s.ok());
|
||||
s = secondary_cache_->Inflate(old_sec_reserved - sec_reserved);
|
||||
assert(s.ok());
|
||||
}
|
||||
}
|
||||
|
||||
TEST_SYNC_POINT("CacheWithSecondaryAdapter::UpdateCacheReservationRatio:End");
|
||||
#ifndef NDEBUG
|
||||
// As mentioned in the function comments, we may accumulate some erros when
|
||||
// the ratio is changed. We set a flag here which disables some assertions
|
||||
// in the destructor
|
||||
ratio_changed_ = true;
|
||||
#endif
|
||||
return s;
|
||||
}
|
||||
|
||||
Status CacheWithSecondaryAdapter::UpdateAdmissionPolicy(
|
||||
TieredAdmissionPolicy adm_policy) {
|
||||
adm_policy_ = adm_policy;
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
std::shared_ptr<Cache> NewTieredCache(const TieredCacheOptions& _opts) {
|
||||
if (!_opts.cache_opts) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (opts.adm_policy >= TieredAdmissionPolicy::kAdmPolicyMax) {
|
||||
return nullptr;
|
||||
TieredCacheOptions opts = _opts;
|
||||
{
|
||||
bool valid_adm_policy = true;
|
||||
|
||||
switch (_opts.adm_policy) {
|
||||
case TieredAdmissionPolicy::kAdmPolicyAuto:
|
||||
// Select an appropriate default policy
|
||||
if (opts.adm_policy == TieredAdmissionPolicy::kAdmPolicyAuto) {
|
||||
if (opts.nvm_sec_cache) {
|
||||
opts.adm_policy = TieredAdmissionPolicy::kAdmPolicyThreeQueue;
|
||||
} else {
|
||||
opts.adm_policy = TieredAdmissionPolicy::kAdmPolicyPlaceholder;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case TieredAdmissionPolicy::kAdmPolicyPlaceholder:
|
||||
case TieredAdmissionPolicy::kAdmPolicyAllowCacheHits:
|
||||
if (opts.nvm_sec_cache) {
|
||||
valid_adm_policy = false;
|
||||
}
|
||||
break;
|
||||
case TieredAdmissionPolicy::kAdmPolicyThreeQueue:
|
||||
if (!opts.nvm_sec_cache) {
|
||||
valid_adm_policy = false;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
valid_adm_policy = false;
|
||||
}
|
||||
if (!valid_adm_policy) {
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
std::shared_ptr<Cache> cache;
|
||||
@@ -426,21 +667,56 @@ std::shared_ptr<Cache> NewTieredVolatileCache(
|
||||
LRUCacheOptions cache_opts =
|
||||
*(static_cast_with_check<LRUCacheOptions, ShardedCacheOptions>(
|
||||
opts.cache_opts));
|
||||
cache_opts.capacity += opts.comp_cache_opts.capacity;
|
||||
cache_opts.capacity = opts.total_capacity;
|
||||
cache = cache_opts.MakeSharedCache();
|
||||
} else if (opts.cache_type == PrimaryCacheType::kCacheTypeHCC) {
|
||||
HyperClockCacheOptions cache_opts =
|
||||
*(static_cast_with_check<HyperClockCacheOptions, ShardedCacheOptions>(
|
||||
opts.cache_opts));
|
||||
cache_opts.capacity += opts.comp_cache_opts.capacity;
|
||||
cache_opts.capacity = opts.total_capacity;
|
||||
cache = cache_opts.MakeSharedCache();
|
||||
} else {
|
||||
return nullptr;
|
||||
}
|
||||
std::shared_ptr<SecondaryCache> sec_cache;
|
||||
opts.comp_cache_opts.capacity = static_cast<size_t>(
|
||||
opts.total_capacity * opts.compressed_secondary_ratio);
|
||||
sec_cache = NewCompressedSecondaryCache(opts.comp_cache_opts);
|
||||
|
||||
if (opts.nvm_sec_cache) {
|
||||
if (opts.adm_policy == TieredAdmissionPolicy::kAdmPolicyThreeQueue) {
|
||||
sec_cache = std::make_shared<TieredSecondaryCache>(
|
||||
sec_cache, opts.nvm_sec_cache,
|
||||
TieredAdmissionPolicy::kAdmPolicyThreeQueue);
|
||||
} else {
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
return std::make_shared<CacheWithSecondaryAdapter>(
|
||||
cache, sec_cache, opts.adm_policy, /*distribute_cache_res=*/true);
|
||||
}
|
||||
|
||||
Status UpdateTieredCache(const std::shared_ptr<Cache>& cache,
|
||||
int64_t total_capacity,
|
||||
double compressed_secondary_ratio,
|
||||
TieredAdmissionPolicy adm_policy) {
|
||||
if (!cache || strcmp(cache->Name(), kTieredCacheName)) {
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
CacheWithSecondaryAdapter* tiered_cache =
|
||||
static_cast<CacheWithSecondaryAdapter*>(cache.get());
|
||||
|
||||
Status s;
|
||||
if (total_capacity > 0) {
|
||||
tiered_cache->SetCapacity(total_capacity);
|
||||
}
|
||||
if (compressed_secondary_ratio >= 0.0 && compressed_secondary_ratio <= 1.0) {
|
||||
s = tiered_cache->UpdateCacheReservationRatio(compressed_secondary_ratio);
|
||||
}
|
||||
if (adm_policy < TieredAdmissionPolicy::kAdmPolicyMax) {
|
||||
s = tiered_cache->UpdateAdmissionPolicy(adm_policy);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
} // namespace ROCKSDB_NAMESPACE
|
||||
Vendored
+21
-5
@@ -20,10 +20,12 @@ class CacheWithSecondaryAdapter : public CacheWrapper {
|
||||
|
||||
~CacheWithSecondaryAdapter() override;
|
||||
|
||||
Status Insert(const Slice& key, ObjectPtr value,
|
||||
const CacheItemHelper* helper, size_t charge,
|
||||
Handle** handle = nullptr,
|
||||
Priority priority = Priority::LOW) override;
|
||||
Status Insert(
|
||||
const Slice& key, ObjectPtr value, const CacheItemHelper* helper,
|
||||
size_t charge, Handle** handle = nullptr,
|
||||
Priority priority = Priority::LOW,
|
||||
const Slice& compressed_value = Slice(),
|
||||
CompressionType type = CompressionType::kNoCompression) override;
|
||||
|
||||
Handle* Lookup(const Slice& key, const CacheItemHelper* helper,
|
||||
CreateContext* create_context,
|
||||
@@ -43,6 +45,16 @@ class CacheWithSecondaryAdapter : public CacheWrapper {
|
||||
|
||||
const char* Name() const override;
|
||||
|
||||
void SetCapacity(size_t capacity) override;
|
||||
|
||||
Status GetSecondaryCacheCapacity(size_t& size) const override;
|
||||
|
||||
Status GetSecondaryCachePinnedUsage(size_t& size) const override;
|
||||
|
||||
Status UpdateCacheReservationRatio(double ratio);
|
||||
|
||||
Status UpdateAdmissionPolicy(TieredAdmissionPolicy adm_policy);
|
||||
|
||||
Cache* TEST_GetCache() { return target_.get(); }
|
||||
|
||||
SecondaryCache* TEST_GetSecondaryCache() { return secondary_cache_.get(); }
|
||||
@@ -72,7 +84,11 @@ class CacheWithSecondaryAdapter : public CacheWrapper {
|
||||
std::shared_ptr<ConcurrentCacheReservationManager> pri_cache_res_;
|
||||
// Fraction of a cache memory reservation to be assigned to the secondary
|
||||
// cache
|
||||
double sec_cache_res_ratio_;
|
||||
std::atomic<double> sec_cache_res_ratio_;
|
||||
mutable port::Mutex mutex_;
|
||||
#ifndef NDEBUG
|
||||
bool ratio_changed_ = false;
|
||||
#endif
|
||||
};
|
||||
|
||||
} // namespace ROCKSDB_NAMESPACE
|
||||
Vendored
+10
@@ -83,6 +83,16 @@ size_t ShardedCacheBase::GetCapacity() const {
|
||||
return capacity_;
|
||||
}
|
||||
|
||||
Status ShardedCacheBase::GetSecondaryCacheCapacity(size_t& size) const {
|
||||
size = 0;
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status ShardedCacheBase::GetSecondaryCachePinnedUsage(size_t& size) const {
|
||||
size = 0;
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
bool ShardedCacheBase::HasStrictCapacityLimit() const {
|
||||
MutexLock l(&config_mutex_);
|
||||
return strict_capacity_limit_;
|
||||
|
||||
Vendored
+8
-3
@@ -99,6 +99,8 @@ class ShardedCacheBase : public Cache {
|
||||
|
||||
bool HasStrictCapacityLimit() const override;
|
||||
size_t GetCapacity() const override;
|
||||
Status GetSecondaryCacheCapacity(size_t& size) const override;
|
||||
Status GetSecondaryCachePinnedUsage(size_t& size) const override;
|
||||
|
||||
using Cache::GetUsage;
|
||||
size_t GetUsage(Handle* handle) const override;
|
||||
@@ -170,9 +172,12 @@ class ShardedCache : public ShardedCacheBase {
|
||||
[s_c_l](CacheShard* cs) { cs->SetStrictCapacityLimit(s_c_l); });
|
||||
}
|
||||
|
||||
Status Insert(const Slice& key, ObjectPtr obj, const CacheItemHelper* helper,
|
||||
size_t charge, Handle** handle = nullptr,
|
||||
Priority priority = Priority::LOW) override {
|
||||
Status Insert(
|
||||
const Slice& key, ObjectPtr obj, const CacheItemHelper* helper,
|
||||
size_t charge, Handle** handle = nullptr,
|
||||
Priority priority = Priority::LOW,
|
||||
const Slice& /*compressed_value*/ = Slice(),
|
||||
CompressionType /*type*/ = CompressionType::kNoCompression) override {
|
||||
assert(helper);
|
||||
HashVal hash = CacheShard::ComputeHash(key, hash_seed_);
|
||||
auto h_out = reinterpret_cast<HandleImpl**>(handle);
|
||||
|
||||
Vendored
+119
@@ -0,0 +1,119 @@
|
||||
// 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).
|
||||
|
||||
#include "cache/tiered_secondary_cache.h"
|
||||
|
||||
namespace ROCKSDB_NAMESPACE {
|
||||
|
||||
// Creation callback for use in the lookup path. It calls the upper layer
|
||||
// create_cb to create the object, and optionally calls the compressed
|
||||
// secondary cache InsertSaved to save the compressed block. If
|
||||
// advise_erase is set, it means the primary cache wants the block to be
|
||||
// erased in the secondary cache, so we skip calling InsertSaved.
|
||||
//
|
||||
// For the time being, we assume that all blocks in the nvm tier belong to
|
||||
// the primary block cache (i.e CacheTier::kVolatileTier). That can be changed
|
||||
// if we implement demotion from the compressed secondary cache to the nvm
|
||||
// cache in the future.
|
||||
Status TieredSecondaryCache::MaybeInsertAndCreate(
|
||||
const Slice& data, CompressionType type, CacheTier source,
|
||||
Cache::CreateContext* ctx, MemoryAllocator* allocator,
|
||||
Cache::ObjectPtr* out_obj, size_t* out_charge) {
|
||||
TieredSecondaryCache::CreateContext* context =
|
||||
static_cast<TieredSecondaryCache::CreateContext*>(ctx);
|
||||
assert(source == CacheTier::kVolatileTier);
|
||||
if (!context->advise_erase && type != kNoCompression) {
|
||||
// Attempt to insert into compressed secondary cache
|
||||
// TODO: Don't hardcode the source
|
||||
context->comp_sec_cache->InsertSaved(*context->key, data, type, source)
|
||||
.PermitUncheckedError();
|
||||
}
|
||||
// Primary cache will accept the object, so call its helper to create
|
||||
// the object
|
||||
return context->helper->create_cb(data, type, source, context->inner_ctx,
|
||||
allocator, out_obj, out_charge);
|
||||
}
|
||||
|
||||
// The lookup first looks up in the compressed secondary cache. If its a miss,
|
||||
// then the nvm cache lookup is called. The cache item helper and create
|
||||
// context are wrapped in order to intercept the creation callback to make
|
||||
// the decision on promoting to the compressed secondary cache.
|
||||
std::unique_ptr<SecondaryCacheResultHandle> TieredSecondaryCache::Lookup(
|
||||
const Slice& key, const Cache::CacheItemHelper* helper,
|
||||
Cache::CreateContext* create_context, bool wait, bool advise_erase,
|
||||
bool& kept_in_sec_cache) {
|
||||
bool dummy = false;
|
||||
std::unique_ptr<SecondaryCacheResultHandle> result =
|
||||
target()->Lookup(key, helper, create_context, wait, advise_erase,
|
||||
/*kept_in_sec_cache=*/dummy);
|
||||
// We never want the item to spill back into the secondary cache
|
||||
kept_in_sec_cache = true;
|
||||
if (result) {
|
||||
assert(result->IsReady());
|
||||
return result;
|
||||
}
|
||||
|
||||
// If wait is true, then we can be a bit more efficient and avoid a memory
|
||||
// allocation for the CReateContext.
|
||||
const Cache::CacheItemHelper* outer_helper =
|
||||
TieredSecondaryCache::GetHelper();
|
||||
if (wait) {
|
||||
TieredSecondaryCache::CreateContext ctx;
|
||||
ctx.key = &key;
|
||||
ctx.advise_erase = advise_erase;
|
||||
ctx.helper = helper;
|
||||
ctx.inner_ctx = create_context;
|
||||
ctx.comp_sec_cache = target();
|
||||
|
||||
return nvm_sec_cache_->Lookup(key, outer_helper, &ctx, wait, advise_erase,
|
||||
kept_in_sec_cache);
|
||||
}
|
||||
|
||||
// If wait is false, i.e its an async lookup, we have to allocate a result
|
||||
// handle for tracking purposes. Embed the CreateContext inside the handle
|
||||
// so we need only allocate memory once instead of twice.
|
||||
std::unique_ptr<ResultHandle> handle(new ResultHandle());
|
||||
handle->ctx()->key = &key;
|
||||
handle->ctx()->advise_erase = advise_erase;
|
||||
handle->ctx()->helper = helper;
|
||||
handle->ctx()->inner_ctx = create_context;
|
||||
handle->ctx()->comp_sec_cache = target();
|
||||
handle->SetInnerHandle(nvm_sec_cache_->Lookup(
|
||||
key, outer_helper, handle->ctx(), wait, advise_erase, kept_in_sec_cache));
|
||||
if (!handle->inner_handle()) {
|
||||
handle.reset();
|
||||
} else {
|
||||
result.reset(handle.release());
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Call the nvm cache WaitAll to complete the lookups
|
||||
void TieredSecondaryCache::WaitAll(
|
||||
std::vector<SecondaryCacheResultHandle*> handles) {
|
||||
std::vector<SecondaryCacheResultHandle*> nvm_handles;
|
||||
std::vector<ResultHandle*> my_handles;
|
||||
nvm_handles.reserve(handles.size());
|
||||
for (auto handle : handles) {
|
||||
// The handle could belong to the compressed secondary cache. Skip if
|
||||
// that's the case.
|
||||
if (handle->IsReady()) {
|
||||
continue;
|
||||
}
|
||||
ResultHandle* hdl = static_cast<ResultHandle*>(handle);
|
||||
nvm_handles.push_back(hdl->inner_handle());
|
||||
my_handles.push_back(hdl);
|
||||
}
|
||||
nvm_sec_cache_->WaitAll(nvm_handles);
|
||||
for (auto handle : my_handles) {
|
||||
assert(handle->IsReady());
|
||||
auto nvm_handle = handle->inner_handle();
|
||||
handle->SetSize(nvm_handle->Size());
|
||||
handle->SetValue(nvm_handle->Value());
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace ROCKSDB_NAMESPACE
|
||||
Vendored
+155
@@ -0,0 +1,155 @@
|
||||
// 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 "rocksdb/cache.h"
|
||||
#include "rocksdb/secondary_cache.h"
|
||||
|
||||
namespace ROCKSDB_NAMESPACE {
|
||||
|
||||
// A SecondaryCache that implements stacking of a compressed secondary cache
|
||||
// and a non-volatile (local flash) cache. It implements an admission
|
||||
// policy of warming the bottommost tier (local flash) with compressed
|
||||
// blocks from the SST on misses, and on hits in the bottommost tier,
|
||||
// promoting to the compressed and/or primary block cache. The admission
|
||||
// policies of the primary block cache and compressed secondary cache remain
|
||||
// unchanged - promote on second access. There is no demotion ofablocks
|
||||
// evicted from a tier. They are just discarded.
|
||||
//
|
||||
// In order to properly handle compressed blocks directly read from SSTs, and
|
||||
// to allow writeback of blocks compressed by the compressed secondary
|
||||
// cache in the future, we make use of the compression type and source
|
||||
// cache tier arguments in InsertSaved.
|
||||
class TieredSecondaryCache : public SecondaryCacheWrapper {
|
||||
public:
|
||||
TieredSecondaryCache(std::shared_ptr<SecondaryCache> comp_sec_cache,
|
||||
std::shared_ptr<SecondaryCache> nvm_sec_cache,
|
||||
TieredAdmissionPolicy adm_policy)
|
||||
: SecondaryCacheWrapper(comp_sec_cache), nvm_sec_cache_(nvm_sec_cache) {
|
||||
#ifndef NDEBUG
|
||||
assert(adm_policy == TieredAdmissionPolicy::kAdmPolicyThreeQueue);
|
||||
#else
|
||||
(void)adm_policy;
|
||||
#endif
|
||||
}
|
||||
|
||||
~TieredSecondaryCache() override {}
|
||||
|
||||
const char* Name() const override { return "TieredSecondaryCache"; }
|
||||
|
||||
// This is a no-op as we currently don't allow demotion (i.e
|
||||
// insertion by the upper layer) of evicted blocks.
|
||||
virtual Status Insert(const Slice& /*key*/, Cache::ObjectPtr /*obj*/,
|
||||
const Cache::CacheItemHelper* /*helper*/,
|
||||
bool /*force_insert*/) override {
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
// Warm up the nvm tier directly
|
||||
virtual Status InsertSaved(
|
||||
const Slice& key, const Slice& saved,
|
||||
CompressionType type = CompressionType::kNoCompression,
|
||||
CacheTier source = CacheTier::kVolatileTier) override {
|
||||
return nvm_sec_cache_->InsertSaved(key, saved, type, source);
|
||||
}
|
||||
|
||||
virtual std::unique_ptr<SecondaryCacheResultHandle> Lookup(
|
||||
const Slice& key, const Cache::CacheItemHelper* helper,
|
||||
Cache::CreateContext* create_context, bool wait, bool advise_erase,
|
||||
bool& kept_in_sec_cache) override;
|
||||
|
||||
virtual void WaitAll(
|
||||
std::vector<SecondaryCacheResultHandle*> handles) override;
|
||||
|
||||
private:
|
||||
struct CreateContext : public Cache::CreateContext {
|
||||
const Slice* key;
|
||||
bool advise_erase;
|
||||
const Cache::CacheItemHelper* helper;
|
||||
Cache::CreateContext* inner_ctx;
|
||||
std::shared_ptr<SecondaryCacheResultHandle> inner_handle;
|
||||
SecondaryCache* comp_sec_cache;
|
||||
};
|
||||
|
||||
class ResultHandle : public SecondaryCacheResultHandle {
|
||||
public:
|
||||
~ResultHandle() override {}
|
||||
|
||||
bool IsReady() override {
|
||||
return !inner_handle_ || inner_handle_->IsReady();
|
||||
}
|
||||
|
||||
void Wait() override {
|
||||
inner_handle_->Wait();
|
||||
Complete();
|
||||
}
|
||||
|
||||
size_t Size() override { return size_; }
|
||||
|
||||
Cache::ObjectPtr Value() override { return value_; }
|
||||
|
||||
void Complete() {
|
||||
assert(IsReady());
|
||||
size_ = inner_handle_->Size();
|
||||
value_ = inner_handle_->Value();
|
||||
inner_handle_.reset();
|
||||
}
|
||||
|
||||
void SetInnerHandle(std::unique_ptr<SecondaryCacheResultHandle>&& handle) {
|
||||
inner_handle_ = std::move(handle);
|
||||
}
|
||||
|
||||
void SetSize(size_t size) { size_ = size; }
|
||||
|
||||
void SetValue(Cache::ObjectPtr val) { value_ = val; }
|
||||
|
||||
CreateContext* ctx() { return &ctx_; }
|
||||
|
||||
SecondaryCacheResultHandle* inner_handle() { return inner_handle_.get(); }
|
||||
|
||||
private:
|
||||
std::unique_ptr<SecondaryCacheResultHandle> inner_handle_;
|
||||
CreateContext ctx_;
|
||||
size_t size_;
|
||||
Cache::ObjectPtr value_;
|
||||
};
|
||||
|
||||
static void NoopDelete(Cache::ObjectPtr /*obj*/,
|
||||
MemoryAllocator* /*allocator*/) {
|
||||
assert(false);
|
||||
}
|
||||
static size_t ZeroSize(Cache::ObjectPtr /*obj*/) {
|
||||
assert(false);
|
||||
return 0;
|
||||
}
|
||||
static Status NoopSaveTo(Cache::ObjectPtr /*from_obj*/,
|
||||
size_t /*from_offset*/, size_t /*length*/,
|
||||
char* /*out_buf*/) {
|
||||
assert(false);
|
||||
return Status::OK();
|
||||
}
|
||||
static Status MaybeInsertAndCreate(const Slice& data, CompressionType type,
|
||||
CacheTier source,
|
||||
Cache::CreateContext* ctx,
|
||||
MemoryAllocator* allocator,
|
||||
Cache::ObjectPtr* out_obj,
|
||||
size_t* out_charge);
|
||||
|
||||
static const Cache::CacheItemHelper* GetHelper() {
|
||||
const static Cache::CacheItemHelper basic_helper(CacheEntryRole::kMisc,
|
||||
&NoopDelete);
|
||||
const static Cache::CacheItemHelper maybe_insert_and_create_helper{
|
||||
CacheEntryRole::kMisc, &NoopDelete, &ZeroSize,
|
||||
&NoopSaveTo, &MaybeInsertAndCreate, &basic_helper,
|
||||
};
|
||||
return &maybe_insert_and_create_helper;
|
||||
}
|
||||
|
||||
std::shared_ptr<SecondaryCache> comp_sec_cache_;
|
||||
std::shared_ptr<SecondaryCache> nvm_sec_cache_;
|
||||
};
|
||||
|
||||
} // namespace ROCKSDB_NAMESPACE
|
||||
Vendored
+711
@@ -0,0 +1,711 @@
|
||||
// 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).
|
||||
//
|
||||
#include "cache/compressed_secondary_cache.h"
|
||||
#include "cache/secondary_cache_adapter.h"
|
||||
#include "db/db_test_util.h"
|
||||
#include "rocksdb/cache.h"
|
||||
#include "rocksdb/secondary_cache.h"
|
||||
#include "typed_cache.h"
|
||||
#include "util/random.h"
|
||||
|
||||
namespace ROCKSDB_NAMESPACE {
|
||||
|
||||
class TestSecondaryCache : public SecondaryCache {
|
||||
public:
|
||||
explicit TestSecondaryCache(size_t capacity)
|
||||
: cache_(NewLRUCache(capacity, 0, false, 0.5 /* high_pri_pool_ratio */,
|
||||
nullptr, kDefaultToAdaptiveMutex,
|
||||
kDontChargeCacheMetadata)),
|
||||
num_insert_saved_(0),
|
||||
num_hits_(0),
|
||||
num_misses_(0) {}
|
||||
|
||||
const char* Name() const override { return "TestSecondaryCache"; }
|
||||
|
||||
Status Insert(const Slice& /*key*/, Cache::ObjectPtr /*value*/,
|
||||
const Cache::CacheItemHelper* /*helper*/,
|
||||
bool /*force_insert*/) override {
|
||||
assert(false);
|
||||
return Status::NotSupported();
|
||||
}
|
||||
|
||||
Status InsertSaved(const Slice& key, const Slice& saved,
|
||||
CompressionType type = kNoCompression,
|
||||
CacheTier source = CacheTier::kVolatileTier) override {
|
||||
CheckCacheKeyCommonPrefix(key);
|
||||
size_t size;
|
||||
char* buf;
|
||||
Status s;
|
||||
|
||||
num_insert_saved_++;
|
||||
size = saved.size();
|
||||
buf = new char[size + sizeof(uint64_t) + 2 * sizeof(uint16_t)];
|
||||
EncodeFixed64(buf, size);
|
||||
buf += sizeof(uint64_t);
|
||||
EncodeFixed16(buf, type);
|
||||
buf += sizeof(uint16_t);
|
||||
EncodeFixed16(buf, (uint16_t)source);
|
||||
buf += sizeof(uint16_t);
|
||||
memcpy(buf, saved.data(), size);
|
||||
buf -= sizeof(uint64_t) + 2 * sizeof(uint16_t);
|
||||
if (!s.ok()) {
|
||||
delete[] buf;
|
||||
return s;
|
||||
}
|
||||
return cache_.Insert(key, buf, size);
|
||||
}
|
||||
|
||||
std::unique_ptr<SecondaryCacheResultHandle> Lookup(
|
||||
const Slice& key, const Cache::CacheItemHelper* helper,
|
||||
Cache::CreateContext* create_context, bool wait, bool /*advise_erase*/,
|
||||
bool& kept_in_sec_cache) override {
|
||||
std::string key_str = key.ToString();
|
||||
TEST_SYNC_POINT_CALLBACK("TestSecondaryCache::Lookup", &key_str);
|
||||
|
||||
std::unique_ptr<SecondaryCacheResultHandle> secondary_handle;
|
||||
kept_in_sec_cache = false;
|
||||
|
||||
TypedHandle* handle = cache_.Lookup(key);
|
||||
if (handle) {
|
||||
num_hits_++;
|
||||
Cache::ObjectPtr value = nullptr;
|
||||
size_t charge = 0;
|
||||
Status s;
|
||||
char* ptr = cache_.Value(handle);
|
||||
CompressionType type;
|
||||
CacheTier source;
|
||||
size_t size = DecodeFixed64(ptr);
|
||||
ptr += sizeof(uint64_t);
|
||||
type = static_cast<CompressionType>(DecodeFixed16(ptr));
|
||||
ptr += sizeof(uint16_t);
|
||||
source = static_cast<CacheTier>(DecodeFixed16(ptr));
|
||||
assert(source == CacheTier::kVolatileTier);
|
||||
ptr += sizeof(uint16_t);
|
||||
s = helper->create_cb(Slice(ptr, size), type, source, create_context,
|
||||
/*alloc*/ nullptr, &value, &charge);
|
||||
if (s.ok()) {
|
||||
secondary_handle.reset(new TestSecondaryCacheResultHandle(
|
||||
cache_.get(), handle, value, charge, /*ready=*/wait));
|
||||
kept_in_sec_cache = true;
|
||||
} else {
|
||||
cache_.Release(handle);
|
||||
}
|
||||
} else {
|
||||
num_misses_++;
|
||||
}
|
||||
return secondary_handle;
|
||||
}
|
||||
|
||||
bool SupportForceErase() const override { return false; }
|
||||
|
||||
void Erase(const Slice& /*key*/) override {}
|
||||
|
||||
void WaitAll(std::vector<SecondaryCacheResultHandle*> handles) override {
|
||||
for (SecondaryCacheResultHandle* handle : handles) {
|
||||
TestSecondaryCacheResultHandle* sec_handle =
|
||||
static_cast<TestSecondaryCacheResultHandle*>(handle);
|
||||
EXPECT_FALSE(sec_handle->IsReady());
|
||||
sec_handle->SetReady();
|
||||
}
|
||||
}
|
||||
|
||||
std::string GetPrintableOptions() const override { return ""; }
|
||||
|
||||
uint32_t num_insert_saved() { return num_insert_saved_; }
|
||||
|
||||
uint32_t num_hits() { return num_hits_; }
|
||||
|
||||
uint32_t num_misses() { return num_misses_; }
|
||||
|
||||
void CheckCacheKeyCommonPrefix(const Slice& key) {
|
||||
Slice current_prefix(key.data(), OffsetableCacheKey::kCommonPrefixSize);
|
||||
if (ckey_prefix_.empty()) {
|
||||
ckey_prefix_ = current_prefix.ToString();
|
||||
} else {
|
||||
EXPECT_EQ(ckey_prefix_, current_prefix.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
class TestSecondaryCacheResultHandle : public SecondaryCacheResultHandle {
|
||||
public:
|
||||
TestSecondaryCacheResultHandle(Cache* cache, Cache::Handle* handle,
|
||||
Cache::ObjectPtr value, size_t size,
|
||||
bool ready)
|
||||
: cache_(cache),
|
||||
handle_(handle),
|
||||
value_(value),
|
||||
size_(size),
|
||||
is_ready_(ready) {}
|
||||
|
||||
~TestSecondaryCacheResultHandle() override { cache_->Release(handle_); }
|
||||
|
||||
bool IsReady() override { return is_ready_; }
|
||||
|
||||
void Wait() override {}
|
||||
|
||||
Cache::ObjectPtr Value() override {
|
||||
assert(is_ready_);
|
||||
return value_;
|
||||
}
|
||||
|
||||
size_t Size() override { return Value() ? size_ : 0; }
|
||||
|
||||
void SetReady() { is_ready_ = true; }
|
||||
|
||||
private:
|
||||
Cache* cache_;
|
||||
Cache::Handle* handle_;
|
||||
Cache::ObjectPtr value_;
|
||||
size_t size_;
|
||||
bool is_ready_;
|
||||
};
|
||||
|
||||
using SharedCache =
|
||||
BasicTypedSharedCacheInterface<char[], CacheEntryRole::kMisc>;
|
||||
using TypedHandle = SharedCache::TypedHandle;
|
||||
SharedCache cache_;
|
||||
uint32_t num_insert_saved_;
|
||||
uint32_t num_hits_;
|
||||
uint32_t num_misses_;
|
||||
std::string ckey_prefix_;
|
||||
};
|
||||
|
||||
class DBTieredSecondaryCacheTest : public DBTestBase {
|
||||
public:
|
||||
DBTieredSecondaryCacheTest()
|
||||
: DBTestBase("db_tiered_secondary_cache_test", /*env_do_fsync=*/true) {}
|
||||
|
||||
std::shared_ptr<Cache> NewCache(size_t pri_capacity,
|
||||
size_t compressed_capacity,
|
||||
size_t nvm_capacity,
|
||||
TieredAdmissionPolicy adm_policy =
|
||||
TieredAdmissionPolicy::kAdmPolicyAuto) {
|
||||
LRUCacheOptions lru_opts;
|
||||
TieredCacheOptions opts;
|
||||
lru_opts.capacity = 0;
|
||||
lru_opts.num_shard_bits = 0;
|
||||
lru_opts.high_pri_pool_ratio = 0;
|
||||
opts.cache_opts = &lru_opts;
|
||||
opts.cache_type = PrimaryCacheType::kCacheTypeLRU;
|
||||
opts.comp_cache_opts.capacity = 0;
|
||||
opts.comp_cache_opts.num_shard_bits = 0;
|
||||
opts.total_capacity = pri_capacity + compressed_capacity;
|
||||
opts.compressed_secondary_ratio =
|
||||
(double)compressed_capacity / opts.total_capacity;
|
||||
if (nvm_capacity > 0) {
|
||||
nvm_sec_cache_.reset(new TestSecondaryCache(nvm_capacity));
|
||||
opts.nvm_sec_cache = nvm_sec_cache_;
|
||||
}
|
||||
opts.adm_policy = adm_policy;
|
||||
cache_ = NewTieredCache(opts);
|
||||
assert(cache_ != nullptr);
|
||||
|
||||
return cache_;
|
||||
}
|
||||
|
||||
TestSecondaryCache* nvm_sec_cache() { return nvm_sec_cache_.get(); }
|
||||
|
||||
CompressedSecondaryCache* compressed_secondary_cache() {
|
||||
return static_cast<CompressedSecondaryCache*>(
|
||||
static_cast<CacheWithSecondaryAdapter*>(cache_.get())
|
||||
->TEST_GetSecondaryCache());
|
||||
}
|
||||
|
||||
private:
|
||||
std::shared_ptr<Cache> cache_;
|
||||
std::shared_ptr<TestSecondaryCache> nvm_sec_cache_;
|
||||
};
|
||||
|
||||
// In this test, the block size is set to 4096. Each value is 1007 bytes, so
|
||||
// each data block contains exactly 4 KV pairs. Metadata blocks are not
|
||||
// cached, so we can accurately estimate the cache usage.
|
||||
TEST_F(DBTieredSecondaryCacheTest, BasicTest) {
|
||||
if (!LZ4_Supported()) {
|
||||
ROCKSDB_GTEST_SKIP("This test requires LZ4 support.");
|
||||
return;
|
||||
}
|
||||
|
||||
BlockBasedTableOptions table_options;
|
||||
// We want a block cache of size 5KB, and a compressed secondary cache of
|
||||
// size 5KB. However, we specify a block cache size of 256KB here in order
|
||||
// to take into account the cache reservation in the block cache on
|
||||
// behalf of the compressed cache. The unit of cache reservation is 256KB.
|
||||
// The effective block cache capacity will be calculated as 256 + 5 = 261KB,
|
||||
// and 256KB will be reserved for the compressed cache, leaving 5KB for
|
||||
// the primary block cache. We only have to worry about this here because
|
||||
// the cache size is so small.
|
||||
table_options.block_cache = NewCache(256 * 1024, 5 * 1024, 256 * 1024);
|
||||
table_options.block_size = 4 * 1024;
|
||||
table_options.cache_index_and_filter_blocks = false;
|
||||
Options options = GetDefaultOptions();
|
||||
options.create_if_missing = true;
|
||||
options.table_factory.reset(NewBlockBasedTableFactory(table_options));
|
||||
|
||||
// Disable paranoid_file_checks so that flush will not read back the newly
|
||||
// written file
|
||||
options.paranoid_file_checks = false;
|
||||
DestroyAndReopen(options);
|
||||
Random rnd(301);
|
||||
const int N = 256;
|
||||
for (int i = 0; i < N; i++) {
|
||||
std::string p_v;
|
||||
test::CompressibleString(&rnd, 0.5, 1007, &p_v);
|
||||
ASSERT_OK(Put(Key(i), p_v));
|
||||
}
|
||||
|
||||
ASSERT_OK(Flush());
|
||||
|
||||
// The first 2 Gets, for keys 0 and 5, will load the corresponding data
|
||||
// blocks as they will be cache misses. The nvm secondary cache will be
|
||||
// warmed up with the compressed blocks
|
||||
std::string v = Get(Key(0));
|
||||
ASSERT_EQ(1007, v.size());
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 1u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 1u);
|
||||
|
||||
v = Get(Key(5));
|
||||
ASSERT_EQ(1007, v.size());
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 2u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 2u);
|
||||
|
||||
// At this point, the nvm cache is warmed up with the data blocks for 0
|
||||
// and 5. The next Get will lookup the block in nvm and will be a hit.
|
||||
// It will be created as a standalone entry in memory, and a placeholder
|
||||
// will be inserted in the primary and compressed caches.
|
||||
v = Get(Key(0));
|
||||
ASSERT_EQ(1007, v.size());
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 2u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 2u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_hits(), 1u);
|
||||
|
||||
// For this Get, the primary and compressed only have placeholders for
|
||||
// the required data block. So we will lookup the nvm cache and find the
|
||||
// block there. This time, the block will be promoted to the primary
|
||||
// block cache. No promotion to the compressed secondary cache happens,
|
||||
// and it will retain the placeholder.
|
||||
v = Get(Key(0));
|
||||
ASSERT_EQ(1007, v.size());
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 2u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 2u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_hits(), 2u);
|
||||
|
||||
// This Get will find the data block in the primary cache.
|
||||
v = Get(Key(0));
|
||||
ASSERT_EQ(1007, v.size());
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 2u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 2u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_hits(), 2u);
|
||||
|
||||
// We repeat the sequence for key 5. This will end up evicting the block
|
||||
// for 0 from the in-memory cache.
|
||||
v = Get(Key(5));
|
||||
ASSERT_EQ(1007, v.size());
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 2u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 2u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_hits(), 3u);
|
||||
|
||||
v = Get(Key(5));
|
||||
ASSERT_EQ(1007, v.size());
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 2u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 2u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_hits(), 4u);
|
||||
|
||||
v = Get(Key(5));
|
||||
ASSERT_EQ(1007, v.size());
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 2u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 2u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_hits(), 4u);
|
||||
|
||||
// This Get for key 0 will find the data block in nvm. Since the compressed
|
||||
// cache still has the placeholder, the block (compressed) will be
|
||||
// admitted. It is theh inserted into the primary as a standalone entry.
|
||||
v = Get(Key(0));
|
||||
ASSERT_EQ(1007, v.size());
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 2u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 2u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_hits(), 5u);
|
||||
|
||||
// This Get for key 0 will find the data block in the compressed secondary
|
||||
// cache.
|
||||
v = Get(Key(0));
|
||||
ASSERT_EQ(1007, v.size());
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 2u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 2u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_hits(), 5u);
|
||||
|
||||
Destroy(options);
|
||||
}
|
||||
|
||||
// This test is very similar to BasicTest, except it calls MultiGet rather
|
||||
// than Get, in order to exercise the async lookup and WaitAll path.
|
||||
TEST_F(DBTieredSecondaryCacheTest, BasicMultiGetTest) {
|
||||
if (!LZ4_Supported()) {
|
||||
ROCKSDB_GTEST_SKIP("This test requires LZ4 support.");
|
||||
return;
|
||||
}
|
||||
|
||||
BlockBasedTableOptions table_options;
|
||||
table_options.block_cache = NewCache(260 * 1024, 10 * 1024, 256 * 1024);
|
||||
table_options.block_size = 4 * 1024;
|
||||
table_options.cache_index_and_filter_blocks = false;
|
||||
Options options = GetDefaultOptions();
|
||||
options.create_if_missing = true;
|
||||
options.table_factory.reset(NewBlockBasedTableFactory(table_options));
|
||||
|
||||
options.paranoid_file_checks = false;
|
||||
DestroyAndReopen(options);
|
||||
Random rnd(301);
|
||||
const int N = 256;
|
||||
for (int i = 0; i < N; i++) {
|
||||
std::string p_v;
|
||||
test::CompressibleString(&rnd, 0.5, 1007, &p_v);
|
||||
ASSERT_OK(Put(Key(i), p_v));
|
||||
}
|
||||
|
||||
ASSERT_OK(Flush());
|
||||
|
||||
std::vector<std::string> keys;
|
||||
std::vector<std::string> values;
|
||||
|
||||
keys.push_back(Key(0));
|
||||
keys.push_back(Key(4));
|
||||
keys.push_back(Key(8));
|
||||
values = MultiGet(keys, /*snapshot=*/nullptr, /*async=*/true);
|
||||
ASSERT_EQ(values.size(), keys.size());
|
||||
for (auto value : values) {
|
||||
ASSERT_EQ(1007, value.size());
|
||||
}
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 3u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 3u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_hits(), 0u);
|
||||
|
||||
keys.clear();
|
||||
values.clear();
|
||||
keys.push_back(Key(12));
|
||||
keys.push_back(Key(16));
|
||||
keys.push_back(Key(20));
|
||||
values = MultiGet(keys, /*snapshot=*/nullptr, /*async=*/true);
|
||||
ASSERT_EQ(values.size(), keys.size());
|
||||
for (auto value : values) {
|
||||
ASSERT_EQ(1007, value.size());
|
||||
}
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 6u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 6u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_hits(), 0u);
|
||||
|
||||
keys.clear();
|
||||
values.clear();
|
||||
keys.push_back(Key(0));
|
||||
keys.push_back(Key(4));
|
||||
keys.push_back(Key(8));
|
||||
values = MultiGet(keys, /*snapshot=*/nullptr, /*async=*/true);
|
||||
ASSERT_EQ(values.size(), keys.size());
|
||||
for (auto value : values) {
|
||||
ASSERT_EQ(1007, value.size());
|
||||
}
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 6u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 6u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_hits(), 3u);
|
||||
|
||||
keys.clear();
|
||||
values.clear();
|
||||
keys.push_back(Key(0));
|
||||
keys.push_back(Key(4));
|
||||
keys.push_back(Key(8));
|
||||
values = MultiGet(keys, /*snapshot=*/nullptr, /*async=*/true);
|
||||
ASSERT_EQ(values.size(), keys.size());
|
||||
for (auto value : values) {
|
||||
ASSERT_EQ(1007, value.size());
|
||||
}
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 6u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 6u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_hits(), 6u);
|
||||
|
||||
keys.clear();
|
||||
values.clear();
|
||||
keys.push_back(Key(0));
|
||||
keys.push_back(Key(4));
|
||||
keys.push_back(Key(8));
|
||||
values = MultiGet(keys, /*snapshot=*/nullptr, /*async=*/true);
|
||||
ASSERT_EQ(values.size(), keys.size());
|
||||
for (auto value : values) {
|
||||
ASSERT_EQ(1007, value.size());
|
||||
}
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 6u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 6u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_hits(), 6u);
|
||||
|
||||
keys.clear();
|
||||
values.clear();
|
||||
keys.push_back(Key(12));
|
||||
keys.push_back(Key(16));
|
||||
keys.push_back(Key(20));
|
||||
values = MultiGet(keys, /*snapshot=*/nullptr, /*async=*/true);
|
||||
ASSERT_EQ(values.size(), keys.size());
|
||||
for (auto value : values) {
|
||||
ASSERT_EQ(1007, value.size());
|
||||
}
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 6u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 6u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_hits(), 9u);
|
||||
|
||||
keys.clear();
|
||||
values.clear();
|
||||
keys.push_back(Key(12));
|
||||
keys.push_back(Key(16));
|
||||
keys.push_back(Key(20));
|
||||
values = MultiGet(keys, /*snapshot=*/nullptr, /*async=*/true);
|
||||
ASSERT_EQ(values.size(), keys.size());
|
||||
for (auto value : values) {
|
||||
ASSERT_EQ(1007, value.size());
|
||||
}
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 6u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 6u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_hits(), 12u);
|
||||
|
||||
keys.clear();
|
||||
values.clear();
|
||||
keys.push_back(Key(12));
|
||||
keys.push_back(Key(16));
|
||||
keys.push_back(Key(20));
|
||||
values = MultiGet(keys, /*snapshot=*/nullptr, /*async=*/true);
|
||||
ASSERT_EQ(values.size(), keys.size());
|
||||
for (auto value : values) {
|
||||
ASSERT_EQ(1007, value.size());
|
||||
}
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 6u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 6u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_hits(), 12u);
|
||||
|
||||
Destroy(options);
|
||||
}
|
||||
|
||||
TEST_F(DBTieredSecondaryCacheTest, WaitAllTest) {
|
||||
if (!LZ4_Supported()) {
|
||||
ROCKSDB_GTEST_SKIP("This test requires LZ4 support.");
|
||||
return;
|
||||
}
|
||||
|
||||
BlockBasedTableOptions table_options;
|
||||
table_options.block_cache = NewCache(250 * 1024, 20 * 1024, 256 * 1024);
|
||||
table_options.block_size = 4 * 1024;
|
||||
table_options.cache_index_and_filter_blocks = false;
|
||||
Options options = GetDefaultOptions();
|
||||
options.create_if_missing = true;
|
||||
options.table_factory.reset(NewBlockBasedTableFactory(table_options));
|
||||
|
||||
options.paranoid_file_checks = false;
|
||||
DestroyAndReopen(options);
|
||||
Random rnd(301);
|
||||
const int N = 256;
|
||||
for (int i = 0; i < N; i++) {
|
||||
std::string p_v;
|
||||
test::CompressibleString(&rnd, 0.5, 1007, &p_v);
|
||||
ASSERT_OK(Put(Key(i), p_v));
|
||||
}
|
||||
|
||||
ASSERT_OK(Flush());
|
||||
|
||||
std::vector<std::string> keys;
|
||||
std::vector<std::string> values;
|
||||
|
||||
keys.push_back(Key(0));
|
||||
keys.push_back(Key(4));
|
||||
keys.push_back(Key(8));
|
||||
values = MultiGet(keys, /*snapshot=*/nullptr, /*async=*/true);
|
||||
ASSERT_EQ(values.size(), keys.size());
|
||||
for (auto value : values) {
|
||||
ASSERT_EQ(1007, value.size());
|
||||
}
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 3u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 3u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_hits(), 0u);
|
||||
|
||||
keys.clear();
|
||||
values.clear();
|
||||
keys.push_back(Key(12));
|
||||
keys.push_back(Key(16));
|
||||
keys.push_back(Key(20));
|
||||
values = MultiGet(keys, /*snapshot=*/nullptr, /*async=*/true);
|
||||
ASSERT_EQ(values.size(), keys.size());
|
||||
for (auto value : values) {
|
||||
ASSERT_EQ(1007, value.size());
|
||||
}
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 6u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 6u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_hits(), 0u);
|
||||
|
||||
// Insert placeholders for 4 in primary and compressed
|
||||
std::string val = Get(Key(4));
|
||||
|
||||
// Force placeholder 4 out of primary
|
||||
keys.clear();
|
||||
values.clear();
|
||||
keys.push_back(Key(24));
|
||||
keys.push_back(Key(28));
|
||||
keys.push_back(Key(32));
|
||||
keys.push_back(Key(36));
|
||||
values = MultiGet(keys, /*snapshot=*/nullptr, /*async=*/true);
|
||||
ASSERT_EQ(values.size(), keys.size());
|
||||
for (auto value : values) {
|
||||
ASSERT_EQ(1007, value.size());
|
||||
}
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 10u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 10u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_hits(), 1u);
|
||||
|
||||
// Now read 4 again. This will create a placeholder in primary, and insert
|
||||
// in compressed secondary since it already has a placeholder
|
||||
val = Get(Key(4));
|
||||
|
||||
// Now read 0, 4 and 8. While 4 is already in the compressed secondary
|
||||
// cache, 0 and 8 will be read asynchronously from the nvm tier. The
|
||||
// WaitAll will be called for all 3 blocks.
|
||||
keys.clear();
|
||||
values.clear();
|
||||
keys.push_back(Key(0));
|
||||
keys.push_back(Key(4));
|
||||
keys.push_back(Key(8));
|
||||
values = MultiGet(keys, /*snapshot=*/nullptr, /*async=*/true);
|
||||
ASSERT_EQ(values.size(), keys.size());
|
||||
for (auto value : values) {
|
||||
ASSERT_EQ(1007, value.size());
|
||||
}
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 10u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 10u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_hits(), 4u);
|
||||
|
||||
Destroy(options);
|
||||
}
|
||||
|
||||
// This test is for iteration. It iterates through a set of keys in two
|
||||
// passes. First pass loads the compressed blocks into the nvm tier, and
|
||||
// the second pass should hit all of those blocks.
|
||||
TEST_F(DBTieredSecondaryCacheTest, IterateTest) {
|
||||
if (!LZ4_Supported()) {
|
||||
ROCKSDB_GTEST_SKIP("This test requires LZ4 support.");
|
||||
return;
|
||||
}
|
||||
|
||||
BlockBasedTableOptions table_options;
|
||||
table_options.block_cache = NewCache(250 * 1024, 10 * 1024, 256 * 1024);
|
||||
table_options.block_size = 4 * 1024;
|
||||
table_options.cache_index_and_filter_blocks = false;
|
||||
Options options = GetDefaultOptions();
|
||||
options.create_if_missing = true;
|
||||
options.table_factory.reset(NewBlockBasedTableFactory(table_options));
|
||||
|
||||
options.paranoid_file_checks = false;
|
||||
DestroyAndReopen(options);
|
||||
Random rnd(301);
|
||||
const int N = 256;
|
||||
for (int i = 0; i < N; i++) {
|
||||
std::string p_v;
|
||||
test::CompressibleString(&rnd, 0.5, 1007, &p_v);
|
||||
ASSERT_OK(Put(Key(i), p_v));
|
||||
}
|
||||
|
||||
ASSERT_OK(Flush());
|
||||
|
||||
ReadOptions ro;
|
||||
ro.readahead_size = 256 * 1024;
|
||||
auto iter = dbfull()->NewIterator(ro);
|
||||
iter->SeekToFirst();
|
||||
for (int i = 0; i < 31; ++i) {
|
||||
ASSERT_EQ(Key(i), iter->key().ToString());
|
||||
ASSERT_EQ(1007, iter->value().size());
|
||||
iter->Next();
|
||||
}
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 8u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 8u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_hits(), 0u);
|
||||
delete iter;
|
||||
|
||||
iter = dbfull()->NewIterator(ro);
|
||||
iter->SeekToFirst();
|
||||
for (int i = 0; i < 31; ++i) {
|
||||
ASSERT_EQ(Key(i), iter->key().ToString());
|
||||
ASSERT_EQ(1007, iter->value().size());
|
||||
iter->Next();
|
||||
}
|
||||
ASSERT_EQ(nvm_sec_cache()->num_insert_saved(), 8u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_misses(), 8u);
|
||||
ASSERT_EQ(nvm_sec_cache()->num_hits(), 8u);
|
||||
delete iter;
|
||||
|
||||
Destroy(options);
|
||||
}
|
||||
|
||||
class DBTieredAdmPolicyTest
|
||||
: public DBTieredSecondaryCacheTest,
|
||||
public testing::WithParamInterface<TieredAdmissionPolicy> {};
|
||||
|
||||
TEST_P(DBTieredAdmPolicyTest, CompressedOnlyTest) {
|
||||
if (!LZ4_Supported()) {
|
||||
ROCKSDB_GTEST_SKIP("This test requires LZ4 support.");
|
||||
return;
|
||||
}
|
||||
|
||||
BlockBasedTableOptions table_options;
|
||||
// We want a block cache of size 10KB, and a compressed secondary cache of
|
||||
// size 10KB. However, we specify a block cache size of 256KB here in order
|
||||
// to take into account the cache reservation in the block cache on
|
||||
// behalf of the compressed cache. The unit of cache reservation is 256KB.
|
||||
// The effective block cache capacity will be calculated as 256 + 10 = 266KB,
|
||||
// and 256KB will be reserved for the compressed cache, leaving 10KB for
|
||||
// the primary block cache. We only have to worry about this here because
|
||||
// the cache size is so small.
|
||||
table_options.block_cache = NewCache(256 * 1024, 10 * 1024, 0, GetParam());
|
||||
table_options.block_size = 4 * 1024;
|
||||
table_options.cache_index_and_filter_blocks = false;
|
||||
Options options = GetDefaultOptions();
|
||||
options.create_if_missing = true;
|
||||
options.table_factory.reset(NewBlockBasedTableFactory(table_options));
|
||||
|
||||
size_t comp_cache_usage = compressed_secondary_cache()->TEST_GetUsage();
|
||||
// Disable paranoid_file_checks so that flush will not read back the newly
|
||||
// written file
|
||||
options.paranoid_file_checks = false;
|
||||
DestroyAndReopen(options);
|
||||
Random rnd(301);
|
||||
const int N = 256;
|
||||
for (int i = 0; i < N; i++) {
|
||||
std::string p_v;
|
||||
test::CompressibleString(&rnd, 0.5, 1007, &p_v);
|
||||
ASSERT_OK(Put(Key(i), p_v));
|
||||
}
|
||||
|
||||
ASSERT_OK(Flush());
|
||||
|
||||
// The first 2 Gets, for keys 0 and 5, will load the corresponding data
|
||||
// blocks as they will be cache misses. Since this is a 2-tier cache (
|
||||
// primary and compressed), no warm-up should happen with the compressed
|
||||
// blocks.
|
||||
std::string v = Get(Key(0));
|
||||
ASSERT_EQ(1007, v.size());
|
||||
|
||||
v = Get(Key(5));
|
||||
ASSERT_EQ(1007, v.size());
|
||||
|
||||
ASSERT_EQ(compressed_secondary_cache()->TEST_GetUsage(), comp_cache_usage);
|
||||
|
||||
Destroy(options);
|
||||
}
|
||||
|
||||
INSTANTIATE_TEST_CASE_P(
|
||||
DBTieredAdmPolicyTest, DBTieredAdmPolicyTest,
|
||||
::testing::Values(TieredAdmissionPolicy::kAdmPolicyAuto,
|
||||
TieredAdmissionPolicy::kAdmPolicyPlaceholder,
|
||||
TieredAdmissionPolicy::kAdmPolicyAllowCacheHits));
|
||||
|
||||
} // namespace ROCKSDB_NAMESPACE
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
ROCKSDB_NAMESPACE::port::InstallStackTraceHandler();
|
||||
::testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
Vendored
+17
-11
@@ -234,15 +234,19 @@ class FullTypedCacheHelperFns : public BasicTypedCacheHelperFns<TValue> {
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
static Status Create(const Slice& data, CreateContext* context,
|
||||
static Status Create(const Slice& data, CompressionType type,
|
||||
CacheTier source, CreateContext* context,
|
||||
MemoryAllocator* allocator, ObjectPtr* out_obj,
|
||||
size_t* out_charge) {
|
||||
std::unique_ptr<TValue> value = nullptr;
|
||||
if (source != CacheTier::kVolatileTier) {
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
if constexpr (sizeof(TCreateContext) > 0) {
|
||||
TCreateContext* tcontext = static_cast<TCreateContext*>(context);
|
||||
tcontext->Create(&value, out_charge, data, allocator);
|
||||
tcontext->Create(&value, out_charge, data, type, allocator);
|
||||
} else {
|
||||
TCreateContext::Create(&value, out_charge, data, allocator);
|
||||
TCreateContext::Create(&value, out_charge, data, type, allocator);
|
||||
}
|
||||
*out_obj = UpCastValue(value.release());
|
||||
return Status::OK();
|
||||
@@ -301,13 +305,15 @@ class FullTypedCacheInterface
|
||||
inline Status InsertFull(
|
||||
const Slice& key, TValuePtr value, size_t charge,
|
||||
TypedHandle** handle = nullptr, Priority priority = Priority::LOW,
|
||||
CacheTier lowest_used_cache_tier = CacheTier::kNonVolatileBlockTier) {
|
||||
CacheTier lowest_used_cache_tier = CacheTier::kNonVolatileBlockTier,
|
||||
const Slice& compressed = Slice(),
|
||||
CompressionType type = CompressionType::kNoCompression) {
|
||||
auto untyped_handle = reinterpret_cast<Handle**>(handle);
|
||||
auto helper = lowest_used_cache_tier == CacheTier::kNonVolatileBlockTier
|
||||
auto helper = lowest_used_cache_tier > CacheTier::kVolatileTier
|
||||
? GetFullHelper()
|
||||
: GetBasicHelper();
|
||||
return this->cache_->Insert(key, UpCastValue(value), helper, charge,
|
||||
untyped_handle, priority);
|
||||
untyped_handle, priority, compressed, type);
|
||||
}
|
||||
|
||||
// Like SecondaryCache::InsertSaved, with SecondaryCache compatibility
|
||||
@@ -319,9 +325,9 @@ class FullTypedCacheInterface
|
||||
size_t* out_charge = nullptr) {
|
||||
ObjectPtr value;
|
||||
size_t charge;
|
||||
Status st = GetFullHelper()->create_cb(data, create_context,
|
||||
this->cache_->memory_allocator(),
|
||||
&value, &charge);
|
||||
Status st = GetFullHelper()->create_cb(
|
||||
data, kNoCompression, CacheTier::kVolatileTier, create_context,
|
||||
this->cache_->memory_allocator(), &value, &charge);
|
||||
if (out_charge) {
|
||||
*out_charge = charge;
|
||||
}
|
||||
@@ -340,7 +346,7 @@ class FullTypedCacheInterface
|
||||
const Slice& key, TCreateContext* create_context = nullptr,
|
||||
Priority priority = Priority::LOW, Statistics* stats = nullptr,
|
||||
CacheTier lowest_used_cache_tier = CacheTier::kNonVolatileBlockTier) {
|
||||
if (lowest_used_cache_tier == CacheTier::kNonVolatileBlockTier) {
|
||||
if (lowest_used_cache_tier > CacheTier::kVolatileTier) {
|
||||
return reinterpret_cast<TypedHandle*>(this->cache_->Lookup(
|
||||
key, GetFullHelper(), create_context, priority, stats));
|
||||
} else {
|
||||
@@ -352,7 +358,7 @@ class FullTypedCacheInterface
|
||||
inline void StartAsyncLookupFull(
|
||||
TypedAsyncLookupHandle& async_handle,
|
||||
CacheTier lowest_used_cache_tier = CacheTier::kNonVolatileBlockTier) {
|
||||
if (lowest_used_cache_tier == CacheTier::kNonVolatileBlockTier) {
|
||||
if (lowest_used_cache_tier > CacheTier::kVolatileTier) {
|
||||
async_handle.helper = GetFullHelper();
|
||||
this->cache_->StartAsyncLookup(async_handle);
|
||||
} else {
|
||||
|
||||
+25
-11
@@ -19,6 +19,14 @@
|
||||
|
||||
namespace ROCKSDB_NAMESPACE {
|
||||
|
||||
inline static SequenceNumber GetSeqNum(const DBImpl* db, const Snapshot* s) {
|
||||
if (s) {
|
||||
return s->GetSequenceNumber();
|
||||
} else {
|
||||
return db->GetLatestSequenceNumber();
|
||||
}
|
||||
}
|
||||
|
||||
Status ArenaWrappedDBIter::GetProperty(std::string prop_name,
|
||||
std::string* prop) {
|
||||
if (prop_name == "rocksdb.iterator.super-version-number") {
|
||||
@@ -54,7 +62,9 @@ void ArenaWrappedDBIter::Init(
|
||||
}
|
||||
}
|
||||
|
||||
Status ArenaWrappedDBIter::Refresh() {
|
||||
Status ArenaWrappedDBIter::Refresh() { return Refresh(nullptr); }
|
||||
|
||||
Status ArenaWrappedDBIter::Refresh(const Snapshot* snapshot) {
|
||||
if (cfd_ == nullptr || db_impl_ == nullptr || !allow_refresh_) {
|
||||
return Status::NotSupported("Creating renew iterator is not allowed.");
|
||||
}
|
||||
@@ -63,6 +73,10 @@ Status ArenaWrappedDBIter::Refresh() {
|
||||
// correct behavior. Will be corrected automatically when we take a snapshot
|
||||
// here for the case of WritePreparedTxnDB.
|
||||
uint64_t cur_sv_number = cfd_->GetSuperVersionNumber();
|
||||
// If we recreate a new internal iterator below (NewInternalIterator()),
|
||||
// we will pass in read_options_. We need to make sure it
|
||||
// has the right snapshot.
|
||||
read_options_.snapshot = snapshot;
|
||||
TEST_SYNC_POINT("ArenaWrappedDBIter::Refresh:1");
|
||||
TEST_SYNC_POINT("ArenaWrappedDBIter::Refresh:2");
|
||||
auto reinit_internal_iter = [&]() {
|
||||
@@ -72,18 +86,19 @@ Status ArenaWrappedDBIter::Refresh() {
|
||||
new (&arena_) Arena();
|
||||
|
||||
SuperVersion* sv = cfd_->GetReferencedSuperVersion(db_impl_);
|
||||
SequenceNumber latest_seq = db_impl_->GetLatestSequenceNumber();
|
||||
assert(sv->version_number >= cur_sv_number);
|
||||
SequenceNumber read_seq = GetSeqNum(db_impl_, snapshot);
|
||||
if (read_callback_) {
|
||||
read_callback_->Refresh(latest_seq);
|
||||
read_callback_->Refresh(read_seq);
|
||||
}
|
||||
Init(env, read_options_, *(cfd_->ioptions()), sv->mutable_cf_options,
|
||||
sv->current, latest_seq,
|
||||
sv->current, read_seq,
|
||||
sv->mutable_cf_options.max_sequential_skip_in_iterations,
|
||||
cur_sv_number, read_callback_, db_impl_, cfd_, expose_blob_index_,
|
||||
sv->version_number, read_callback_, db_impl_, cfd_, expose_blob_index_,
|
||||
allow_refresh_);
|
||||
|
||||
InternalIterator* internal_iter = db_impl_->NewInternalIterator(
|
||||
read_options_, cfd_, sv, &arena_, latest_seq,
|
||||
read_options_, cfd_, sv, &arena_, read_seq,
|
||||
/* allow_unprepared_value */ true, /* db_iter */ this);
|
||||
SetIterUnderDBIter(internal_iter);
|
||||
};
|
||||
@@ -92,13 +107,13 @@ Status ArenaWrappedDBIter::Refresh() {
|
||||
reinit_internal_iter();
|
||||
break;
|
||||
} else {
|
||||
SequenceNumber latest_seq = db_impl_->GetLatestSequenceNumber();
|
||||
SequenceNumber read_seq = GetSeqNum(db_impl_, snapshot);
|
||||
// Refresh range-tombstones in MemTable
|
||||
if (!read_options_.ignore_range_deletions) {
|
||||
SuperVersion* sv = cfd_->GetThreadLocalSuperVersion(db_impl_);
|
||||
TEST_SYNC_POINT_CALLBACK("ArenaWrappedDBIter::Refresh:SV", nullptr);
|
||||
auto t = sv->mem->NewRangeTombstoneIterator(
|
||||
read_options_, latest_seq, false /* immutable_memtable */);
|
||||
read_options_, read_seq, false /* immutable_memtable */);
|
||||
if (!t || t->empty()) {
|
||||
// If memtable_range_tombstone_iter_ points to a non-empty tombstone
|
||||
// iterator, then it means sv->mem is not the memtable that
|
||||
@@ -128,9 +143,6 @@ Status ArenaWrappedDBIter::Refresh() {
|
||||
}
|
||||
db_impl_->ReturnAndCleanupSuperVersion(cfd_, sv);
|
||||
}
|
||||
// Refresh latest sequence number
|
||||
db_iter_->set_sequence(latest_seq);
|
||||
db_iter_->set_valid(false);
|
||||
// Check again if the latest super version number is changed
|
||||
uint64_t latest_sv_number = cfd_->GetSuperVersionNumber();
|
||||
if (latest_sv_number != cur_sv_number) {
|
||||
@@ -139,6 +151,8 @@ Status ArenaWrappedDBIter::Refresh() {
|
||||
cur_sv_number = latest_sv_number;
|
||||
continue;
|
||||
}
|
||||
db_iter_->set_sequence(read_seq);
|
||||
db_iter_->set_valid(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,6 +80,7 @@ class ArenaWrappedDBIter : public Iterator {
|
||||
Status GetProperty(std::string prop_name, std::string* prop) override;
|
||||
|
||||
Status Refresh() override;
|
||||
Status Refresh(const Snapshot*) override;
|
||||
|
||||
void Init(Env* env, const ReadOptions& read_options,
|
||||
const ImmutableOptions& ioptions,
|
||||
|
||||
@@ -46,7 +46,8 @@ class BlobContents {
|
||||
class BlobContentsCreator : public Cache::CreateContext {
|
||||
public:
|
||||
static void Create(std::unique_ptr<BlobContents>* out, size_t* out_charge,
|
||||
const Slice& contents, MemoryAllocator* alloc) {
|
||||
const Slice& contents, CompressionType /*type*/,
|
||||
MemoryAllocator* alloc) {
|
||||
auto raw = new BlobContents(AllocateAndCopyBlock(contents, alloc),
|
||||
contents.size());
|
||||
out->reset(raw);
|
||||
|
||||
@@ -585,7 +585,8 @@ Status BlobFileReader::UncompressBlobIfNeeded(
|
||||
assert(result);
|
||||
|
||||
if (compression_type == kNoCompression) {
|
||||
BlobContentsCreator::Create(result, nullptr, value_slice, allocator);
|
||||
BlobContentsCreator::Create(result, nullptr, value_slice, kNoCompression,
|
||||
allocator);
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
@@ -96,9 +96,13 @@ class DBBlobIndexTest : public DBTestBase {
|
||||
}
|
||||
|
||||
ArenaWrappedDBIter* GetBlobIterator() {
|
||||
return dbfull()->NewIteratorImpl(
|
||||
ReadOptions(), cfd(), dbfull()->GetLatestSequenceNumber(),
|
||||
nullptr /*read_callback*/, true /*expose_blob_index*/);
|
||||
ColumnFamilyData* column_family = cfd();
|
||||
DBImpl* db_impl = dbfull();
|
||||
return db_impl->NewIteratorImpl(
|
||||
ReadOptions(), column_family,
|
||||
column_family->GetReferencedSuperVersion(db_impl),
|
||||
db_impl->GetLatestSequenceNumber(), nullptr /*read_callback*/,
|
||||
true /*expose_blob_index*/);
|
||||
}
|
||||
|
||||
Options GetTestOptions() {
|
||||
|
||||
@@ -120,6 +120,7 @@ using ROCKSDB_NAMESPACE::TransactionDB;
|
||||
using ROCKSDB_NAMESPACE::TransactionDBOptions;
|
||||
using ROCKSDB_NAMESPACE::TransactionLogIterator;
|
||||
using ROCKSDB_NAMESPACE::TransactionOptions;
|
||||
using ROCKSDB_NAMESPACE::WaitForCompactOptions;
|
||||
using ROCKSDB_NAMESPACE::WALRecoveryMode;
|
||||
using ROCKSDB_NAMESPACE::WritableFile;
|
||||
using ROCKSDB_NAMESPACE::WriteBatch;
|
||||
@@ -275,6 +276,9 @@ struct rocksdb_optimistictransactiondb_t {
|
||||
struct rocksdb_optimistictransaction_options_t {
|
||||
OptimisticTransactionOptions rep;
|
||||
};
|
||||
struct rocksdb_wait_for_compact_options_t {
|
||||
WaitForCompactOptions rep;
|
||||
};
|
||||
|
||||
struct rocksdb_compactionfiltercontext_t {
|
||||
CompactionFilter::Context rep;
|
||||
@@ -4585,6 +4589,11 @@ void rocksdb_readoptions_set_iter_start_ts(rocksdb_readoptions_t* opt,
|
||||
}
|
||||
}
|
||||
|
||||
void rocksdb_readoptions_set_auto_readahead_size(rocksdb_readoptions_t* opt,
|
||||
unsigned char v) {
|
||||
opt->rep.auto_readahead_size = v;
|
||||
}
|
||||
|
||||
rocksdb_writeoptions_t* rocksdb_writeoptions_create() {
|
||||
return new rocksdb_writeoptions_t;
|
||||
}
|
||||
@@ -6719,4 +6728,59 @@ double rocksdb_statistics_histogram_data_get_min(
|
||||
return data->rep.min;
|
||||
}
|
||||
|
||||
void rocksdb_wait_for_compact(rocksdb_t* db,
|
||||
rocksdb_wait_for_compact_options_t* options,
|
||||
char** errptr) {
|
||||
SaveError(errptr, db->rep->WaitForCompact(options->rep));
|
||||
}
|
||||
|
||||
rocksdb_wait_for_compact_options_t* rocksdb_wait_for_compact_options_create() {
|
||||
return new rocksdb_wait_for_compact_options_t;
|
||||
}
|
||||
|
||||
void rocksdb_wait_for_compact_options_destroy(
|
||||
rocksdb_wait_for_compact_options_t* opt) {
|
||||
delete opt;
|
||||
}
|
||||
|
||||
void rocksdb_wait_for_compact_options_set_abort_on_pause(
|
||||
rocksdb_wait_for_compact_options_t* opt, unsigned char v) {
|
||||
opt->rep.abort_on_pause = v;
|
||||
}
|
||||
|
||||
unsigned char rocksdb_wait_for_compact_options_get_abort_on_pause(
|
||||
rocksdb_wait_for_compact_options_t* opt) {
|
||||
return opt->rep.abort_on_pause;
|
||||
}
|
||||
|
||||
void rocksdb_wait_for_compact_options_set_flush(
|
||||
rocksdb_wait_for_compact_options_t* opt, unsigned char v) {
|
||||
opt->rep.flush = v;
|
||||
}
|
||||
|
||||
unsigned char rocksdb_wait_for_compact_options_get_flush(
|
||||
rocksdb_wait_for_compact_options_t* opt) {
|
||||
return opt->rep.flush;
|
||||
}
|
||||
|
||||
void rocksdb_wait_for_compact_options_set_close_db(
|
||||
rocksdb_wait_for_compact_options_t* opt, unsigned char v) {
|
||||
opt->rep.close_db = v;
|
||||
}
|
||||
|
||||
unsigned char rocksdb_wait_for_compact_options_get_close_db(
|
||||
rocksdb_wait_for_compact_options_t* opt) {
|
||||
return opt->rep.close_db;
|
||||
}
|
||||
|
||||
void rocksdb_wait_for_compact_options_set_timeout(
|
||||
rocksdb_wait_for_compact_options_t* opt, uint64_t microseconds) {
|
||||
opt->rep.timeout = std::chrono::microseconds(microseconds);
|
||||
}
|
||||
|
||||
uint64_t rocksdb_wait_for_compact_options_get_timeout(
|
||||
rocksdb_wait_for_compact_options_t* opt) {
|
||||
return opt->rep.timeout.count();
|
||||
}
|
||||
|
||||
} // end extern "C"
|
||||
+36
@@ -375,6 +375,11 @@ static rocksdb_t* CheckCompaction(rocksdb_t* db, rocksdb_options_t* options,
|
||||
|
||||
// Force compaction
|
||||
rocksdb_compact_range(db, NULL, 0, NULL, 0);
|
||||
rocksdb_wait_for_compact_options_t* wco;
|
||||
wco = rocksdb_wait_for_compact_options_create();
|
||||
rocksdb_wait_for_compact(db, wco, &err);
|
||||
CheckNoError(err);
|
||||
rocksdb_wait_for_compact_options_destroy(wco);
|
||||
// should have filtered bar, but not foo
|
||||
CheckGet(db, roptions, "foo", "foovalue");
|
||||
CheckGet(db, roptions, "bar", NULL);
|
||||
@@ -3687,6 +3692,37 @@ int main(int argc, char** argv) {
|
||||
rocksdb_statistics_histogram_data_destroy(hist);
|
||||
}
|
||||
|
||||
StartPhase("wait_for_compact_options");
|
||||
{
|
||||
rocksdb_wait_for_compact_options_t* wco;
|
||||
wco = rocksdb_wait_for_compact_options_create();
|
||||
|
||||
rocksdb_wait_for_compact_options_set_abort_on_pause(wco, 1);
|
||||
CheckCondition(1 ==
|
||||
rocksdb_wait_for_compact_options_get_abort_on_pause(wco));
|
||||
|
||||
rocksdb_wait_for_compact_options_set_flush(wco, 1);
|
||||
CheckCondition(1 == rocksdb_wait_for_compact_options_get_flush(wco));
|
||||
|
||||
rocksdb_wait_for_compact_options_set_close_db(wco, 1);
|
||||
CheckCondition(1 == rocksdb_wait_for_compact_options_get_close_db(wco));
|
||||
|
||||
rocksdb_wait_for_compact_options_set_timeout(wco, 342);
|
||||
CheckCondition(342 == rocksdb_wait_for_compact_options_get_timeout(wco));
|
||||
|
||||
rocksdb_wait_for_compact_options_destroy(wco);
|
||||
}
|
||||
StartPhase("wait_for_compact");
|
||||
{
|
||||
rocksdb_wait_for_compact_options_t* wco;
|
||||
wco = rocksdb_wait_for_compact_options_create();
|
||||
rocksdb_wait_for_compact_options_set_flush(wco, 1);
|
||||
|
||||
rocksdb_wait_for_compact(db, wco, &err);
|
||||
CheckNoError(err);
|
||||
rocksdb_wait_for_compact_options_destroy(wco);
|
||||
}
|
||||
|
||||
StartPhase("cancel_all_background_work");
|
||||
rocksdb_cancel_all_background_work(db, 1);
|
||||
|
||||
|
||||
+7
-15
@@ -476,6 +476,7 @@ void SuperVersion::Init(ColumnFamilyData* new_cfd, MemTable* new_mem,
|
||||
mem = new_mem;
|
||||
imm = new_imm;
|
||||
current = new_current;
|
||||
full_history_ts_low = cfd->GetFullHistoryTsLow();
|
||||
cfd->Ref();
|
||||
mem->Ref();
|
||||
imm->Ref();
|
||||
@@ -1118,7 +1119,7 @@ Compaction* ColumnFamilyData::PickCompaction(
|
||||
GetName(), mutable_options, mutable_db_options, current_->storage_info(),
|
||||
log_buffer);
|
||||
if (result != nullptr) {
|
||||
result->SetInputVersion(current_);
|
||||
result->FinalizeInputInfo(current_);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -1202,7 +1203,7 @@ Compaction* ColumnFamilyData::CompactRange(
|
||||
compact_range_options, begin, end, compaction_end, conflict,
|
||||
max_file_num_to_ignore, trim_ts);
|
||||
if (result != nullptr) {
|
||||
result->SetInputVersion(current_);
|
||||
result->FinalizeInputInfo(current_);
|
||||
}
|
||||
TEST_SYNC_POINT("ColumnFamilyData::CompactRange:Return");
|
||||
return result;
|
||||
@@ -1283,8 +1284,6 @@ void ColumnFamilyData::InstallSuperVersion(
|
||||
new_superversion->Init(this, mem_, imm_.current(), current_);
|
||||
SuperVersion* old_superversion = super_version_;
|
||||
super_version_ = new_superversion;
|
||||
++super_version_number_;
|
||||
super_version_->version_number = super_version_number_;
|
||||
if (old_superversion == nullptr || old_superversion->current != current() ||
|
||||
old_superversion->mem != mem_ ||
|
||||
old_superversion->imm != imm_.current()) {
|
||||
@@ -1319,6 +1318,8 @@ void ColumnFamilyData::InstallSuperVersion(
|
||||
sv_context->superversions_to_free.push_back(old_superversion);
|
||||
}
|
||||
}
|
||||
++super_version_number_;
|
||||
super_version_->version_number = super_version_number_;
|
||||
}
|
||||
|
||||
void ColumnFamilyData::ResetThreadLocalSuperVersions() {
|
||||
@@ -1557,24 +1558,15 @@ bool ColumnFamilyData::ShouldPostponeFlushToRetainUDT(
|
||||
if (full_history_ts_low.empty()) {
|
||||
return false;
|
||||
}
|
||||
#ifndef NDEBUG
|
||||
Slice last_table_newest_udt;
|
||||
#endif /* !NDEBUG */
|
||||
for (const Slice& table_newest_udt :
|
||||
imm()->GetTablesNewestUDT(max_memtable_id)) {
|
||||
assert(table_newest_udt.size() == full_history_ts_low.size());
|
||||
assert(last_table_newest_udt.empty() ||
|
||||
ucmp->CompareTimestamp(table_newest_udt, last_table_newest_udt) >=
|
||||
0);
|
||||
// Checking the newest UDT contained in MemTable with ascending ID up to
|
||||
// `max_memtable_id`. MemTable with bigger ID will have newer UDT, return
|
||||
// immediately on finding the first MemTable that needs postponing.
|
||||
// `max_memtable_id`. Return immediately on finding the first MemTable that
|
||||
// needs postponing.
|
||||
if (ucmp->CompareTimestamp(table_newest_udt, full_history_ts_low) >= 0) {
|
||||
return true;
|
||||
}
|
||||
#ifndef NDEBUG
|
||||
last_table_newest_udt = table_newest_udt;
|
||||
#endif /* !NDEBUG */
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -211,6 +211,12 @@ struct SuperVersion {
|
||||
// Version number of the current SuperVersion
|
||||
uint64_t version_number;
|
||||
WriteStallCondition write_stall_condition;
|
||||
// Each time `full_history_ts_low` collapses history, a new SuperVersion is
|
||||
// installed. This field tracks the effective `full_history_ts_low` for that
|
||||
// SuperVersion, to be used by read APIs for sanity checks. This field is
|
||||
// immutable once SuperVersion is installed. For column family that doesn't
|
||||
// enable UDT feature, this is an empty string.
|
||||
std::string full_history_ts_low;
|
||||
|
||||
// should be called outside the mutex
|
||||
SuperVersion() = default;
|
||||
|
||||
+36
-23
@@ -204,32 +204,36 @@ bool Compaction::IsFullCompaction(
|
||||
return num_files_in_compaction == total_num_files;
|
||||
}
|
||||
|
||||
const TablePropertiesCollection& Compaction::GetTableProperties() {
|
||||
if (!input_table_properties_initialized_) {
|
||||
const ReadOptions read_options(Env::IOActivity::kCompaction);
|
||||
for (size_t i = 0; i < num_input_levels(); ++i) {
|
||||
for (const FileMetaData* fmd : *(this->inputs(i))) {
|
||||
std::shared_ptr<const TableProperties> tp;
|
||||
std::string file_name =
|
||||
TableFileName(immutable_options_.cf_paths, fmd->fd.GetNumber(),
|
||||
fmd->fd.GetPathId());
|
||||
Status s = input_version_->GetTableProperties(read_options, &tp, fmd,
|
||||
&file_name);
|
||||
if (s.ok()) {
|
||||
table_properties_[file_name] = tp;
|
||||
} else {
|
||||
ROCKS_LOG_ERROR(immutable_options_.info_log,
|
||||
"Unable to load table properties for file %" PRIu64
|
||||
" --- %s\n",
|
||||
fmd->fd.GetNumber(), s.ToString().c_str());
|
||||
}
|
||||
Status Compaction::InitInputTableProperties() {
|
||||
if (!input_table_properties_.empty()) {
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status s;
|
||||
const ReadOptions read_options(Env::IOActivity::kCompaction);
|
||||
assert(input_version_);
|
||||
for (size_t i = 0; i < num_input_levels(); ++i) {
|
||||
for (const FileMetaData* fmd : *(this->inputs(i))) {
|
||||
std::shared_ptr<const TableProperties> tp;
|
||||
std::string file_name =
|
||||
TableFileName(immutable_options_.cf_paths, fmd->fd.GetNumber(),
|
||||
fmd->fd.GetPathId());
|
||||
s = input_version_->GetTableProperties(read_options, &tp, fmd,
|
||||
&file_name);
|
||||
if (s.ok()) {
|
||||
input_table_properties_[file_name] = tp;
|
||||
} else {
|
||||
ROCKS_LOG_ERROR(immutable_options_.info_log,
|
||||
"Unable to load table properties for file %" PRIu64
|
||||
" --- %s\n",
|
||||
fmd->fd.GetNumber(), s.ToString().c_str());
|
||||
input_table_properties_.clear();
|
||||
return s;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
input_table_properties_initialized_ = true;
|
||||
};
|
||||
|
||||
return table_properties_;
|
||||
return s;
|
||||
}
|
||||
|
||||
Compaction::Compaction(
|
||||
@@ -774,8 +778,17 @@ std::unique_ptr<CompactionFilter> Compaction::CreateCompactionFilter() const {
|
||||
CompactionFilter::Context context;
|
||||
context.is_full_compaction = is_full_compaction_;
|
||||
context.is_manual_compaction = is_manual_compaction_;
|
||||
context.input_start_level = start_level_;
|
||||
context.column_family_id = cfd_->GetID();
|
||||
context.reason = TableFileCreationReason::kCompaction;
|
||||
context.input_table_properties = GetInputTableProperties();
|
||||
if (context.input_table_properties.empty()) {
|
||||
ROCKS_LOG_WARN(
|
||||
immutable_options_.info_log,
|
||||
"Unable to set `input_table_properties` of `CompactionFilter::Context` "
|
||||
"for compaction.");
|
||||
}
|
||||
|
||||
return cfd_->ioptions()->compaction_filter_factory->CreateCompactionFilter(
|
||||
context);
|
||||
}
|
||||
|
||||
+24
-10
@@ -289,7 +289,14 @@ class Compaction {
|
||||
// is the sum of all input file sizes.
|
||||
uint64_t OutputFilePreallocationSize() const;
|
||||
|
||||
void SetInputVersion(Version* input_version);
|
||||
// TODO(hx235): eventually we should consider `InitInputTableProperties()`'s
|
||||
// status and fail the compaction if needed
|
||||
// TODO(hx235): consider making this function part of the construction so we
|
||||
// don't forget to call it
|
||||
void FinalizeInputInfo(Version* input_version) {
|
||||
SetInputVersion(input_version);
|
||||
InitInputTableProperties().PermitUncheckedError();
|
||||
}
|
||||
|
||||
struct InputLevelSummaryBuffer {
|
||||
char buffer[128];
|
||||
@@ -326,16 +333,20 @@ class Compaction {
|
||||
int output_level, VersionStorageInfo* vstorage,
|
||||
const std::vector<CompactionInputFiles>& inputs);
|
||||
|
||||
// If called before a compaction finishes, will return
|
||||
// table properties of all compaction input files.
|
||||
// If called after a compaction finished, will return
|
||||
// table properties of all compaction input and output files.
|
||||
const TablePropertiesCollection& GetTableProperties();
|
||||
const TablePropertiesCollection& GetInputTableProperties() const {
|
||||
return input_table_properties_;
|
||||
}
|
||||
|
||||
// TODO(hx235): consider making this function symmetric to
|
||||
// InitInputTableProperties()
|
||||
void SetOutputTableProperties(
|
||||
const std::string& file_name,
|
||||
const std::shared_ptr<const TableProperties>& tp) {
|
||||
table_properties_[file_name] = tp;
|
||||
output_table_properties_[file_name] = tp;
|
||||
}
|
||||
|
||||
const TablePropertiesCollection& GetOutputTableProperties() const {
|
||||
return output_table_properties_;
|
||||
}
|
||||
|
||||
Slice GetSmallestUserKey() const { return smallest_user_key_; }
|
||||
@@ -432,6 +443,10 @@ class Compaction {
|
||||
const int output_level);
|
||||
|
||||
private:
|
||||
void SetInputVersion(Version* input_version);
|
||||
|
||||
Status InitInputTableProperties();
|
||||
|
||||
// mark (or clear) all files that are being compacted
|
||||
void MarkFilesBeingCompacted(bool mark_as_compacted);
|
||||
|
||||
@@ -522,9 +537,8 @@ class Compaction {
|
||||
// Does input compression match the output compression?
|
||||
bool InputCompressionMatchesOutput() const;
|
||||
|
||||
bool input_table_properties_initialized_ = false;
|
||||
// table properties of output files
|
||||
TablePropertiesCollection table_properties_;
|
||||
TablePropertiesCollection input_table_properties_;
|
||||
TablePropertiesCollection output_table_properties_;
|
||||
|
||||
// smallest user keys in compaction
|
||||
// includes timestamp if user-defined timestamp is enabled.
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
#include "db/blob/prefetch_buffer_collection.h"
|
||||
#include "db/snapshot_checker.h"
|
||||
#include "db/wide/wide_column_serialization.h"
|
||||
#include "db/wide/wide_columns_helper.h"
|
||||
#include "logging/logging.h"
|
||||
#include "port/likely.h"
|
||||
#include "rocksdb/listener.h"
|
||||
@@ -423,16 +424,13 @@ bool CompactionIterator::InvokeFilterIfNeeded(bool* need_skip,
|
||||
return false;
|
||||
} else if (decision == CompactionFilter::Decision::kChangeWideColumnEntity) {
|
||||
WideColumns sorted_columns;
|
||||
|
||||
sorted_columns.reserve(new_columns.size());
|
||||
|
||||
for (const auto& column : new_columns) {
|
||||
sorted_columns.emplace_back(column.first, column.second);
|
||||
}
|
||||
|
||||
std::sort(sorted_columns.begin(), sorted_columns.end(),
|
||||
[](const WideColumn& lhs, const WideColumn& rhs) {
|
||||
return lhs.name().compare(rhs.name()) < 0;
|
||||
});
|
||||
WideColumnsHelper::SortColumns(sorted_columns);
|
||||
|
||||
{
|
||||
const Status s = WideColumnSerialization::Serialize(
|
||||
|
||||
@@ -844,7 +844,8 @@ Status CompactionJob::Run() {
|
||||
return status;
|
||||
}
|
||||
|
||||
Status CompactionJob::Install(const MutableCFOptions& mutable_cf_options) {
|
||||
Status CompactionJob::Install(const MutableCFOptions& mutable_cf_options,
|
||||
bool* compaction_released) {
|
||||
assert(compact_);
|
||||
|
||||
AutoThreadOperationStageUpdater stage_updater(
|
||||
@@ -860,7 +861,7 @@ Status CompactionJob::Install(const MutableCFOptions& mutable_cf_options) {
|
||||
compaction_stats_);
|
||||
|
||||
if (status.ok()) {
|
||||
status = InstallCompactionResults(mutable_cf_options);
|
||||
status = InstallCompactionResults(mutable_cf_options, compaction_released);
|
||||
}
|
||||
if (!versions_->io_status().ok()) {
|
||||
io_status_ = versions_->io_status();
|
||||
@@ -1318,6 +1319,7 @@ void CompactionJob::ProcessKeyValueCompaction(SubcompactionState* sub_compact) {
|
||||
"CompactionJob::ProcessKeyValueCompaction()::Processing",
|
||||
reinterpret_cast<void*>(
|
||||
const_cast<Compaction*>(sub_compact->compaction)));
|
||||
uint64_t last_cpu_micros = prev_cpu_micros;
|
||||
while (status.ok() && !cfd->IsDropped() && c_iter->Valid()) {
|
||||
// Invariant: c_iter.status() is guaranteed to be OK if c_iter->Valid()
|
||||
// returns true.
|
||||
@@ -1329,6 +1331,12 @@ void CompactionJob::ProcessKeyValueCompaction(SubcompactionState* sub_compact) {
|
||||
RecordDroppedKeys(c_iter_stats, &sub_compact->compaction_job_stats);
|
||||
c_iter->ResetRecordCounts();
|
||||
RecordCompactionIOStats();
|
||||
|
||||
uint64_t cur_cpu_micros = db_options_.clock->CPUMicros();
|
||||
assert(cur_cpu_micros >= last_cpu_micros);
|
||||
RecordTick(stats_, COMPACTION_CPU_TOTAL_TIME,
|
||||
cur_cpu_micros - last_cpu_micros);
|
||||
last_cpu_micros = cur_cpu_micros;
|
||||
}
|
||||
|
||||
// Add current compaction_iterator key to target compaction output, if the
|
||||
@@ -1436,8 +1444,11 @@ void CompactionJob::ProcessKeyValueCompaction(SubcompactionState* sub_compact) {
|
||||
sub_compact->Current().UpdateBlobStats();
|
||||
}
|
||||
|
||||
uint64_t cur_cpu_micros = db_options_.clock->CPUMicros();
|
||||
sub_compact->compaction_job_stats.cpu_micros =
|
||||
db_options_.clock->CPUMicros() - prev_cpu_micros;
|
||||
cur_cpu_micros - prev_cpu_micros;
|
||||
RecordTick(stats_, COMPACTION_CPU_TOTAL_TIME,
|
||||
cur_cpu_micros - last_cpu_micros);
|
||||
|
||||
if (measure_io_stats_) {
|
||||
sub_compact->compaction_job_stats.file_write_nanos +=
|
||||
@@ -1687,7 +1698,7 @@ Status CompactionJob::FinishCompactionOutputFile(
|
||||
}
|
||||
|
||||
Status CompactionJob::InstallCompactionResults(
|
||||
const MutableCFOptions& mutable_cf_options) {
|
||||
const MutableCFOptions& mutable_cf_options, bool* compaction_released) {
|
||||
assert(compact_);
|
||||
|
||||
db_mutex_->AssertHeld();
|
||||
@@ -1769,9 +1780,15 @@ Status CompactionJob::InstallCompactionResults(
|
||||
}
|
||||
}
|
||||
|
||||
return versions_->LogAndApply(compaction->column_family_data(),
|
||||
mutable_cf_options, read_options, edit,
|
||||
db_mutex_, db_directory_);
|
||||
auto manifest_wcb = [&compaction, &compaction_released](const Status& s) {
|
||||
compaction->ReleaseCompactionFiles(s);
|
||||
*compaction_released = true;
|
||||
};
|
||||
|
||||
return versions_->LogAndApply(
|
||||
compaction->column_family_data(), mutable_cf_options, read_options, edit,
|
||||
db_mutex_, db_directory_, /*new_descriptor_log=*/false,
|
||||
/*column_family_options=*/nullptr, manifest_wcb);
|
||||
}
|
||||
|
||||
void CompactionJob::RecordCompactionIOStats() {
|
||||
@@ -1921,6 +1938,7 @@ Status CompactionJob::OpenCompactionOutputFile(SubcompactionState* sub_compact,
|
||||
db_options_.stats, listeners, db_options_.file_checksum_gen_factory.get(),
|
||||
tmp_set.Contains(FileType::kTableFile), false));
|
||||
|
||||
// TODO(hx235): pass in the correct `oldest_key_time` instead of `0`
|
||||
TableBuilderOptions tboptions(
|
||||
*cfd->ioptions(), *(sub_compact->compaction->mutable_cf_options()),
|
||||
cfd->internal_comparator(), cfd->int_tbl_prop_collector_factories(),
|
||||
@@ -1962,7 +1980,7 @@ bool CompactionJob::UpdateCompactionStats(uint64_t* num_input_range_del) {
|
||||
|
||||
bool has_error = false;
|
||||
const ReadOptions read_options(Env::IOActivity::kCompaction);
|
||||
const auto& input_table_properties = compaction->GetTableProperties();
|
||||
const auto& input_table_properties = compaction->GetInputTableProperties();
|
||||
for (int input_level = 0;
|
||||
input_level < static_cast<int>(compaction->num_input_levels());
|
||||
++input_level) {
|
||||
|
||||
@@ -186,7 +186,10 @@ class CompactionJob {
|
||||
|
||||
// REQUIRED: mutex held
|
||||
// Add compaction input/output to the current version
|
||||
Status Install(const MutableCFOptions& mutable_cf_options);
|
||||
// Releases compaction file through Compaction::ReleaseCompactionFiles().
|
||||
// Sets *compaction_released to true if compaction is released.
|
||||
Status Install(const MutableCFOptions& mutable_cf_options,
|
||||
bool* compaction_released);
|
||||
|
||||
// Return the IO status
|
||||
IOStatus io_status() const { return io_status_; }
|
||||
@@ -273,7 +276,8 @@ class CompactionJob {
|
||||
const Slice& next_table_min_key,
|
||||
const Slice* comp_start_user_key,
|
||||
const Slice* comp_end_user_key);
|
||||
Status InstallCompactionResults(const MutableCFOptions& mutable_cf_options);
|
||||
Status InstallCompactionResults(const MutableCFOptions& mutable_cf_options,
|
||||
bool* compaction_released);
|
||||
Status OpenCompactionOutputFile(SubcompactionState* sub_compact,
|
||||
CompactionOutputs& outputs);
|
||||
void UpdateCompactionJobStats(
|
||||
|
||||
@@ -644,7 +644,7 @@ class CompactionJobTestBase : public testing::Test {
|
||||
mutable_cf_options_.max_compaction_bytes, 0, kNoCompression,
|
||||
cfd->GetLatestMutableCFOptions()->compression_opts,
|
||||
Temperature::kUnknown, max_subcompactions, grandparents, true);
|
||||
compaction.SetInputVersion(cfd->current());
|
||||
compaction.FinalizeInputInfo(cfd->current());
|
||||
|
||||
assert(db_options_.info_log);
|
||||
LogBuffer log_buffer(InfoLogLevel::INFO_LEVEL, db_options_.info_log.get());
|
||||
@@ -674,7 +674,9 @@ class CompactionJobTestBase : public testing::Test {
|
||||
ASSERT_OK(s);
|
||||
ASSERT_OK(compaction_job.io_status());
|
||||
mutex_.Lock();
|
||||
ASSERT_OK(compaction_job.Install(*cfd->GetLatestMutableCFOptions()));
|
||||
bool compaction_released = false;
|
||||
ASSERT_OK(compaction_job.Install(*cfd->GetLatestMutableCFOptions(),
|
||||
&compaction_released));
|
||||
ASSERT_OK(compaction_job.io_status());
|
||||
mutex_.Unlock();
|
||||
log_buffer.FlushBufferToLog();
|
||||
|
||||
@@ -994,6 +994,61 @@ TEST_F(CompactionPickerTest, UniversalIncrementalSpace5) {
|
||||
ASSERT_EQ(13, compaction->num_input_files(1));
|
||||
}
|
||||
|
||||
TEST_F(CompactionPickerTest,
|
||||
PartiallyExcludeL0ToReduceWriteStopForSizeAmpCompaction) {
|
||||
const uint64_t kFileSize = 100000;
|
||||
const uint64_t kL0FileCount = 30;
|
||||
const uint64_t kLastLevelFileCount = 1;
|
||||
const uint64_t kNumLevels = 5;
|
||||
|
||||
for (const uint64_t test_no_exclusion : {false, true}) {
|
||||
const uint64_t kExpectedNumExcludedL0 =
|
||||
test_no_exclusion ? 0 : kL0FileCount * 1 / 10;
|
||||
|
||||
mutable_cf_options_.level0_stop_writes_trigger = 36;
|
||||
mutable_cf_options_.compaction_options_universal
|
||||
.max_size_amplification_percent = 1;
|
||||
mutable_cf_options_.compaction_options_universal.max_merge_width =
|
||||
test_no_exclusion
|
||||
// In universal compaction, sorted runs from non L0 levels are
|
||||
// counted toward `level0_stop_writes_trigger`. Therefore we need to
|
||||
// subtract the total number of sorted runs picked originally for
|
||||
// this compaction (i.e, kL0FileCount + kLastLevelFileCount) from
|
||||
// `level0_stop_writes_trigger` to calculate `max_merge_width` that
|
||||
// results in no L0 exclusion for testing purpose.
|
||||
? mutable_cf_options_.level0_stop_writes_trigger -
|
||||
(kL0FileCount + kLastLevelFileCount)
|
||||
: UINT_MAX;
|
||||
|
||||
UniversalCompactionPicker universal_compaction_picker(ioptions_, &icmp_);
|
||||
NewVersionStorage(kNumLevels, kCompactionStyleUniversal);
|
||||
|
||||
for (uint64_t i = 1; i <= kL0FileCount + kLastLevelFileCount; ++i) {
|
||||
Add(i <= kL0FileCount ? 0 : kNumLevels - 1, static_cast<uint32_t>(i),
|
||||
std::to_string((i + 100) * 1000).c_str(),
|
||||
std::to_string((i + 100) * 1000 + 999).c_str(), kFileSize, 0, i * 100,
|
||||
i * 100 + 99);
|
||||
}
|
||||
|
||||
UpdateVersionStorageInfo();
|
||||
|
||||
ASSERT_TRUE(universal_compaction_picker.NeedsCompaction(vstorage_.get()));
|
||||
std::unique_ptr<Compaction> compaction(
|
||||
universal_compaction_picker.PickCompaction(
|
||||
cf_name_, mutable_cf_options_, mutable_db_options_, vstorage_.get(),
|
||||
&log_buffer_));
|
||||
ASSERT_TRUE(compaction.get() != nullptr);
|
||||
ASSERT_EQ(compaction->compaction_reason(),
|
||||
CompactionReason::kUniversalSizeAmplification);
|
||||
ASSERT_EQ(compaction->num_input_files(0),
|
||||
kL0FileCount - kExpectedNumExcludedL0);
|
||||
ASSERT_EQ(compaction->num_input_files(kNumLevels - 1), kLastLevelFileCount);
|
||||
for (uint64_t level = 1; level <= kNumLevels - 2; level++) {
|
||||
ASSERT_EQ(compaction->num_input_files(level), 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(CompactionPickerTest, NeedsCompactionFIFO) {
|
||||
NewVersionStorage(1, kCompactionStyleFIFO);
|
||||
const int kFileCount =
|
||||
@@ -3380,6 +3435,9 @@ TEST_F(CompactionPickerTest, UniversalSizeAmpTierCompactionNonLastLevel) {
|
||||
ioptions_.preclude_last_level_data_seconds = 1000;
|
||||
mutable_cf_options_.compaction_options_universal
|
||||
.max_size_amplification_percent = 200;
|
||||
// To avoid any L0 file exclusion in size amp compaction intended for reducing
|
||||
// write stop
|
||||
mutable_cf_options_.compaction_options_universal.max_merge_width = 2;
|
||||
UniversalCompactionPicker universal_compaction_picker(ioptions_, &icmp_);
|
||||
|
||||
NewVersionStorage(kNumLevels, kCompactionStyleUniversal);
|
||||
@@ -3453,6 +3511,9 @@ TEST_F(CompactionPickerTest, UniversalSizeAmpTierCompactionNotSuport) {
|
||||
ioptions_.preclude_last_level_data_seconds = 1000;
|
||||
mutable_cf_options_.compaction_options_universal
|
||||
.max_size_amplification_percent = 200;
|
||||
// To avoid any L0 file exclusion in size amp compaction intended for reducing
|
||||
// write stop
|
||||
mutable_cf_options_.compaction_options_universal.max_merge_width = 2;
|
||||
UniversalCompactionPicker universal_compaction_picker(ioptions_, &icmp_);
|
||||
|
||||
NewVersionStorage(kNumLevels, kCompactionStyleUniversal);
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
#include "db/compaction/compaction_picker_universal.h"
|
||||
|
||||
#include <cinttypes>
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <queue>
|
||||
#include <string>
|
||||
@@ -114,6 +114,13 @@ class UniversalCompactionBuilder {
|
||||
// because some files are being compacted.
|
||||
Compaction* PickPeriodicCompaction();
|
||||
|
||||
bool ShouldSkipLastSortedRunForSizeAmpCompaction() const {
|
||||
assert(!sorted_runs_.empty());
|
||||
return ioptions_.preclude_last_level_data_seconds > 0 &&
|
||||
ioptions_.num_levels > 2 &&
|
||||
sorted_runs_.back().level == ioptions_.num_levels - 1 &&
|
||||
sorted_runs_.size() > 1;
|
||||
}
|
||||
// Used in universal compaction when the allow_trivial_move
|
||||
// option is set. Checks whether there are any overlapping files
|
||||
// in the input. Returns true if the input files are non
|
||||
@@ -122,6 +129,100 @@ class UniversalCompactionBuilder {
|
||||
|
||||
uint64_t GetMaxOverlappingBytes() const;
|
||||
|
||||
// To conditionally exclude some of the newest L0 files
|
||||
// from a size amp compaction. This is to prevent a large number of L0
|
||||
// files from being locked by a size amp compaction, potentially leading to
|
||||
// write stop with a few more flushes.
|
||||
//
|
||||
// Such exclusion is based on `num_l0_input_pre_exclusion`,
|
||||
// `level0_stop_writes_trigger`, `max/min_merge_width` and the pre-exclusion
|
||||
// compaction score. Noted that it will not make the size amp compaction of
|
||||
// interest invalid from running as a size amp compaction as long as its
|
||||
// pre-exclusion compaction score satisfies the condition to run.
|
||||
//
|
||||
// @param `num_l0_input_pre_exclusion` Number of L0 input files prior to
|
||||
// exclusion
|
||||
// @param `end_index` Index of the last sorted run selected as compaction
|
||||
// input. Will not be affected by this exclusion.
|
||||
// @param `start_index` Index of the first input sorted run prior to
|
||||
// exclusion. Will be modified as output based on the exclusion.
|
||||
// @param `candidate_size` Total size of all except for the last input sorted
|
||||
// runs prior to exclusion. Will be modified as output based on the exclusion.
|
||||
//
|
||||
// @return Number of L0 files to exclude. `start_index` and
|
||||
// `candidate_size` will be modified accordingly
|
||||
std::size_t MightExcludeNewL0sToReduceWriteStop(
|
||||
std::size_t num_l0_input_pre_exclusion, std::size_t end_index,
|
||||
std::size_t& start_index, uint64_t& candidate_size) const {
|
||||
if (num_l0_input_pre_exclusion == 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
assert(start_index <= end_index && sorted_runs_.size() > end_index);
|
||||
assert(mutable_cf_options_.level0_stop_writes_trigger > 0);
|
||||
const std::size_t level0_stop_writes_trigger = static_cast<std::size_t>(
|
||||
mutable_cf_options_.level0_stop_writes_trigger);
|
||||
const std::size_t max_merge_width = static_cast<std::size_t>(
|
||||
mutable_cf_options_.compaction_options_universal.max_merge_width);
|
||||
const std::size_t min_merge_width = static_cast<std::size_t>(
|
||||
mutable_cf_options_.compaction_options_universal.min_merge_width);
|
||||
const uint64_t max_size_amplification_percent =
|
||||
mutable_cf_options_.compaction_options_universal
|
||||
.max_size_amplification_percent;
|
||||
const uint64_t base_sr_size = sorted_runs_[end_index].size;
|
||||
|
||||
// Leave at least 1 L0 file and 2 input sorted runs after exclusion
|
||||
const std::size_t max_num_l0_to_exclude =
|
||||
std::min(num_l0_input_pre_exclusion - 1, end_index - start_index - 1);
|
||||
// In universal compaction, sorted runs from non L0 levels are counted
|
||||
// toward `level0_stop_writes_trigger`. Therefore we need to subtract the
|
||||
// total number of sorted runs picked originally for this compaction from
|
||||
// `level0_stop_writes_trigger` to calculate
|
||||
// `num_extra_l0_before_write_stop`
|
||||
const std::size_t num_extra_l0_before_write_stop =
|
||||
level0_stop_writes_trigger -
|
||||
std::min(level0_stop_writes_trigger, end_index - start_index + 1);
|
||||
const std::size_t num_l0_to_exclude_for_max_merge_width =
|
||||
std::min(max_merge_width -
|
||||
std::min(max_merge_width, num_extra_l0_before_write_stop),
|
||||
max_num_l0_to_exclude);
|
||||
const std::size_t num_l0_to_exclude_for_min_merge_width =
|
||||
std::min(min_merge_width -
|
||||
std::min(min_merge_width, num_extra_l0_before_write_stop),
|
||||
max_num_l0_to_exclude);
|
||||
|
||||
std::size_t num_l0_to_exclude = 0;
|
||||
uint64_t candidate_size_post_exclusion = candidate_size;
|
||||
|
||||
for (std::size_t possible_num_l0_to_exclude =
|
||||
num_l0_to_exclude_for_min_merge_width;
|
||||
possible_num_l0_to_exclude <= num_l0_to_exclude_for_max_merge_width;
|
||||
++possible_num_l0_to_exclude) {
|
||||
uint64_t current_candidate_size = candidate_size_post_exclusion;
|
||||
for (std::size_t j = num_l0_to_exclude; j < possible_num_l0_to_exclude;
|
||||
++j) {
|
||||
current_candidate_size -=
|
||||
sorted_runs_.at(start_index + j).compensated_file_size;
|
||||
}
|
||||
|
||||
// To ensure the compaction score before and after exclusion is similar
|
||||
// so this exclusion will not make the size amp compaction of
|
||||
// interest invalid from running as a size amp compaction as long as its
|
||||
// pre-exclusion compaction score satisfies the condition to run.
|
||||
if (current_candidate_size * 100 <
|
||||
max_size_amplification_percent * base_sr_size ||
|
||||
current_candidate_size < candidate_size * 9 / 10) {
|
||||
break;
|
||||
}
|
||||
num_l0_to_exclude = possible_num_l0_to_exclude;
|
||||
candidate_size_post_exclusion = current_candidate_size;
|
||||
}
|
||||
|
||||
start_index += num_l0_to_exclude;
|
||||
candidate_size = candidate_size_post_exclusion;
|
||||
return num_l0_to_exclude;
|
||||
}
|
||||
|
||||
const ImmutableOptions& ioptions_;
|
||||
const InternalKeyComparator* icmp_;
|
||||
double score_;
|
||||
@@ -778,85 +879,67 @@ Compaction* UniversalCompactionBuilder::PickCompactionToReduceSortedRuns(
|
||||
|
||||
// Look at overall size amplification. If size amplification
|
||||
// exceeds the configured value, then do a compaction
|
||||
// of the candidate files all the way upto the earliest
|
||||
// base file (overrides configured values of file-size ratios,
|
||||
// min_merge_width and max_merge_width).
|
||||
//
|
||||
// on longest span of candidate files without conflict with other compactions
|
||||
// ending at the earliest base file (overriding configured values of file-size
|
||||
// ratios, min_merge_width and max_merge_width).
|
||||
Compaction* UniversalCompactionBuilder::PickCompactionToReduceSizeAmp() {
|
||||
// percentage flexibility while reducing size amplification
|
||||
uint64_t ratio = mutable_cf_options_.compaction_options_universal
|
||||
.max_size_amplification_percent;
|
||||
|
||||
unsigned int candidate_count = 0;
|
||||
uint64_t candidate_size = 0;
|
||||
size_t start_index = 0;
|
||||
const SortedRun* sr = nullptr;
|
||||
|
||||
assert(!sorted_runs_.empty());
|
||||
if (sorted_runs_.back().being_compacted) {
|
||||
|
||||
const size_t end_index = ShouldSkipLastSortedRunForSizeAmpCompaction()
|
||||
? sorted_runs_.size() - 2
|
||||
: sorted_runs_.size() - 1;
|
||||
if (sorted_runs_[end_index].being_compacted) {
|
||||
return nullptr;
|
||||
}
|
||||
const uint64_t base_sr_size = sorted_runs_[end_index].size;
|
||||
size_t start_index = end_index;
|
||||
uint64_t candidate_size = 0;
|
||||
size_t num_l0_files = 0;
|
||||
|
||||
// Get longest span (i.e, [start_index, end_index]) of available sorted runs
|
||||
while (start_index > 0) {
|
||||
const SortedRun* sr = &sorted_runs_[start_index - 1];
|
||||
if (sr->being_compacted) {
|
||||
char file_num_buf[kFormatFileNumberBufSize];
|
||||
sr->Dump(file_num_buf, sizeof(file_num_buf), true);
|
||||
ROCKS_LOG_BUFFER(
|
||||
log_buffer_,
|
||||
"[%s] Universal: stopping at sorted run undergoing compaction: "
|
||||
"%s[%" ROCKSDB_PRIszt "]",
|
||||
cf_name_.c_str(), file_num_buf, start_index - 1);
|
||||
break;
|
||||
}
|
||||
candidate_size += sr->compensated_file_size;
|
||||
num_l0_files += sr->level == 0 ? 1 : 0;
|
||||
--start_index;
|
||||
}
|
||||
|
||||
if (start_index == end_index) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Skip files that are already being compacted
|
||||
for (size_t loop = 0; loop + 1 < sorted_runs_.size(); loop++) {
|
||||
sr = &sorted_runs_[loop];
|
||||
if (!sr->being_compacted) {
|
||||
start_index = loop; // Consider this as the first candidate.
|
||||
break;
|
||||
}
|
||||
char file_num_buf[kFormatFileNumberBufSize];
|
||||
sr->Dump(file_num_buf, sizeof(file_num_buf), true);
|
||||
{
|
||||
const size_t num_l0_to_exclude = MightExcludeNewL0sToReduceWriteStop(
|
||||
num_l0_files, end_index, start_index, candidate_size);
|
||||
ROCKS_LOG_BUFFER(log_buffer_,
|
||||
"[%s] Universal: skipping %s[%d] compacted %s",
|
||||
cf_name_.c_str(), file_num_buf, loop,
|
||||
" cannot be a candidate to reduce size amp.\n");
|
||||
sr = nullptr;
|
||||
"[%s] Universal: Excluding %" ROCKSDB_PRIszt
|
||||
" latest L0 files to reduce potential write stop "
|
||||
"triggered by `level0_stop_writes_trigger`",
|
||||
cf_name_.c_str(), num_l0_to_exclude);
|
||||
}
|
||||
|
||||
if (sr == nullptr) {
|
||||
return nullptr; // no candidate files
|
||||
}
|
||||
{
|
||||
char file_num_buf[kFormatFileNumberBufSize];
|
||||
sr->Dump(file_num_buf, sizeof(file_num_buf), true);
|
||||
sorted_runs_[start_index].Dump(file_num_buf, sizeof(file_num_buf), true);
|
||||
ROCKS_LOG_BUFFER(
|
||||
log_buffer_,
|
||||
"[%s] Universal: First candidate %s[%" ROCKSDB_PRIszt "] %s",
|
||||
cf_name_.c_str(), file_num_buf, start_index, " to reduce size amp.\n");
|
||||
}
|
||||
|
||||
// size of the base sorted run for size amp calculation
|
||||
uint64_t base_sr_size = sorted_runs_.back().size;
|
||||
size_t sr_end_idx = sorted_runs_.size() - 1;
|
||||
// If tiered compaction is enabled and the last sorted run is the last level
|
||||
if (ioptions_.preclude_last_level_data_seconds > 0 &&
|
||||
ioptions_.num_levels > 2 &&
|
||||
sorted_runs_.back().level == ioptions_.num_levels - 1 &&
|
||||
sorted_runs_.size() > 1) {
|
||||
sr_end_idx = sorted_runs_.size() - 2;
|
||||
base_sr_size = sorted_runs_[sr_end_idx].size;
|
||||
}
|
||||
|
||||
// keep adding up all the remaining files
|
||||
for (size_t loop = start_index; loop < sr_end_idx; loop++) {
|
||||
sr = &sorted_runs_[loop];
|
||||
if (sr->being_compacted) {
|
||||
// TODO with incremental compaction is supported, we might want to
|
||||
// schedule some incremental compactions in parallel if needed.
|
||||
char file_num_buf[kFormatFileNumberBufSize];
|
||||
sr->Dump(file_num_buf, sizeof(file_num_buf), true);
|
||||
ROCKS_LOG_BUFFER(
|
||||
log_buffer_, "[%s] Universal: Possible candidate %s[%d] %s",
|
||||
cf_name_.c_str(), file_num_buf, start_index,
|
||||
" is already being compacted. No size amp reduction possible.\n");
|
||||
return nullptr;
|
||||
}
|
||||
candidate_size += sr->compensated_file_size;
|
||||
candidate_count++;
|
||||
}
|
||||
if (candidate_count == 0) {
|
||||
return nullptr;
|
||||
}
|
||||
// percentage flexibility while reducing size amplification
|
||||
const uint64_t ratio = mutable_cf_options_.compaction_options_universal
|
||||
.max_size_amplification_percent;
|
||||
|
||||
// size amplification = percentage of additional size
|
||||
if (candidate_size * 100 < ratio * base_sr_size) {
|
||||
@@ -893,7 +976,7 @@ Compaction* UniversalCompactionBuilder::PickCompactionToReduceSizeAmp() {
|
||||
}
|
||||
}
|
||||
return PickCompactionWithSortedRunRange(
|
||||
start_index, sr_end_idx, CompactionReason::kUniversalSizeAmplification);
|
||||
start_index, end_index, CompactionReason::kUniversalSizeAmplification);
|
||||
}
|
||||
|
||||
Compaction* UniversalCompactionBuilder::PickIncrementalForReduceSizeAmp(
|
||||
@@ -1442,4 +1525,3 @@ uint64_t UniversalCompactionBuilder::GetMaxOverlappingBytes() const {
|
||||
}
|
||||
}
|
||||
} // namespace ROCKSDB_NAMESPACE
|
||||
|
||||
+28
-7
@@ -1427,10 +1427,7 @@ TEST_P(DBMultiGetTestWithParam, MultiGetMultiCFMutex) {
|
||||
int retries = 0;
|
||||
bool last_try = false;
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
|
||||
"DBImpl::MultiGet::LastTry", [&](void* /*arg*/) {
|
||||
last_try = true;
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
|
||||
});
|
||||
"DBImpl::MultiGet::LastTry", [&](void* /*arg*/) { last_try = true; });
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
|
||||
"DBImpl::MultiGet::AfterRefSV", [&](void* /*arg*/) {
|
||||
if (last_try) {
|
||||
@@ -1447,8 +1444,28 @@ TEST_P(DBMultiGetTestWithParam, MultiGetMultiCFMutex) {
|
||||
}
|
||||
}
|
||||
});
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency({
|
||||
{"DBImpl::MultiGet::AfterLastTryRefSV",
|
||||
"DBMultiGetTestWithParam::MultiGetMultiCFMutex:BeforeCreateSV"},
|
||||
{"DBMultiGetTestWithParam::MultiGetMultiCFMutex:AfterCreateSV",
|
||||
"DBImpl::MultiGet::BeforeLastTryUnRefSV"},
|
||||
});
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
|
||||
|
||||
port::Thread create_sv_thread([this]() {
|
||||
TEST_SYNC_POINT(
|
||||
"DBMultiGetTestWithParam::MultiGetMultiCFMutex:BeforeCreateSV");
|
||||
// Create a new SuperVersion for each column family after last_try
|
||||
// of MultiGet ref SuperVersion and before unref it.
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
ASSERT_OK(Put(i, "cf" + std::to_string(i) + "_key",
|
||||
"cf" + std::to_string(i) + "_val_after_last_try"));
|
||||
ASSERT_OK(Flush(i));
|
||||
}
|
||||
TEST_SYNC_POINT(
|
||||
"DBMultiGetTestWithParam::MultiGetMultiCFMutex:AfterCreateSV");
|
||||
});
|
||||
|
||||
std::vector<int> cfs;
|
||||
std::vector<std::string> keys;
|
||||
std::vector<std::string> values;
|
||||
@@ -1460,6 +1477,7 @@ TEST_P(DBMultiGetTestWithParam, MultiGetMultiCFMutex) {
|
||||
|
||||
values = MultiGet(cfs, keys, nullptr, std::get<0>(GetParam()),
|
||||
std::get<1>(GetParam()));
|
||||
create_sv_thread.join();
|
||||
ASSERT_TRUE(last_try);
|
||||
ASSERT_EQ(values.size(), 8);
|
||||
for (unsigned int j = 0; j < values.size(); ++j) {
|
||||
@@ -1473,6 +1491,7 @@ TEST_P(DBMultiGetTestWithParam, MultiGetMultiCFMutex) {
|
||||
->cfd();
|
||||
ASSERT_NE(cfd->TEST_GetLocalSV()->Get(), SuperVersion::kSVInUse);
|
||||
}
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
|
||||
}
|
||||
|
||||
TEST_P(DBMultiGetTestWithParam, MultiGetMultiCFSnapshot) {
|
||||
@@ -3635,10 +3654,12 @@ class DBBasicTestMultiGet : public DBTestBase {
|
||||
|
||||
Status Insert(const Slice& key, Cache::ObjectPtr value,
|
||||
const CacheItemHelper* helper, size_t charge,
|
||||
Handle** handle = nullptr,
|
||||
Priority priority = Priority::LOW) override {
|
||||
Handle** handle = nullptr, Priority priority = Priority::LOW,
|
||||
const Slice& compressed = Slice(),
|
||||
CompressionType type = kNoCompression) override {
|
||||
num_inserts_++;
|
||||
return target_->Insert(key, value, helper, charge, handle, priority);
|
||||
return target_->Insert(key, value, helper, charge, handle, priority,
|
||||
compressed, type);
|
||||
}
|
||||
|
||||
Handle* Lookup(const Slice& key, const CacheItemHelper* helper,
|
||||
|
||||
@@ -294,7 +294,9 @@ class ReadOnlyCacheWrapper : public CacheWrapper {
|
||||
|
||||
Status Insert(const Slice& /*key*/, Cache::ObjectPtr /*value*/,
|
||||
const CacheItemHelper* /*helper*/, size_t /*charge*/,
|
||||
Handle** /*handle*/, Priority /*priority*/) override {
|
||||
Handle** /*handle*/, Priority /*priority*/,
|
||||
const Slice& /*compressed*/,
|
||||
CompressionType /*type*/) override {
|
||||
return Status::NotSupported();
|
||||
}
|
||||
};
|
||||
@@ -628,13 +630,15 @@ class MockCache : public LRUCache {
|
||||
|
||||
Status Insert(const Slice& key, Cache::ObjectPtr value,
|
||||
const Cache::CacheItemHelper* helper, size_t charge,
|
||||
Handle** handle, Priority priority) override {
|
||||
Handle** handle, Priority priority, const Slice& compressed,
|
||||
CompressionType type) override {
|
||||
if (priority == Priority::LOW) {
|
||||
low_pri_insert_count++;
|
||||
} else {
|
||||
high_pri_insert_count++;
|
||||
}
|
||||
return LRUCache::Insert(key, value, helper, charge, handle, priority);
|
||||
return LRUCache::Insert(key, value, helper, charge, handle, priority,
|
||||
compressed, type);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1775,6 +1775,64 @@ TEST_F(DBBloomFilterTest, ContextCustomFilterPolicy) {
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(DBBloomFilterTest, MutatingRibbonFilterPolicy) {
|
||||
// Test that RibbonFilterPolicy has a mutable bloom_before_level fields that
|
||||
// can be updated through SetOptions
|
||||
|
||||
Options options = CurrentOptions();
|
||||
options.statistics = CreateDBStatistics();
|
||||
auto& stats = *options.statistics;
|
||||
BlockBasedTableOptions table_options;
|
||||
// First config forces Bloom filter, to establish a baseline before
|
||||
// SetOptions().
|
||||
table_options.filter_policy.reset(NewRibbonFilterPolicy(10, INT_MAX));
|
||||
double expected_bpk = 10.0;
|
||||
// Other configs to try, with approx expected bits per key
|
||||
std::vector<std::pair<std::string, double>> configs = {{"-1", 7.0},
|
||||
{"0", 10.0}};
|
||||
|
||||
table_options.cache_index_and_filter_blocks = true;
|
||||
options.table_factory.reset(NewBlockBasedTableFactory(table_options));
|
||||
|
||||
ASSERT_OK(TryReopen(options));
|
||||
|
||||
char v[] = "a";
|
||||
|
||||
for (;; ++(v[0])) {
|
||||
const int maxKey = 8000;
|
||||
for (int i = 0; i < maxKey; i++) {
|
||||
ASSERT_OK(Put(Key(i), v));
|
||||
}
|
||||
ASSERT_OK(Flush());
|
||||
|
||||
for (int i = 0; i < maxKey; i++) {
|
||||
ASSERT_EQ(Get(Key(i)), v);
|
||||
}
|
||||
|
||||
uint64_t filter_bytes =
|
||||
stats.getAndResetTickerCount(BLOCK_CACHE_FILTER_BYTES_INSERT);
|
||||
|
||||
EXPECT_NEAR(filter_bytes * 8.0 / maxKey, expected_bpk, 0.3);
|
||||
|
||||
if (configs.empty()) {
|
||||
break;
|
||||
}
|
||||
|
||||
ASSERT_OK(
|
||||
db_->SetOptions({{"table_factory.filter_policy.bloom_before_level",
|
||||
configs.back().first}}));
|
||||
|
||||
// Ensure original object is mutated
|
||||
std::string val;
|
||||
ASSERT_OK(
|
||||
table_options.filter_policy->GetOption({}, "bloom_before_level", &val));
|
||||
ASSERT_EQ(configs.back().first, val);
|
||||
|
||||
expected_bpk = configs.back().second;
|
||||
configs.pop_back();
|
||||
}
|
||||
}
|
||||
|
||||
class SliceTransformLimitedDomain : public SliceTransform {
|
||||
const char* Name() const override { return "SliceTransformLimitedDomain"; }
|
||||
|
||||
|
||||
@@ -166,9 +166,12 @@ class ChangeFilter : public CompactionFilter {
|
||||
class KeepFilterFactory : public CompactionFilterFactory {
|
||||
public:
|
||||
explicit KeepFilterFactory(bool check_context = false,
|
||||
bool check_context_cf_id = false)
|
||||
bool check_context_cf_id = false,
|
||||
bool check_context_input_table_properties = false)
|
||||
: check_context_(check_context),
|
||||
check_context_cf_id_(check_context_cf_id),
|
||||
check_context_input_table_properties_(
|
||||
check_context_input_table_properties),
|
||||
compaction_filter_created_(false) {}
|
||||
|
||||
std::unique_ptr<CompactionFilter> CreateCompactionFilter(
|
||||
@@ -176,6 +179,11 @@ class KeepFilterFactory : public CompactionFilterFactory {
|
||||
if (check_context_) {
|
||||
EXPECT_EQ(expect_full_compaction_.load(), context.is_full_compaction);
|
||||
EXPECT_EQ(expect_manual_compaction_.load(), context.is_manual_compaction);
|
||||
EXPECT_EQ(expect_input_start_level_.load(), context.input_start_level);
|
||||
}
|
||||
if (check_context_input_table_properties_) {
|
||||
EXPECT_TRUE(expect_input_table_properties_ ==
|
||||
context.input_table_properties);
|
||||
}
|
||||
if (check_context_cf_id_) {
|
||||
EXPECT_EQ(expect_cf_id_.load(), context.column_family_id);
|
||||
@@ -189,9 +197,15 @@ class KeepFilterFactory : public CompactionFilterFactory {
|
||||
const char* Name() const override { return "KeepFilterFactory"; }
|
||||
bool check_context_;
|
||||
bool check_context_cf_id_;
|
||||
// `check_context_input_table_properties_` can be true only when access to
|
||||
// `expect_input_table_properties_` is syncronized since we can't have
|
||||
// std::atomic<TablePropertiesCollection> unfortunately
|
||||
bool check_context_input_table_properties_;
|
||||
std::atomic_bool expect_full_compaction_;
|
||||
std::atomic_bool expect_manual_compaction_;
|
||||
std::atomic<uint32_t> expect_cf_id_;
|
||||
std::atomic<int> expect_input_start_level_;
|
||||
TablePropertiesCollection expect_input_table_properties_;
|
||||
bool compaction_filter_created_;
|
||||
};
|
||||
|
||||
@@ -654,7 +668,9 @@ TEST_F(DBTestCompactionFilter, CompactionFilterWithMergeOperator) {
|
||||
}
|
||||
|
||||
TEST_F(DBTestCompactionFilter, CompactionFilterContextManual) {
|
||||
KeepFilterFactory* filter = new KeepFilterFactory(true, true);
|
||||
KeepFilterFactory* filter = new KeepFilterFactory(
|
||||
true /* check_context */, true /* check_context_cf_id */,
|
||||
true /* check_context_input_table_properties */);
|
||||
|
||||
Options options = CurrentOptions();
|
||||
options.compaction_style = kCompactionStyleUniversal;
|
||||
@@ -662,8 +678,9 @@ TEST_F(DBTestCompactionFilter, CompactionFilterContextManual) {
|
||||
options.compression = kNoCompression;
|
||||
options.level0_file_num_compaction_trigger = 8;
|
||||
Reopen(options);
|
||||
const int kNumFiles = 3;
|
||||
int num_keys_per_file = 400;
|
||||
for (int j = 0; j < 3; j++) {
|
||||
for (int j = 0; j < kNumFiles; j++) {
|
||||
// Write several keys.
|
||||
const std::string value(10, 'x');
|
||||
for (int i = 0; i < num_keys_per_file; i++) {
|
||||
@@ -683,6 +700,11 @@ TEST_F(DBTestCompactionFilter, CompactionFilterContextManual) {
|
||||
filter->expect_manual_compaction_.store(true);
|
||||
filter->expect_full_compaction_.store(true);
|
||||
filter->expect_cf_id_.store(0);
|
||||
filter->expect_input_start_level_.store(0);
|
||||
ASSERT_OK(dbfull()->GetPropertiesOfAllTables(
|
||||
&filter->expect_input_table_properties_));
|
||||
ASSERT_TRUE(filter->expect_input_table_properties_.size() == kNumFiles);
|
||||
|
||||
ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr));
|
||||
ASSERT_EQ(cfilter_count, 700);
|
||||
ASSERT_EQ(NumSortedRuns(0), 1);
|
||||
|
||||
+186
-8
@@ -3536,12 +3536,12 @@ TEST_P(DBCompactionWaitForCompactTest,
|
||||
// (has_unpersisted_data_ true) Check to make sure there's no extra L0 file
|
||||
// created from WAL. Re-opening DB won't trigger any flush or compaction
|
||||
|
||||
int compaction_finished = 0;
|
||||
std::atomic_int compaction_finished = 0;
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
|
||||
"DBImpl::BackgroundCompaction:Finish",
|
||||
[&](void*) { compaction_finished++; });
|
||||
|
||||
int flush_finished = 0;
|
||||
std::atomic_int flush_finished = 0;
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
|
||||
"FlushJob::End", [&](void*) { flush_finished++; });
|
||||
|
||||
@@ -6025,23 +6025,18 @@ TEST_P(DBCompactionDirectIOTest, DirectIO) {
|
||||
options.use_direct_io_for_flush_and_compaction = GetParam();
|
||||
options.env = MockEnv::Create(Env::Default());
|
||||
Reopen(options);
|
||||
bool readahead = false;
|
||||
SyncPoint::GetInstance()->SetCallBack(
|
||||
"CompactionJob::OpenCompactionOutputFile", [&](void* arg) {
|
||||
bool* use_direct_writes = static_cast<bool*>(arg);
|
||||
ASSERT_EQ(*use_direct_writes,
|
||||
options.use_direct_io_for_flush_and_compaction);
|
||||
});
|
||||
if (options.use_direct_io_for_flush_and_compaction) {
|
||||
SyncPoint::GetInstance()->SetCallBack(
|
||||
"SanitizeOptions:direct_io", [&](void* /*arg*/) { readahead = true; });
|
||||
}
|
||||
SyncPoint::GetInstance()->EnableProcessing();
|
||||
CreateAndReopenWithCF({"pikachu"}, options);
|
||||
MakeTables(3, "p", "q", 1);
|
||||
ASSERT_EQ("1,1,1", FilesPerLevel(1));
|
||||
Compact(1, "p", "q");
|
||||
ASSERT_EQ(readahead, options.use_direct_reads);
|
||||
ASSERT_EQ(false, options.use_direct_reads);
|
||||
ASSERT_EQ("0,0,1", FilesPerLevel(1));
|
||||
Destroy(options);
|
||||
delete options.env;
|
||||
@@ -10042,6 +10037,189 @@ TEST_F(DBCompactionTest, VerifyRecordCount) {
|
||||
"processed.";
|
||||
ASSERT_TRUE(std::strstr(s.getState(), expect));
|
||||
}
|
||||
|
||||
TEST_F(DBCompactionTest, ErrorWhenReadFileHead) {
|
||||
// This is to test a bug that is fixed in
|
||||
// https://github.com/facebook/rocksdb/pull/11782.
|
||||
//
|
||||
// Ingest error when reading from a file with offset = 0,
|
||||
// See if compaction handles it correctly.
|
||||
Options opts = CurrentOptions();
|
||||
opts.num_levels = 7;
|
||||
opts.compression = kNoCompression;
|
||||
DestroyAndReopen(opts);
|
||||
|
||||
// Set up LSM
|
||||
// L5: F1 [key0, key99], F2 [key100, key199]
|
||||
// L6: F3 [key50, key149]
|
||||
Random rnd(301);
|
||||
const int kValLen = 100;
|
||||
for (int error_file = 1; error_file <= 3; ++error_file) {
|
||||
for (int i = 50; i < 150; ++i) {
|
||||
ASSERT_OK(Put(Key(i), rnd.RandomString(kValLen)));
|
||||
}
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(6);
|
||||
|
||||
std::vector<std::string> values;
|
||||
for (int i = 0; i < 100; ++i) {
|
||||
values.emplace_back(rnd.RandomString(kValLen));
|
||||
ASSERT_OK(Put(Key(i), values.back()));
|
||||
}
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(5);
|
||||
|
||||
for (int i = 100; i < 200; ++i) {
|
||||
values.emplace_back(rnd.RandomString(kValLen));
|
||||
ASSERT_OK(Put(Key(i), values.back()));
|
||||
}
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(5);
|
||||
|
||||
ASSERT_EQ(2, NumTableFilesAtLevel(5));
|
||||
ASSERT_EQ(1, NumTableFilesAtLevel(6));
|
||||
|
||||
std::atomic_int count = 0;
|
||||
SyncPoint::GetInstance()->SetCallBack(
|
||||
"RandomAccessFileReader::Read::BeforeReturn",
|
||||
[&count, &error_file](void* pair_ptr) {
|
||||
auto p =
|
||||
reinterpret_cast<std::pair<std::string*, IOStatus*>*>(pair_ptr);
|
||||
int cur = ++count;
|
||||
if (cur == error_file) {
|
||||
IOStatus* io_s = p->second;
|
||||
*io_s = IOStatus::IOError();
|
||||
io_s->SetRetryable(true);
|
||||
}
|
||||
});
|
||||
SyncPoint::GetInstance()->EnableProcessing();
|
||||
|
||||
Status s = db_->CompactRange(CompactRangeOptions(), nullptr, nullptr);
|
||||
// Failed compaction should not lose data.
|
||||
PinnableSlice slice;
|
||||
for (int i = 0; i < 200; ++i) {
|
||||
ASSERT_OK(Get(Key(i), &slice));
|
||||
ASSERT_EQ(slice, values[i]);
|
||||
}
|
||||
ASSERT_NOK(s);
|
||||
ASSERT_TRUE(s.IsIOError());
|
||||
s = db_->CompactRange(CompactRangeOptions(), nullptr, nullptr);
|
||||
ASSERT_OK(s);
|
||||
for (int i = 0; i < 200; ++i) {
|
||||
ASSERT_OK(Get(Key(i), &slice));
|
||||
ASSERT_EQ(slice, values[i]);
|
||||
}
|
||||
SyncPoint::GetInstance()->DisableProcessing();
|
||||
DestroyAndReopen(opts);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(DBCompactionTest, ReleaseCompactionDuringManifestWrite) {
|
||||
// Tests the fix for issue #10257.
|
||||
// Compactions are released in LogAndApply() so that picking a compaction
|
||||
// from the new Version won't see these compactions as registered.
|
||||
Options options = CurrentOptions();
|
||||
options.compaction_style = kCompactionStyleLevel;
|
||||
// Make sure we can run multiple compactions at the same time.
|
||||
env_->SetBackgroundThreads(3, Env::Priority::LOW);
|
||||
env_->SetBackgroundThreads(3, Env::Priority::BOTTOM);
|
||||
options.max_background_compactions = 3;
|
||||
options.num_levels = 4;
|
||||
DestroyAndReopen(options);
|
||||
Random rnd(301);
|
||||
|
||||
// Construct the following LSM
|
||||
// L2: [K1-K2] [K10-K11] [k100-k101]
|
||||
// L3: [K1] [K10] [k100]
|
||||
// We will have 3 threads to run 3 manual compactions.
|
||||
// The first thread that writes to MANIFEST will not finish
|
||||
// until the next two threads enters LogAndApply() and form
|
||||
// a write group.
|
||||
// We check that compactions are all released after the first
|
||||
// thread from the write group finishes writing to MANIFEST.
|
||||
|
||||
// L3
|
||||
ASSERT_OK(Put(Key(1), rnd.RandomString(20)));
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(3);
|
||||
ASSERT_OK(Put(Key(10), rnd.RandomString(20)));
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(3);
|
||||
ASSERT_OK(Put(Key(100), rnd.RandomString(20)));
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(3);
|
||||
// L2
|
||||
ASSERT_OK(Put(Key(100), rnd.RandomString(20)));
|
||||
ASSERT_OK(Put(Key(101), rnd.RandomString(20)));
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(2);
|
||||
ASSERT_OK(Put(Key(1), rnd.RandomString(20)));
|
||||
ASSERT_OK(Put(Key(2), rnd.RandomString(20)));
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(2);
|
||||
ASSERT_OK(Put(Key(10), rnd.RandomString(20)));
|
||||
ASSERT_OK(Put(Key(11), rnd.RandomString(20)));
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(2);
|
||||
|
||||
ASSERT_EQ(NumTableFilesAtLevel(1), 0);
|
||||
ASSERT_EQ(NumTableFilesAtLevel(2), 3);
|
||||
ASSERT_EQ(NumTableFilesAtLevel(3), 3);
|
||||
|
||||
SyncPoint::GetInstance()->ClearAllCallBacks();
|
||||
std::atomic_int count = 0;
|
||||
SyncPoint::GetInstance()->SetCallBack(
|
||||
"VersionSet::LogAndApply:BeforeWriterWaiting", [&](void*) {
|
||||
int c = count.fetch_add(1);
|
||||
if (c == 2) {
|
||||
TEST_SYNC_POINT("all threads to enter LogAndApply");
|
||||
}
|
||||
});
|
||||
SyncPoint::GetInstance()->LoadDependency(
|
||||
{{"all threads to enter LogAndApply",
|
||||
"VersionSet::LogAndApply:WriteManifestStart"}});
|
||||
// Verify that compactions are released after writing to MANIFEST
|
||||
std::atomic_int after_compact_count = 0;
|
||||
SyncPoint::GetInstance()->SetCallBack(
|
||||
"DBImpl::BackgroundCompaction:AfterCompaction", [&](void* ptr) {
|
||||
int c = after_compact_count.fetch_add(1);
|
||||
if (c > 0) {
|
||||
ColumnFamilyData* cfd = (ColumnFamilyData*)(ptr);
|
||||
ASSERT_TRUE(
|
||||
cfd->compaction_picker()->compactions_in_progress()->empty());
|
||||
}
|
||||
});
|
||||
SyncPoint::GetInstance()->EnableProcessing();
|
||||
|
||||
std::vector<std::thread> threads;
|
||||
threads.emplace_back(std::thread([&]() {
|
||||
std::string k1_str = Key(1);
|
||||
std::string k2_str = Key(2);
|
||||
Slice k1 = k1_str;
|
||||
Slice k2 = k2_str;
|
||||
ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &k1, &k2));
|
||||
}));
|
||||
threads.emplace_back(std::thread([&]() {
|
||||
std::string k10_str = Key(10);
|
||||
std::string k11_str = Key(11);
|
||||
Slice k10 = k10_str;
|
||||
Slice k11 = k11_str;
|
||||
ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &k10, &k11));
|
||||
}));
|
||||
std::string k100_str = Key(100);
|
||||
std::string k101_str = Key(101);
|
||||
Slice k100 = k100_str;
|
||||
Slice k101 = k101_str;
|
||||
ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &k100, &k101));
|
||||
|
||||
for (auto& thread : threads) {
|
||||
thread.join();
|
||||
}
|
||||
|
||||
SyncPoint::GetInstance()->DisableProcessing();
|
||||
SyncPoint::GetInstance()->ClearAllCallBacks();
|
||||
}
|
||||
|
||||
} // namespace ROCKSDB_NAMESPACE
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
|
||||
@@ -3193,6 +3193,279 @@ INSTANTIATE_TEST_CASE_P(DBFlushDirectIOTest, DBFlushDirectIOTest,
|
||||
|
||||
INSTANTIATE_TEST_CASE_P(DBAtomicFlushTest, DBAtomicFlushTest, testing::Bool());
|
||||
|
||||
TEST_F(DBFlushTest, NonAtomicFlushRollbackPendingFlushes) {
|
||||
// Fix a bug in when atomic_flush=false.
|
||||
// The bug can happen as follows:
|
||||
// Start Flush0 for memtable M0 to SST0
|
||||
// Start Flush1 for memtable M1 to SST1
|
||||
// Flush1 returns OK, but don't install to MANIFEST and let whoever flushes
|
||||
// M0 to take care of it
|
||||
// Flush0 finishes with a retryable IOError
|
||||
// - It rollbacks M0, (incorrectly) not M1
|
||||
// - Deletes SST1 and SST2
|
||||
//
|
||||
// Auto-recovery will start Flush2 for M0, it does not pick up M1 since it
|
||||
// thinks that M1 is flushed
|
||||
// Flush2 writes SST3 and finishes OK, tries to install SST3 and SST2
|
||||
// Error opening SST2 since it's already deleted
|
||||
//
|
||||
// The fix is to let Flush0 also rollback M1.
|
||||
Options opts = CurrentOptions();
|
||||
opts.atomic_flush = false;
|
||||
opts.memtable_factory.reset(test::NewSpecialSkipListFactory(1));
|
||||
opts.max_write_buffer_number = 64;
|
||||
opts.max_background_flushes = 4;
|
||||
env_->SetBackgroundThreads(4, Env::HIGH);
|
||||
DestroyAndReopen(opts);
|
||||
std::atomic_int flush_count = 0;
|
||||
SyncPoint::GetInstance()->ClearAllCallBacks();
|
||||
SyncPoint::GetInstance()->DisableProcessing();
|
||||
SyncPoint::GetInstance()->SetCallBack(
|
||||
"FlushJob::WriteLevel0Table:s", [&](void* s_ptr) {
|
||||
int c = flush_count.fetch_add(1);
|
||||
if (c == 0) {
|
||||
Status* s = (Status*)(s_ptr);
|
||||
IOStatus io_error = IOStatus::IOError("injected foobar");
|
||||
io_error.SetRetryable(true);
|
||||
*s = io_error;
|
||||
TEST_SYNC_POINT("Let mem1 flush start");
|
||||
TEST_SYNC_POINT("Wait for mem1 flush to finish");
|
||||
}
|
||||
});
|
||||
SyncPoint::GetInstance()->LoadDependency(
|
||||
{{"Let mem1 flush start", "Mem1 flush starts"},
|
||||
{"DBImpl::BGWorkFlush:done", "Wait for mem1 flush to finish"},
|
||||
{"RecoverFromRetryableBGIOError:RecoverSuccess",
|
||||
"Wait for error recover"}});
|
||||
// Need first flush to wait for the second flush to finish
|
||||
SyncPoint::GetInstance()->EnableProcessing();
|
||||
ASSERT_OK(Put(Key(1), "val1"));
|
||||
// trigger bg flush mem0
|
||||
ASSERT_OK(Put(Key(2), "val2"));
|
||||
TEST_SYNC_POINT("Mem1 flush starts");
|
||||
// trigger bg flush mem1
|
||||
ASSERT_OK(Put(Key(3), "val3"));
|
||||
|
||||
TEST_SYNC_POINT("Wait for error recover");
|
||||
ASSERT_EQ(1, NumTableFilesAtLevel(0));
|
||||
SyncPoint::GetInstance()->ClearAllCallBacks();
|
||||
SyncPoint::GetInstance()->DisableProcessing();
|
||||
}
|
||||
|
||||
TEST_F(DBFlushTest, AbortNonAtomicFlushWhenBGError) {
|
||||
// Fix a bug in when atomic_flush=false.
|
||||
// The bug can happen as follows:
|
||||
// Start Flush0 for memtable M0 to SST0
|
||||
// Start Flush1 for memtable M1 to SST1
|
||||
// Flush1 returns OK, but doesn't install output MANIFEST and let whoever
|
||||
// flushes M0 to take care of it
|
||||
// Start Flush2 for memtable M2 to SST2
|
||||
// Flush0 finishes with a retryable IOError
|
||||
// - It rollbacks M0 AND M1
|
||||
// - Deletes SST1 and SST2
|
||||
// Flush2 finishes, does not rollback M2,
|
||||
// - releases the pending file number that keeps SST2 alive
|
||||
// - deletes SST2
|
||||
//
|
||||
// Then auto-recovery starts, error opening SST2 when try to install
|
||||
// flush result
|
||||
//
|
||||
// The fix is to let Flush2 rollback M2 if it finds that
|
||||
// there is a background error.
|
||||
Options opts = CurrentOptions();
|
||||
opts.atomic_flush = false;
|
||||
opts.memtable_factory.reset(test::NewSpecialSkipListFactory(1));
|
||||
opts.max_write_buffer_number = 64;
|
||||
opts.max_background_flushes = 4;
|
||||
env_->SetBackgroundThreads(4, Env::HIGH);
|
||||
DestroyAndReopen(opts);
|
||||
std::atomic_int flush_count = 0;
|
||||
SyncPoint::GetInstance()->ClearAllCallBacks();
|
||||
SyncPoint::GetInstance()->DisableProcessing();
|
||||
SyncPoint::GetInstance()->SetCallBack(
|
||||
"FlushJob::WriteLevel0Table:s", [&](void* s_ptr) {
|
||||
int c = flush_count.fetch_add(1);
|
||||
if (c == 0) {
|
||||
Status* s = (Status*)(s_ptr);
|
||||
IOStatus io_error = IOStatus::IOError("injected foobar");
|
||||
io_error.SetRetryable(true);
|
||||
*s = io_error;
|
||||
TEST_SYNC_POINT("Let mem1 flush start");
|
||||
TEST_SYNC_POINT("Wait for mem1 flush to finish");
|
||||
|
||||
TEST_SYNC_POINT("Let mem2 flush start");
|
||||
TEST_SYNC_POINT("Wait for mem2 to start writing table");
|
||||
}
|
||||
});
|
||||
|
||||
SyncPoint::GetInstance()->SetCallBack(
|
||||
"FlushJob::WriteLevel0Table", [&](void* mems) {
|
||||
autovector<MemTable*>* mems_ptr = (autovector<MemTable*>*)mems;
|
||||
if ((*mems_ptr)[0]->GetID() == 3) {
|
||||
TEST_SYNC_POINT("Mem2 flush starts writing table");
|
||||
TEST_SYNC_POINT("Mem2 flush waits until rollback");
|
||||
}
|
||||
});
|
||||
SyncPoint::GetInstance()->LoadDependency(
|
||||
{{"Let mem1 flush start", "Mem1 flush starts"},
|
||||
{"DBImpl::BGWorkFlush:done", "Wait for mem1 flush to finish"},
|
||||
{"Let mem2 flush start", "Mem2 flush starts"},
|
||||
{"Mem2 flush starts writing table",
|
||||
"Wait for mem2 to start writing table"},
|
||||
{"RollbackMemtableFlush", "Mem2 flush waits until rollback"},
|
||||
{"RecoverFromRetryableBGIOError:RecoverSuccess",
|
||||
"Wait for error recover"}});
|
||||
SyncPoint::GetInstance()->EnableProcessing();
|
||||
|
||||
ASSERT_OK(Put(Key(1), "val1"));
|
||||
// trigger bg flush mem0
|
||||
ASSERT_OK(Put(Key(2), "val2"));
|
||||
TEST_SYNC_POINT("Mem1 flush starts");
|
||||
// trigger bg flush mem1
|
||||
ASSERT_OK(Put(Key(3), "val3"));
|
||||
|
||||
TEST_SYNC_POINT("Mem2 flush starts");
|
||||
ASSERT_OK(Put(Key(4), "val4"));
|
||||
|
||||
TEST_SYNC_POINT("Wait for error recover");
|
||||
// Recovery flush writes 3 memtables together into 1 file.
|
||||
ASSERT_EQ(1, NumTableFilesAtLevel(0));
|
||||
SyncPoint::GetInstance()->ClearAllCallBacks();
|
||||
SyncPoint::GetInstance()->DisableProcessing();
|
||||
}
|
||||
|
||||
TEST_F(DBFlushTest, NonAtomicNormalFlushAbortWhenBGError) {
|
||||
Options opts = CurrentOptions();
|
||||
opts.atomic_flush = false;
|
||||
opts.memtable_factory.reset(test::NewSpecialSkipListFactory(1));
|
||||
opts.max_write_buffer_number = 64;
|
||||
opts.max_background_flushes = 1;
|
||||
env_->SetBackgroundThreads(2, Env::HIGH);
|
||||
DestroyAndReopen(opts);
|
||||
SyncPoint::GetInstance()->ClearAllCallBacks();
|
||||
SyncPoint::GetInstance()->DisableProcessing();
|
||||
std::atomic_int flush_write_table_count = 0;
|
||||
SyncPoint::GetInstance()->SetCallBack(
|
||||
"FlushJob::WriteLevel0Table:s", [&](void* s_ptr) {
|
||||
int c = flush_write_table_count.fetch_add(1);
|
||||
if (c == 0) {
|
||||
Status* s = (Status*)(s_ptr);
|
||||
IOStatus io_error = IOStatus::IOError("injected foobar");
|
||||
io_error.SetRetryable(true);
|
||||
*s = io_error;
|
||||
}
|
||||
});
|
||||
|
||||
SyncPoint::GetInstance()->EnableProcessing();
|
||||
SyncPoint::GetInstance()->LoadDependency(
|
||||
{{"Let error recovery start",
|
||||
"RecoverFromRetryableBGIOError:BeforeStart"},
|
||||
{"RecoverFromRetryableBGIOError:RecoverSuccess",
|
||||
"Wait for error recover"}});
|
||||
|
||||
ASSERT_OK(Put(Key(1), "val1"));
|
||||
// trigger bg flush0 for mem0
|
||||
ASSERT_OK(Put(Key(2), "val2"));
|
||||
// Not checking status since this wait can finish before flush starts.
|
||||
dbfull()->TEST_WaitForFlushMemTable().PermitUncheckedError();
|
||||
|
||||
// trigger bg flush1 for mem1, should see bg error and abort
|
||||
// before picking a memtable to flush
|
||||
ASSERT_OK(Put(Key(3), "val3"));
|
||||
ASSERT_NOK(dbfull()->TEST_WaitForFlushMemTable());
|
||||
ASSERT_EQ(0, NumTableFilesAtLevel(0));
|
||||
|
||||
TEST_SYNC_POINT("Let error recovery start");
|
||||
TEST_SYNC_POINT("Wait for error recover");
|
||||
// Recovery flush writes 2 memtables together into 1 file.
|
||||
ASSERT_EQ(1, NumTableFilesAtLevel(0));
|
||||
// 1 for flush 0 and 1 for recovery flush
|
||||
ASSERT_EQ(2, flush_write_table_count);
|
||||
SyncPoint::GetInstance()->ClearAllCallBacks();
|
||||
SyncPoint::GetInstance()->DisableProcessing();
|
||||
}
|
||||
|
||||
TEST_F(DBFlushTest, DBStuckAfterAtomicFlushError) {
|
||||
// Test for a bug with atomic flush where DB can become stuck
|
||||
// after a flush error. A repro timeline:
|
||||
//
|
||||
// Start Flush0 for mem0
|
||||
// Start Flush1 for mem1
|
||||
// Now Flush1 will wait for Flush0 to install mem0
|
||||
// Flush0 finishes with retryable IOError, rollbacks mem0
|
||||
// Resume starts and waits for background job to finish, i.e., Flush1
|
||||
// Fill memtable again, trigger Flush2 for mem0
|
||||
// Flush2 will get error status, and not rollback mem0, see code in
|
||||
// https://github.com/facebook/rocksdb/blob/b927ba5936216861c2c35ab68f50ba4a78e65747/db/db_impl/db_impl_compaction_flush.cc#L725
|
||||
//
|
||||
// DB is stuck since mem0 can never be picked now
|
||||
//
|
||||
// The fix is to rollback mem0 in Flush2, and let Flush1 also abort upon
|
||||
// background error besides waiting for older memtables to be installed.
|
||||
// The recovery flush in this case should pick up all memtables
|
||||
// and write them to a single L0 file.
|
||||
Options opts = CurrentOptions();
|
||||
opts.atomic_flush = true;
|
||||
opts.memtable_factory.reset(test::NewSpecialSkipListFactory(1));
|
||||
opts.max_write_buffer_number = 64;
|
||||
opts.max_background_flushes = 4;
|
||||
env_->SetBackgroundThreads(4, Env::HIGH);
|
||||
DestroyAndReopen(opts);
|
||||
|
||||
std::atomic_int flush_count = 0;
|
||||
SyncPoint::GetInstance()->ClearAllCallBacks();
|
||||
SyncPoint::GetInstance()->DisableProcessing();
|
||||
SyncPoint::GetInstance()->SetCallBack(
|
||||
"FlushJob::WriteLevel0Table:s", [&](void* s_ptr) {
|
||||
int c = flush_count.fetch_add(1);
|
||||
if (c == 0) {
|
||||
Status* s = (Status*)(s_ptr);
|
||||
IOStatus io_error = IOStatus::IOError("injected foobar");
|
||||
io_error.SetRetryable(true);
|
||||
*s = io_error;
|
||||
TEST_SYNC_POINT("Let flush for mem1 start");
|
||||
// Wait for Flush1 to start waiting to install flush result
|
||||
TEST_SYNC_POINT("Wait for flush for mem1");
|
||||
}
|
||||
});
|
||||
SyncPoint::GetInstance()->LoadDependency(
|
||||
{{"Let flush for mem1 start", "Flush for mem1"},
|
||||
{"DBImpl::AtomicFlushMemTablesToOutputFiles:WaitCV",
|
||||
"Wait for flush for mem1"},
|
||||
{"RecoverFromRetryableBGIOError:BeforeStart",
|
||||
"Wait for resume to start"},
|
||||
{"Recovery should continue here",
|
||||
"RecoverFromRetryableBGIOError:BeforeStart2"},
|
||||
{"RecoverFromRetryableBGIOError:RecoverSuccess",
|
||||
"Wait for error recover"}});
|
||||
SyncPoint::GetInstance()->EnableProcessing();
|
||||
ASSERT_OK(Put(Key(1), "val1"));
|
||||
// trigger Flush0 for mem0
|
||||
ASSERT_OK(Put(Key(2), "val2"));
|
||||
|
||||
// trigger Flush1 for mem1
|
||||
TEST_SYNC_POINT("Flush for mem1");
|
||||
ASSERT_OK(Put(Key(3), "val3"));
|
||||
|
||||
// Wait until resume started to schedule another flush
|
||||
TEST_SYNC_POINT("Wait for resume to start");
|
||||
// This flush should not be scheduled due to bg error
|
||||
ASSERT_OK(Put(Key(4), "val4"));
|
||||
|
||||
// TEST_WaitForBackgroundWork() returns background error
|
||||
// after all background work is done.
|
||||
ASSERT_NOK(dbfull()->TEST_WaitForBackgroundWork());
|
||||
// Flush should abort and not writing any table
|
||||
ASSERT_EQ(0, NumTableFilesAtLevel(0));
|
||||
|
||||
// Wait until this flush is done.
|
||||
TEST_SYNC_POINT("Recovery should continue here");
|
||||
TEST_SYNC_POINT("Wait for error recover");
|
||||
// error recovery can schedule new flushes, but should not
|
||||
// encounter error
|
||||
ASSERT_OK(dbfull()->TEST_WaitForBackgroundWork());
|
||||
ASSERT_EQ(1, NumTableFilesAtLevel(0));
|
||||
}
|
||||
} // namespace ROCKSDB_NAMESPACE
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
|
||||
@@ -59,12 +59,18 @@ Status CompactedDBImpl::Get(const ReadOptions& _read_options,
|
||||
|
||||
assert(user_comparator_);
|
||||
if (read_options.timestamp) {
|
||||
const Status s =
|
||||
FailIfTsMismatchCf(DefaultColumnFamily(), *(read_options.timestamp),
|
||||
/*ts_for_read=*/true);
|
||||
Status s =
|
||||
FailIfTsMismatchCf(DefaultColumnFamily(), *(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
if (read_options.timestamp->size() > 0) {
|
||||
s = FailIfReadCollapsedHistory(cfd_, cfd_->GetSuperVersion(),
|
||||
*(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const Status s = FailIfCfHasTs(DefaultColumnFamily());
|
||||
if (!s.ok()) {
|
||||
@@ -133,11 +139,17 @@ std::vector<Status> CompactedDBImpl::MultiGet(
|
||||
|
||||
if (read_options.timestamp) {
|
||||
Status s =
|
||||
FailIfTsMismatchCf(DefaultColumnFamily(), *(read_options.timestamp),
|
||||
/*ts_for_read=*/true);
|
||||
FailIfTsMismatchCf(DefaultColumnFamily(), *(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
return std::vector<Status>(num_keys, s);
|
||||
}
|
||||
if (read_options.timestamp->size() > 0) {
|
||||
s = FailIfReadCollapsedHistory(cfd_, cfd_->GetSuperVersion(),
|
||||
*(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
return std::vector<Status>(num_keys, s);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Status s = FailIfCfHasTs(DefaultColumnFamily());
|
||||
if (!s.ok()) {
|
||||
|
||||
+279
-147
@@ -106,6 +106,7 @@
|
||||
#include "util/mutexlock.h"
|
||||
#include "util/stop_watch.h"
|
||||
#include "util/string_util.h"
|
||||
#include "util/udt_util.h"
|
||||
#include "utilities/trace/replayer_impl.h"
|
||||
|
||||
namespace ROCKSDB_NAMESPACE {
|
||||
@@ -149,24 +150,6 @@ void DumpSupportInfo(Logger* logger) {
|
||||
|
||||
ROCKS_LOG_HEADER(logger, "DMutex implementation: %s", DMutex::kName());
|
||||
}
|
||||
|
||||
// `start` is the inclusive lower user key bound without user-defined timestamp
|
||||
// `limit` is the exclusive upper user key bound without user-defined timestamp
|
||||
std::tuple<Slice, Slice> MaybeAddTimestampsToRange(const Slice& start,
|
||||
const Slice& limit,
|
||||
size_t ts_sz,
|
||||
std::string* start_with_ts,
|
||||
std::string* limit_with_ts) {
|
||||
if (ts_sz == 0) {
|
||||
return std::make_tuple(start, limit);
|
||||
}
|
||||
// Maximum timestamp means including all key with any timestamp
|
||||
AppendKeyWithMaxTimestamp(start_with_ts, start, ts_sz);
|
||||
// Append a maximum timestamp as the range limit is exclusive:
|
||||
// [start, limit)
|
||||
AppendKeyWithMaxTimestamp(limit_with_ts, limit, ts_sz);
|
||||
return std::make_tuple(Slice(*start_with_ts), Slice(*limit_with_ts));
|
||||
}
|
||||
} // namespace
|
||||
|
||||
DBImpl::DBImpl(const DBOptions& options, const std::string& dbname,
|
||||
@@ -228,7 +211,6 @@ DBImpl::DBImpl(const DBOptions& options, const std::string& dbname,
|
||||
disable_delete_obsolete_files_(0),
|
||||
pending_purge_obsolete_files_(0),
|
||||
delete_obsolete_files_last_run_(immutable_db_options_.clock->NowMicros()),
|
||||
last_stats_dump_time_microsec_(0),
|
||||
has_unpersisted_data_(false),
|
||||
unable_to_release_oldest_log_(false),
|
||||
num_running_ingest_file_(0),
|
||||
@@ -372,7 +354,6 @@ Status DBImpl::ResumeImpl(DBRecoverContext context) {
|
||||
}
|
||||
|
||||
// Make sure the IO Status stored in version set is set to OK.
|
||||
bool file_deletion_disabled = !IsFileDeletionsEnabled();
|
||||
if (s.ok()) {
|
||||
IOStatus io_s = versions_->io_status();
|
||||
if (io_s.IsIOError()) {
|
||||
@@ -381,7 +362,7 @@ Status DBImpl::ResumeImpl(DBRecoverContext context) {
|
||||
// clean-up phase MANIFEST writing. We must have also disabled file
|
||||
// deletions.
|
||||
assert(!versions_->descriptor_log_);
|
||||
assert(file_deletion_disabled);
|
||||
assert(!IsFileDeletionsEnabled());
|
||||
// Since we are trying to recover from MANIFEST write error, we need to
|
||||
// switch to a new MANIFEST anyway. The old MANIFEST can be corrupted.
|
||||
// Therefore, force writing a dummy version edit because we do not know
|
||||
@@ -419,34 +400,6 @@ Status DBImpl::ResumeImpl(DBRecoverContext context) {
|
||||
}
|
||||
}
|
||||
|
||||
JobContext job_context(0);
|
||||
FindObsoleteFiles(&job_context, true);
|
||||
mutex_.Unlock();
|
||||
|
||||
job_context.manifest_file_number = 1;
|
||||
if (job_context.HaveSomethingToDelete()) {
|
||||
PurgeObsoleteFiles(job_context);
|
||||
}
|
||||
job_context.Clean();
|
||||
|
||||
if (s.ok()) {
|
||||
assert(versions_->io_status().ok());
|
||||
// If we reach here, we should re-enable file deletions if it was disabled
|
||||
// during previous error handling.
|
||||
if (file_deletion_disabled) {
|
||||
// Always return ok
|
||||
s = EnableFileDeletions(/*force=*/true);
|
||||
if (!s.ok()) {
|
||||
ROCKS_LOG_INFO(
|
||||
immutable_db_options_.info_log,
|
||||
"DB resume requested but could not enable file deletions [%s]",
|
||||
s.ToString().c_str());
|
||||
assert(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mutex_.Lock();
|
||||
if (s.ok()) {
|
||||
// This will notify and unblock threads waiting for error recovery to
|
||||
// finish. Those previouly waiting threads can now proceed, which may
|
||||
@@ -459,6 +412,15 @@ Status DBImpl::ResumeImpl(DBRecoverContext context) {
|
||||
error_handler_.GetRecoveryError().PermitUncheckedError();
|
||||
}
|
||||
|
||||
JobContext job_context(0);
|
||||
FindObsoleteFiles(&job_context, true);
|
||||
mutex_.Unlock();
|
||||
job_context.manifest_file_number = 1;
|
||||
if (job_context.HaveSomethingToDelete()) {
|
||||
PurgeObsoleteFiles(job_context);
|
||||
}
|
||||
job_context.Clean();
|
||||
|
||||
if (s.ok()) {
|
||||
ROCKS_LOG_INFO(immutable_db_options_.info_log, "Successfully resumed DB");
|
||||
} else {
|
||||
@@ -466,11 +428,34 @@ Status DBImpl::ResumeImpl(DBRecoverContext context) {
|
||||
s.ToString().c_str());
|
||||
}
|
||||
|
||||
mutex_.Lock();
|
||||
// Check for shutdown again before scheduling further compactions,
|
||||
// since we released and re-acquired the lock above
|
||||
if (shutdown_initiated_) {
|
||||
s = Status::ShutdownInProgress();
|
||||
}
|
||||
if (s.ok() && context.flush_after_recovery) {
|
||||
// Since we drop all non-recovery flush requests during recovery,
|
||||
// and new memtable may fill up during recovery,
|
||||
// schedule one more round of flush.
|
||||
FlushOptions flush_opts;
|
||||
flush_opts.allow_write_stall = false;
|
||||
flush_opts.wait = false;
|
||||
Status status = FlushAllColumnFamilies(
|
||||
flush_opts, FlushReason::kCatchUpAfterErrorRecovery);
|
||||
if (!status.ok()) {
|
||||
// FlushAllColumnFamilies internally should take care of setting
|
||||
// background error if needed.
|
||||
ROCKS_LOG_INFO(immutable_db_options_.info_log,
|
||||
"The catch up flush after successful recovery failed [%s]",
|
||||
s.ToString().c_str());
|
||||
}
|
||||
// FlushAllColumnFamilies releases and re-acquires mutex.
|
||||
if (shutdown_initiated_) {
|
||||
s = Status::ShutdownInProgress();
|
||||
}
|
||||
}
|
||||
|
||||
if (s.ok()) {
|
||||
for (auto cfd : *versions_->GetColumnFamilySet()) {
|
||||
SchedulePendingCompaction(cfd);
|
||||
@@ -766,7 +751,6 @@ void DBImpl::PrintStatistics() {
|
||||
}
|
||||
|
||||
Status DBImpl::StartPeriodicTaskScheduler() {
|
||||
|
||||
#ifndef NDEBUG
|
||||
// It only used by test to disable scheduler
|
||||
bool disable_scheduler = false;
|
||||
@@ -1693,7 +1677,8 @@ Status DBImpl::GetFullHistoryTsLow(ColumnFamilyHandle* column_family,
|
||||
}
|
||||
InstrumentedMutexLock l(&mutex_);
|
||||
*ts_low = cfd->GetFullHistoryTsLow();
|
||||
assert(cfd->user_comparator()->timestamp_size() == ts_low->size());
|
||||
assert(ts_low->empty() ||
|
||||
cfd->user_comparator()->timestamp_size() == ts_low->size());
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
@@ -1961,25 +1946,27 @@ Status DBImpl::GetImpl(const ReadOptions& read_options,
|
||||
return s;
|
||||
}
|
||||
|
||||
Status DBImpl::GetEntity(const ReadOptions& read_options,
|
||||
Status DBImpl::GetEntity(const ReadOptions& _read_options,
|
||||
ColumnFamilyHandle* column_family, const Slice& key,
|
||||
PinnableWideColumns* columns) {
|
||||
if (!column_family) {
|
||||
return Status::InvalidArgument(
|
||||
"Cannot call GetEntity without a column family handle");
|
||||
}
|
||||
|
||||
if (!columns) {
|
||||
return Status::InvalidArgument(
|
||||
"Cannot call GetEntity without a PinnableWideColumns object");
|
||||
}
|
||||
|
||||
if (read_options.io_activity != Env::IOActivity::kUnknown) {
|
||||
if (_read_options.io_activity != Env::IOActivity::kUnknown &&
|
||||
_read_options.io_activity != Env::IOActivity::kGetEntity) {
|
||||
return Status::InvalidArgument(
|
||||
"Cannot call GetEntity with `ReadOptions::io_activity` != "
|
||||
"`Env::IOActivity::kUnknown`");
|
||||
"`Env::IOActivity::kUnknown` or `Env::IOActivity::kGetEntity`");
|
||||
}
|
||||
ReadOptions read_options(_read_options);
|
||||
if (read_options.io_activity == Env::IOActivity::kUnknown) {
|
||||
read_options.io_activity = Env::IOActivity::kGetEntity;
|
||||
}
|
||||
|
||||
columns->Reset();
|
||||
|
||||
GetImplOptions get_impl_options;
|
||||
@@ -2025,11 +2012,9 @@ Status DBImpl::GetImpl(const ReadOptions& read_options, const Slice& key,
|
||||
|
||||
assert(get_impl_options.column_family);
|
||||
|
||||
|
||||
if (read_options.timestamp) {
|
||||
const Status s = FailIfTsMismatchCf(get_impl_options.column_family,
|
||||
*(read_options.timestamp),
|
||||
/*ts_for_read=*/true);
|
||||
*(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
@@ -2076,7 +2061,16 @@ Status DBImpl::GetImpl(const ReadOptions& read_options, const Slice& key,
|
||||
|
||||
// Acquire SuperVersion
|
||||
SuperVersion* sv = GetAndRefSuperVersion(cfd);
|
||||
if (read_options.timestamp && read_options.timestamp->size() > 0) {
|
||||
const Status s =
|
||||
FailIfReadCollapsedHistory(cfd, sv, *(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
ReturnAndCleanupSuperVersion(cfd, sv);
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
TEST_SYNC_POINT_CALLBACK("DBImpl::GetImpl:AfterAcquireSv", nullptr);
|
||||
TEST_SYNC_POINT("DBImpl::GetImpl:1");
|
||||
TEST_SYNC_POINT("DBImpl::GetImpl:2");
|
||||
|
||||
@@ -2227,6 +2221,12 @@ Status DBImpl::GetImpl(const ReadOptions& read_options, const Slice& key,
|
||||
RecordTick(stats_, NUMBER_KEYS_READ);
|
||||
size_t size = 0;
|
||||
if (s.ok()) {
|
||||
const auto& merge_threshold = read_options.merge_operand_count_threshold;
|
||||
if (merge_threshold.has_value() &&
|
||||
merge_context.GetNumOperands() > merge_threshold.value()) {
|
||||
s = Status::OkMergeOperandThresholdExceeded();
|
||||
}
|
||||
|
||||
if (get_impl_options.get_value) {
|
||||
if (get_impl_options.value) {
|
||||
size = get_impl_options.value->size();
|
||||
@@ -2352,8 +2352,7 @@ std::vector<Status> DBImpl::MultiGet(
|
||||
assert(column_family[i]);
|
||||
if (read_options.timestamp) {
|
||||
stat_list[i] =
|
||||
FailIfTsMismatchCf(column_family[i], *(read_options.timestamp),
|
||||
/*ts_for_read=*/true);
|
||||
FailIfTsMismatchCf(column_family[i], *(read_options.timestamp));
|
||||
if (!stat_list[i].ok()) {
|
||||
should_fail = true;
|
||||
}
|
||||
@@ -2385,8 +2384,6 @@ std::vector<Status> DBImpl::MultiGet(
|
||||
}
|
||||
}
|
||||
|
||||
SequenceNumber consistent_seqnum;
|
||||
|
||||
UnorderedMap<uint32_t, MultiGetColumnFamilyData> multiget_cf_data(
|
||||
column_family.size());
|
||||
for (auto cf : column_family) {
|
||||
@@ -2404,10 +2401,21 @@ std::vector<Status> DBImpl::MultiGet(
|
||||
[](UnorderedMap<uint32_t, MultiGetColumnFamilyData>::iterator&
|
||||
cf_iter) { return &cf_iter->second; };
|
||||
|
||||
bool unref_only =
|
||||
SequenceNumber consistent_seqnum;
|
||||
bool sv_from_thread_local;
|
||||
Status status =
|
||||
MultiCFSnapshot<UnorderedMap<uint32_t, MultiGetColumnFamilyData>>(
|
||||
read_options, nullptr, iter_deref_lambda, &multiget_cf_data,
|
||||
&consistent_seqnum);
|
||||
&consistent_seqnum, &sv_from_thread_local);
|
||||
|
||||
if (!status.ok()) {
|
||||
for (auto& s : stat_list) {
|
||||
if (s.ok()) {
|
||||
s = status;
|
||||
}
|
||||
}
|
||||
return stat_list;
|
||||
}
|
||||
|
||||
TEST_SYNC_POINT("DBImpl::MultiGet:AfterGetSeqNum1");
|
||||
TEST_SYNC_POINT("DBImpl::MultiGet:AfterGetSeqNum2");
|
||||
@@ -2488,8 +2496,15 @@ std::vector<Status> DBImpl::MultiGet(
|
||||
}
|
||||
|
||||
if (s.ok()) {
|
||||
const auto& merge_threshold = read_options.merge_operand_count_threshold;
|
||||
if (merge_threshold.has_value() &&
|
||||
merge_context.GetNumOperands() > merge_threshold.value()) {
|
||||
s = Status::OkMergeOperandThresholdExceeded();
|
||||
}
|
||||
|
||||
bytes_read += value->size();
|
||||
num_found++;
|
||||
|
||||
curr_value_size += value->size();
|
||||
if (curr_value_size > read_options.value_size_soft_limit) {
|
||||
while (++keys_read < num_keys) {
|
||||
@@ -2520,10 +2535,11 @@ std::vector<Status> DBImpl::MultiGet(
|
||||
|
||||
for (auto mgd_iter : multiget_cf_data) {
|
||||
auto mgd = mgd_iter.second;
|
||||
if (!unref_only) {
|
||||
if (sv_from_thread_local) {
|
||||
ReturnAndCleanupSuperVersion(mgd.cfd, mgd.super_version);
|
||||
} else {
|
||||
mgd.cfd->GetSuperVersion()->Unref();
|
||||
TEST_SYNC_POINT("DBImpl::MultiGet::BeforeLastTryUnRefSV");
|
||||
CleanupSuperVersion(mgd.super_version);
|
||||
}
|
||||
}
|
||||
RecordTick(stats_, NUMBER_MULTIGET_CALLS);
|
||||
@@ -2538,21 +2554,49 @@ std::vector<Status> DBImpl::MultiGet(
|
||||
}
|
||||
|
||||
template <class T>
|
||||
bool DBImpl::MultiCFSnapshot(
|
||||
Status DBImpl::MultiCFSnapshot(
|
||||
const ReadOptions& read_options, ReadCallback* callback,
|
||||
std::function<MultiGetColumnFamilyData*(typename T::iterator&)>&
|
||||
iter_deref_func,
|
||||
T* cf_list, SequenceNumber* snapshot) {
|
||||
T* cf_list, SequenceNumber* snapshot, bool* sv_from_thread_local) {
|
||||
PERF_TIMER_GUARD(get_snapshot_time);
|
||||
|
||||
assert(sv_from_thread_local);
|
||||
*sv_from_thread_local = true;
|
||||
Status s = Status::OK();
|
||||
const bool check_read_ts =
|
||||
read_options.timestamp && read_options.timestamp->size() > 0;
|
||||
// sv_from_thread_local set to false means the SuperVersion to be cleaned up
|
||||
// is acquired directly via ColumnFamilyData instead of thread local.
|
||||
const auto sv_cleanup_func = [&]() -> void {
|
||||
for (auto cf_iter = cf_list->begin(); cf_iter != cf_list->end();
|
||||
++cf_iter) {
|
||||
auto node = iter_deref_func(cf_iter);
|
||||
SuperVersion* super_version = node->super_version;
|
||||
ColumnFamilyData* cfd = node->cfd;
|
||||
if (super_version != nullptr) {
|
||||
if (*sv_from_thread_local) {
|
||||
ReturnAndCleanupSuperVersion(cfd, super_version);
|
||||
} else {
|
||||
CleanupSuperVersion(super_version);
|
||||
}
|
||||
}
|
||||
node->super_version = nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
bool last_try = false;
|
||||
if (cf_list->size() == 1) {
|
||||
// Fast path for a single column family. We can simply get the thread loca
|
||||
// Fast path for a single column family. We can simply get the thread local
|
||||
// super version
|
||||
auto cf_iter = cf_list->begin();
|
||||
auto node = iter_deref_func(cf_iter);
|
||||
node->super_version = GetAndRefSuperVersion(node->cfd);
|
||||
if (read_options.snapshot != nullptr) {
|
||||
if (check_read_ts) {
|
||||
s = FailIfReadCollapsedHistory(node->cfd, node->super_version,
|
||||
*(read_options.timestamp));
|
||||
}
|
||||
if (s.ok() && read_options.snapshot != nullptr) {
|
||||
// Note: In WritePrepared txns this is not necessary but not harmful
|
||||
// either. Because prep_seq > snapshot => commit_seq > snapshot so if
|
||||
// a snapshot is specified we should be fine with skipping seq numbers
|
||||
@@ -2566,7 +2610,7 @@ bool DBImpl::MultiCFSnapshot(
|
||||
if (callback) {
|
||||
*snapshot = std::max(*snapshot, callback->max_visible_seq());
|
||||
}
|
||||
} else {
|
||||
} else if (s.ok()) {
|
||||
// Since we get and reference the super version before getting
|
||||
// the snapshot number, without a mutex protection, it is possible
|
||||
// that a memtable switch happened in the middle and not all the
|
||||
@@ -2580,26 +2624,17 @@ bool DBImpl::MultiCFSnapshot(
|
||||
*snapshot = GetLastPublishedSequence();
|
||||
}
|
||||
} else {
|
||||
// If we end up with the same issue of memtable geting sealed during 2
|
||||
// If we end up with the same issue of memtable getting sealed during 2
|
||||
// consecutive retries, it means the write rate is very high. In that case
|
||||
// its probably ok to take the mutex on the 3rd try so we can succeed for
|
||||
// sure
|
||||
// it's probably ok to take the mutex on the 3rd try so we can succeed for
|
||||
// sure.
|
||||
constexpr int num_retries = 3;
|
||||
for (int i = 0; i < num_retries; ++i) {
|
||||
last_try = (i == num_retries - 1);
|
||||
bool retry = false;
|
||||
|
||||
if (i > 0) {
|
||||
for (auto cf_iter = cf_list->begin(); cf_iter != cf_list->end();
|
||||
++cf_iter) {
|
||||
auto node = iter_deref_func(cf_iter);
|
||||
SuperVersion* super_version = node->super_version;
|
||||
ColumnFamilyData* cfd = node->cfd;
|
||||
if (super_version != nullptr) {
|
||||
ReturnAndCleanupSuperVersion(cfd, super_version);
|
||||
}
|
||||
node->super_version = nullptr;
|
||||
}
|
||||
sv_cleanup_func();
|
||||
}
|
||||
if (read_options.snapshot == nullptr) {
|
||||
if (last_try) {
|
||||
@@ -2623,6 +2658,19 @@ bool DBImpl::MultiCFSnapshot(
|
||||
node->super_version = node->cfd->GetSuperVersion()->Ref();
|
||||
}
|
||||
TEST_SYNC_POINT("DBImpl::MultiGet::AfterRefSV");
|
||||
if (check_read_ts) {
|
||||
s = FailIfReadCollapsedHistory(node->cfd, node->super_version,
|
||||
*(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
// If read timestamp check failed, a.k.a ReadOptions.timestamp <
|
||||
// super_version.full_history_ts_low. There is no need to continue
|
||||
// because this check will keep failing for the same and newer
|
||||
// SuperVersions, instead we fail fast and ask user to provide
|
||||
// a higher read timestamp.
|
||||
retry = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (read_options.snapshot != nullptr || last_try) {
|
||||
// If user passed a snapshot, then we don't care if a memtable is
|
||||
// sealed or compaction happens because the snapshot would ensure
|
||||
@@ -2646,6 +2694,7 @@ bool DBImpl::MultiCFSnapshot(
|
||||
if (!retry) {
|
||||
if (last_try) {
|
||||
mutex_.Unlock();
|
||||
TEST_SYNC_POINT("DBImpl::MultiGet::AfterLastTryRefSV");
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -2654,8 +2703,11 @@ bool DBImpl::MultiCFSnapshot(
|
||||
|
||||
// Keep track of bytes that we read for statistics-recording later
|
||||
PERF_TIMER_STOP(get_snapshot_time);
|
||||
|
||||
return last_try;
|
||||
*sv_from_thread_local = !last_try;
|
||||
if (!s.ok()) {
|
||||
sv_cleanup_func();
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
void DBImpl::MultiGet(const ReadOptions& read_options, const size_t num_keys,
|
||||
@@ -2705,8 +2757,7 @@ void DBImpl::MultiGetCommon(const ReadOptions& read_options,
|
||||
ColumnFamilyHandle* cfh = column_families[i];
|
||||
assert(cfh);
|
||||
if (read_options.timestamp) {
|
||||
statuses[i] = FailIfTsMismatchCf(cfh, *(read_options.timestamp),
|
||||
/*ts_for_read=*/true);
|
||||
statuses[i] = FailIfTsMismatchCf(cfh, *(read_options.timestamp));
|
||||
if (!statuses[i].ok()) {
|
||||
should_fail = true;
|
||||
}
|
||||
@@ -2789,10 +2840,20 @@ void DBImpl::MultiGetCommon(const ReadOptions& read_options,
|
||||
};
|
||||
|
||||
SequenceNumber consistent_seqnum;
|
||||
bool unref_only = MultiCFSnapshot<
|
||||
bool sv_from_thread_local;
|
||||
Status s = MultiCFSnapshot<
|
||||
autovector<MultiGetColumnFamilyData, MultiGetContext::MAX_BATCH_SIZE>>(
|
||||
read_options, nullptr, iter_deref_lambda, &multiget_cf_data,
|
||||
&consistent_seqnum);
|
||||
&consistent_seqnum, &sv_from_thread_local);
|
||||
|
||||
if (!s.ok()) {
|
||||
for (size_t i = 0; i < num_keys; ++i) {
|
||||
if (statuses[i].ok()) {
|
||||
statuses[i] = s;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
GetWithTimestampReadCallback timestamp_read_callback(0);
|
||||
ReadCallback* read_callback = nullptr;
|
||||
@@ -2801,7 +2862,6 @@ void DBImpl::MultiGetCommon(const ReadOptions& read_options,
|
||||
read_callback = ×tamp_read_callback;
|
||||
}
|
||||
|
||||
Status s;
|
||||
auto cf_iter = multiget_cf_data.begin();
|
||||
for (; cf_iter != multiget_cf_data.end(); ++cf_iter) {
|
||||
s = MultiGetImpl(read_options, cf_iter->start, cf_iter->num_keys,
|
||||
@@ -2822,10 +2882,11 @@ void DBImpl::MultiGetCommon(const ReadOptions& read_options,
|
||||
}
|
||||
|
||||
for (const auto& iter : multiget_cf_data) {
|
||||
if (!unref_only) {
|
||||
if (sv_from_thread_local) {
|
||||
ReturnAndCleanupSuperVersion(iter.cfd, iter.super_version);
|
||||
} else {
|
||||
iter.cfd->GetSuperVersion()->Unref();
|
||||
TEST_SYNC_POINT("DBImpl::MultiGet::BeforeLastTryUnRefSV");
|
||||
CleanupSuperVersion(iter.super_version);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2948,7 +3009,7 @@ void DBImpl::MultiGetCommon(const ReadOptions& read_options,
|
||||
sorted_keys[i] = &key_context[i];
|
||||
}
|
||||
PrepareMultiGetKeys(num_keys, sorted_input, &sorted_keys);
|
||||
MultiGetWithCallback(read_options, column_family, nullptr, &sorted_keys);
|
||||
MultiGetWithCallbackImpl(read_options, column_family, nullptr, &sorted_keys);
|
||||
}
|
||||
|
||||
void DBImpl::MultiGetWithCallback(
|
||||
@@ -2965,7 +3026,13 @@ void DBImpl::MultiGetWithCallback(
|
||||
if (read_options.io_activity == Env::IOActivity::kUnknown) {
|
||||
read_options.io_activity = Env::IOActivity::kMultiGet;
|
||||
}
|
||||
MultiGetWithCallbackImpl(read_options, column_family, callback, sorted_keys);
|
||||
}
|
||||
|
||||
void DBImpl::MultiGetWithCallbackImpl(
|
||||
const ReadOptions& read_options, ColumnFamilyHandle* column_family,
|
||||
ReadCallback* callback,
|
||||
autovector<KeyContext*, MultiGetContext::MAX_BATCH_SIZE>* sorted_keys) {
|
||||
std::array<MultiGetColumnFamilyData, 1> multiget_cf_data;
|
||||
multiget_cf_data[0] = MultiGetColumnFamilyData(column_family, nullptr);
|
||||
std::function<MultiGetColumnFamilyData*(
|
||||
@@ -2977,14 +3044,18 @@ void DBImpl::MultiGetWithCallback(
|
||||
|
||||
size_t num_keys = sorted_keys->size();
|
||||
SequenceNumber consistent_seqnum;
|
||||
bool unref_only = MultiCFSnapshot<std::array<MultiGetColumnFamilyData, 1>>(
|
||||
bool sv_from_thread_local;
|
||||
Status s = MultiCFSnapshot<std::array<MultiGetColumnFamilyData, 1>>(
|
||||
read_options, callback, iter_deref_lambda, &multiget_cf_data,
|
||||
&consistent_seqnum);
|
||||
&consistent_seqnum, &sv_from_thread_local);
|
||||
if (!s.ok()) {
|
||||
return;
|
||||
}
|
||||
#ifndef NDEBUG
|
||||
assert(!unref_only);
|
||||
assert(sv_from_thread_local);
|
||||
#else
|
||||
// Silence unused variable warning
|
||||
(void)unref_only;
|
||||
(void)sv_from_thread_local;
|
||||
#endif // NDEBUG
|
||||
|
||||
if (callback && read_options.snapshot == nullptr) {
|
||||
@@ -3014,9 +3085,9 @@ void DBImpl::MultiGetWithCallback(
|
||||
read_callback = ×tamp_read_callback;
|
||||
}
|
||||
|
||||
Status s = MultiGetImpl(read_options, 0, num_keys, sorted_keys,
|
||||
multiget_cf_data[0].super_version, consistent_seqnum,
|
||||
read_callback);
|
||||
s = MultiGetImpl(read_options, 0, num_keys, sorted_keys,
|
||||
multiget_cf_data[0].super_version, consistent_seqnum,
|
||||
read_callback);
|
||||
assert(s.ok() || s.IsTimedOut() || s.IsAborted());
|
||||
ReturnAndCleanupSuperVersion(multiget_cf_data[0].cfd,
|
||||
multiget_cf_data[0].super_version);
|
||||
@@ -3072,7 +3143,7 @@ Status DBImpl::MultiGetImpl(
|
||||
stats_);
|
||||
MultiGetRange range = ctx.GetMultiGetRange();
|
||||
range.AddValueSize(curr_value_size);
|
||||
bool lookup_current = false;
|
||||
bool lookup_current = true;
|
||||
|
||||
keys_left -= batch_size;
|
||||
for (auto mget_iter = range.begin(); mget_iter != range.end();
|
||||
@@ -3091,9 +3162,10 @@ Status DBImpl::MultiGetImpl(
|
||||
super_version->imm->MultiGet(read_options, &range, callback);
|
||||
}
|
||||
if (!range.empty()) {
|
||||
lookup_current = true;
|
||||
uint64_t left = range.KeysLeft();
|
||||
RecordTick(stats_, MEMTABLE_MISS, left);
|
||||
} else {
|
||||
lookup_current = false;
|
||||
}
|
||||
}
|
||||
if (lookup_current) {
|
||||
@@ -3117,6 +3189,12 @@ Status DBImpl::MultiGetImpl(
|
||||
assert(key->s);
|
||||
|
||||
if (key->s->ok()) {
|
||||
const auto& merge_threshold = read_options.merge_operand_count_threshold;
|
||||
if (merge_threshold.has_value() &&
|
||||
key->merge_context.GetNumOperands() > merge_threshold) {
|
||||
*(key->s) = Status::OkMergeOperandThresholdExceeded();
|
||||
}
|
||||
|
||||
if (key->value) {
|
||||
bytes_read += key->value->size();
|
||||
} else {
|
||||
@@ -3147,20 +3225,54 @@ Status DBImpl::MultiGetImpl(
|
||||
return s;
|
||||
}
|
||||
|
||||
void DBImpl::MultiGetEntity(const ReadOptions& options, size_t num_keys,
|
||||
void DBImpl::MultiGetEntity(const ReadOptions& _read_options, size_t num_keys,
|
||||
ColumnFamilyHandle** column_families,
|
||||
const Slice* keys, PinnableWideColumns* results,
|
||||
Status* statuses, bool sorted_input) {
|
||||
MultiGetCommon(options, num_keys, column_families, keys, /* values */ nullptr,
|
||||
results, /* timestamps */ nullptr, statuses, sorted_input);
|
||||
if (_read_options.io_activity != Env::IOActivity::kUnknown &&
|
||||
_read_options.io_activity != Env::IOActivity::kMultiGetEntity) {
|
||||
Status s = Status::InvalidArgument(
|
||||
"Can only call MultiGetEntity with `ReadOptions::io_activity` is "
|
||||
"`Env::IOActivity::kUnknown` or `Env::IOActivity::kMultiGetEntity`");
|
||||
for (size_t i = 0; i < num_keys; ++i) {
|
||||
if (statuses[i].ok()) {
|
||||
statuses[i] = s;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
ReadOptions read_options(_read_options);
|
||||
if (read_options.io_activity == Env::IOActivity::kUnknown) {
|
||||
read_options.io_activity = Env::IOActivity::kMultiGetEntity;
|
||||
}
|
||||
MultiGetCommon(read_options, num_keys, column_families, keys,
|
||||
/* values */ nullptr, results, /* timestamps */ nullptr,
|
||||
statuses, sorted_input);
|
||||
}
|
||||
|
||||
void DBImpl::MultiGetEntity(const ReadOptions& options,
|
||||
void DBImpl::MultiGetEntity(const ReadOptions& _read_options,
|
||||
ColumnFamilyHandle* column_family, size_t num_keys,
|
||||
const Slice* keys, PinnableWideColumns* results,
|
||||
Status* statuses, bool sorted_input) {
|
||||
MultiGetCommon(options, column_family, num_keys, keys, /* values */ nullptr,
|
||||
results, /* timestamps */ nullptr, statuses, sorted_input);
|
||||
if (_read_options.io_activity != Env::IOActivity::kUnknown &&
|
||||
_read_options.io_activity != Env::IOActivity::kMultiGetEntity) {
|
||||
Status s = Status::InvalidArgument(
|
||||
"Can only call MultiGetEntity with `ReadOptions::io_activity` is "
|
||||
"`Env::IOActivity::kUnknown` or `Env::IOActivity::kMultiGetEntity`");
|
||||
for (size_t i = 0; i < num_keys; ++i) {
|
||||
if (statuses[i].ok()) {
|
||||
statuses[i] = s;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
ReadOptions read_options(_read_options);
|
||||
if (read_options.io_activity == Env::IOActivity::kUnknown) {
|
||||
read_options.io_activity = Env::IOActivity::kMultiGetEntity;
|
||||
}
|
||||
MultiGetCommon(read_options, column_family, num_keys, keys,
|
||||
/* values */ nullptr, results, /* timestamps */ nullptr,
|
||||
statuses, sorted_input);
|
||||
}
|
||||
|
||||
Status DBImpl::CreateColumnFamily(const ColumnFamilyOptions& cf_options,
|
||||
@@ -3486,8 +3598,7 @@ Iterator* DBImpl::NewIterator(const ReadOptions& _read_options,
|
||||
|
||||
if (read_options.timestamp) {
|
||||
const Status s =
|
||||
FailIfTsMismatchCf(column_family, *(read_options.timestamp),
|
||||
/*ts_for_read=*/true);
|
||||
FailIfTsMismatchCf(column_family, *(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
return NewErrorIterator(s);
|
||||
}
|
||||
@@ -3502,8 +3613,16 @@ Iterator* DBImpl::NewIterator(const ReadOptions& _read_options,
|
||||
ColumnFamilyData* cfd = cfh->cfd();
|
||||
assert(cfd != nullptr);
|
||||
ReadCallback* read_callback = nullptr; // No read callback provided.
|
||||
SuperVersion* sv = cfd->GetReferencedSuperVersion(this);
|
||||
if (read_options.timestamp && read_options.timestamp->size() > 0) {
|
||||
const Status s =
|
||||
FailIfReadCollapsedHistory(cfd, sv, *(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
CleanupSuperVersion(sv);
|
||||
return NewErrorIterator(s);
|
||||
}
|
||||
}
|
||||
if (read_options.tailing) {
|
||||
SuperVersion* sv = cfd->GetReferencedSuperVersion(this);
|
||||
auto iter = new ForwardIterator(this, read_options, cfd, sv,
|
||||
/* allow_unprepared_value */ true);
|
||||
result = NewDBIterator(
|
||||
@@ -3515,7 +3634,7 @@ Iterator* DBImpl::NewIterator(const ReadOptions& _read_options,
|
||||
// Note: no need to consider the special case of
|
||||
// last_seq_same_as_publish_seq_==false since NewIterator is overridden in
|
||||
// WritePreparedTxnDB
|
||||
result = NewIteratorImpl(read_options, cfd,
|
||||
result = NewIteratorImpl(read_options, cfd, sv,
|
||||
(read_options.snapshot != nullptr)
|
||||
? read_options.snapshot->GetSequenceNumber()
|
||||
: kMaxSequenceNumber,
|
||||
@@ -3524,14 +3643,10 @@ Iterator* DBImpl::NewIterator(const ReadOptions& _read_options,
|
||||
return result;
|
||||
}
|
||||
|
||||
ArenaWrappedDBIter* DBImpl::NewIteratorImpl(const ReadOptions& read_options,
|
||||
ColumnFamilyData* cfd,
|
||||
SequenceNumber snapshot,
|
||||
ReadCallback* read_callback,
|
||||
bool expose_blob_index,
|
||||
bool allow_refresh) {
|
||||
SuperVersion* sv = cfd->GetReferencedSuperVersion(this);
|
||||
|
||||
ArenaWrappedDBIter* DBImpl::NewIteratorImpl(
|
||||
const ReadOptions& read_options, ColumnFamilyData* cfd, SuperVersion* sv,
|
||||
SequenceNumber snapshot, ReadCallback* read_callback,
|
||||
bool expose_blob_index, bool allow_refresh) {
|
||||
TEST_SYNC_POINT("DBImpl::NewIterator:1");
|
||||
TEST_SYNC_POINT("DBImpl::NewIterator:2");
|
||||
|
||||
@@ -3596,7 +3711,7 @@ ArenaWrappedDBIter* DBImpl::NewIteratorImpl(const ReadOptions& read_options,
|
||||
env_, read_options, *cfd->ioptions(), sv->mutable_cf_options, sv->current,
|
||||
snapshot, sv->mutable_cf_options.max_sequential_skip_in_iterations,
|
||||
sv->version_number, read_callback, this, cfd, expose_blob_index,
|
||||
read_options.snapshot != nullptr ? false : allow_refresh);
|
||||
allow_refresh);
|
||||
|
||||
InternalIterator* internal_iter = NewInternalIterator(
|
||||
db_iter->GetReadOptions(), cfd, sv, db_iter->GetArena(), snapshot,
|
||||
@@ -3631,8 +3746,7 @@ Status DBImpl::NewIterators(
|
||||
if (read_options.timestamp) {
|
||||
for (auto* cf : column_families) {
|
||||
assert(cf);
|
||||
const Status s = FailIfTsMismatchCf(cf, *(read_options.timestamp),
|
||||
/*ts_for_read=*/true);
|
||||
const Status s = FailIfTsMismatchCf(cf, *(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
@@ -3650,10 +3764,27 @@ Status DBImpl::NewIterators(
|
||||
ReadCallback* read_callback = nullptr; // No read callback provided.
|
||||
iterators->clear();
|
||||
iterators->reserve(column_families.size());
|
||||
autovector<std::tuple<ColumnFamilyData*, SuperVersion*>> cfd_to_sv;
|
||||
const bool check_read_ts =
|
||||
read_options.timestamp && read_options.timestamp->size() > 0;
|
||||
for (auto cfh : column_families) {
|
||||
auto cfd = static_cast_with_check<ColumnFamilyHandleImpl>(cfh)->cfd();
|
||||
SuperVersion* sv = cfd->GetReferencedSuperVersion(this);
|
||||
cfd_to_sv.emplace_back(cfd, sv);
|
||||
if (check_read_ts) {
|
||||
const Status s =
|
||||
FailIfReadCollapsedHistory(cfd, sv, *(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
for (auto prev_entry : cfd_to_sv) {
|
||||
CleanupSuperVersion(std::get<1>(prev_entry));
|
||||
}
|
||||
return s;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert(cfd_to_sv.size() == column_families.size());
|
||||
if (read_options.tailing) {
|
||||
for (auto cfh : column_families) {
|
||||
auto cfd = static_cast_with_check<ColumnFamilyHandleImpl>(cfh)->cfd();
|
||||
SuperVersion* sv = cfd->GetReferencedSuperVersion(this);
|
||||
for (auto [cfd, sv] : cfd_to_sv) {
|
||||
auto iter = new ForwardIterator(this, read_options, cfd, sv,
|
||||
/* allow_unprepared_value */ true);
|
||||
iterators->push_back(NewDBIterator(
|
||||
@@ -3669,12 +3800,9 @@ Status DBImpl::NewIterators(
|
||||
auto snapshot = read_options.snapshot != nullptr
|
||||
? read_options.snapshot->GetSequenceNumber()
|
||||
: versions_->LastSequence();
|
||||
for (size_t i = 0; i < column_families.size(); ++i) {
|
||||
auto* cfd =
|
||||
static_cast_with_check<ColumnFamilyHandleImpl>(column_families[i])
|
||||
->cfd();
|
||||
for (auto [cfd, sv] : cfd_to_sv) {
|
||||
iterators->push_back(
|
||||
NewIteratorImpl(read_options, cfd, snapshot, read_callback));
|
||||
NewIteratorImpl(read_options, cfd, sv, snapshot, read_callback));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3902,7 +4030,8 @@ void DBImpl::ReleaseSnapshot(const Snapshot* s) {
|
||||
CfdList cf_scheduled;
|
||||
for (auto* cfd : *versions_->GetColumnFamilySet()) {
|
||||
if (!cfd->ioptions()->allow_ingest_behind) {
|
||||
cfd->current()->storage_info()->UpdateOldestSnapshot(oldest_snapshot);
|
||||
cfd->current()->storage_info()->UpdateOldestSnapshot(
|
||||
oldest_snapshot, /*allow_ingest_behind=*/false);
|
||||
if (!cfd->current()
|
||||
->storage_info()
|
||||
->BottommostFilesMarkedForCompaction()
|
||||
@@ -3980,7 +4109,6 @@ Status DBImpl::GetPropertiesOfTablesInRange(ColumnFamilyHandle* column_family,
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
const std::string& DBImpl::GetName() const { return dbname_; }
|
||||
|
||||
Env* DBImpl::GetEnv() const { return env_; }
|
||||
@@ -3998,7 +4126,6 @@ SystemClock* DBImpl::GetSystemClock() const {
|
||||
return immutable_db_options_.clock;
|
||||
}
|
||||
|
||||
|
||||
Status DBImpl::StartIOTrace(const TraceOptions& trace_options,
|
||||
std::unique_ptr<TraceWriter>&& trace_writer) {
|
||||
assert(trace_writer != nullptr);
|
||||
@@ -4011,7 +4138,6 @@ Status DBImpl::EndIOTrace() {
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
Options DBImpl::GetOptions(ColumnFamilyHandle* column_family) const {
|
||||
InstrumentedMutexLock l(&mutex_);
|
||||
auto cfh = static_cast_with_check<ColumnFamilyHandleImpl>(column_family);
|
||||
@@ -4280,10 +4406,12 @@ void DBImpl::GetApproximateMemTableStats(ColumnFamilyHandle* column_family,
|
||||
// Add timestamp if needed
|
||||
std::string start_with_ts, limit_with_ts;
|
||||
auto [start, limit] = MaybeAddTimestampsToRange(
|
||||
range.start, range.limit, ts_sz, &start_with_ts, &limit_with_ts);
|
||||
&range.start, &range.limit, ts_sz, &start_with_ts, &limit_with_ts);
|
||||
assert(start.has_value());
|
||||
assert(limit.has_value());
|
||||
// Convert user_key into a corresponding internal key.
|
||||
InternalKey k1(start, kMaxSequenceNumber, kValueTypeForSeek);
|
||||
InternalKey k2(limit, kMaxSequenceNumber, kValueTypeForSeek);
|
||||
InternalKey k1(start.value(), kMaxSequenceNumber, kValueTypeForSeek);
|
||||
InternalKey k2(limit.value(), kMaxSequenceNumber, kValueTypeForSeek);
|
||||
MemTable::MemTableStats memStats =
|
||||
sv->mem->ApproximateStats(k1.Encode(), k2.Encode());
|
||||
MemTable::MemTableStats immStats =
|
||||
@@ -4316,11 +4444,14 @@ Status DBImpl::GetApproximateSizes(const SizeApproximationOptions& options,
|
||||
for (int i = 0; i < n; i++) {
|
||||
// Add timestamp if needed
|
||||
std::string start_with_ts, limit_with_ts;
|
||||
auto [start, limit] = MaybeAddTimestampsToRange(
|
||||
range[i].start, range[i].limit, ts_sz, &start_with_ts, &limit_with_ts);
|
||||
auto [start, limit] =
|
||||
MaybeAddTimestampsToRange(&range[i].start, &range[i].limit, ts_sz,
|
||||
&start_with_ts, &limit_with_ts);
|
||||
assert(start.has_value());
|
||||
assert(limit.has_value());
|
||||
// Convert user_key into a corresponding internal key.
|
||||
InternalKey k1(start, kMaxSequenceNumber, kValueTypeForSeek);
|
||||
InternalKey k2(limit, kMaxSequenceNumber, kValueTypeForSeek);
|
||||
InternalKey k1(start.value(), kMaxSequenceNumber, kValueTypeForSeek);
|
||||
InternalKey k2(limit.value(), kMaxSequenceNumber, kValueTypeForSeek);
|
||||
sizes[i] = 0;
|
||||
if (options.include_files) {
|
||||
sizes[i] += versions_->ApproximateSize(
|
||||
@@ -5853,7 +5984,7 @@ Status DBImpl::ClipColumnFamily(ColumnFamilyHandle* column_family,
|
||||
|
||||
if (status.ok()) {
|
||||
// Delete [clip_end_key, largest_use_key]
|
||||
if (ucmp->Compare(end_key, largest_user_key) < 0) {
|
||||
if (ucmp->Compare(end_key, largest_user_key) <= 0) {
|
||||
status = DeleteRange(wo, column_family, end_key, largest_user_key);
|
||||
if (status.ok()) {
|
||||
status = Delete(wo, column_family, largest_user_key);
|
||||
@@ -6043,7 +6174,8 @@ Status DBImpl::VerifyFullFileChecksum(const std::string& file_checksum_expected,
|
||||
fs_.get(), fname, immutable_db_options_.file_checksum_gen_factory.get(),
|
||||
func_name_expected, &file_checksum, &func_name,
|
||||
read_options.readahead_size, immutable_db_options_.allow_mmap_reads,
|
||||
io_tracer_, immutable_db_options_.rate_limiter.get(), read_options);
|
||||
io_tracer_, immutable_db_options_.rate_limiter.get(), read_options,
|
||||
immutable_db_options_.stats, immutable_db_options_.clock);
|
||||
if (s.ok()) {
|
||||
assert(func_name_expected == func_name);
|
||||
if (file_checksum != file_checksum_expected) {
|
||||
|
||||
+60
-31
@@ -643,12 +643,12 @@ class DBImpl : public DB {
|
||||
// get_impl_options.key via get_impl_options.value
|
||||
// If get_impl_options.get_value = false get merge operands associated with
|
||||
// get_impl_options.key via get_impl_options.merge_operands
|
||||
Status GetImpl(const ReadOptions& options, const Slice& key,
|
||||
GetImplOptions& get_impl_options);
|
||||
virtual Status GetImpl(const ReadOptions& options, const Slice& key,
|
||||
GetImplOptions& get_impl_options);
|
||||
|
||||
// If `snapshot` == kMaxSequenceNumber, set a recent one inside the file.
|
||||
ArenaWrappedDBIter* NewIteratorImpl(const ReadOptions& options,
|
||||
ColumnFamilyData* cfd,
|
||||
ColumnFamilyData* cfd, SuperVersion* sv,
|
||||
SequenceNumber snapshot,
|
||||
ReadCallback* read_callback,
|
||||
bool expose_blob_index = false,
|
||||
@@ -1383,8 +1383,10 @@ class DBImpl : public DB {
|
||||
autovector<ColumnFamilyData*> cfds_;
|
||||
autovector<const MutableCFOptions*> mutable_cf_opts_;
|
||||
autovector<autovector<VersionEdit*>> edit_lists_;
|
||||
// files_to_delete_ contains sst files
|
||||
std::unordered_set<std::string> files_to_delete_;
|
||||
// Stale SST files to delete found upon recovery. This stores a mapping from
|
||||
// such a file's absolute path to its parent directory.
|
||||
std::unordered_map<std::string, std::string> files_to_delete_;
|
||||
bool is_new_db_ = false;
|
||||
};
|
||||
|
||||
// Except in DB::Open(), WriteOptionsFile can only be called when:
|
||||
@@ -1543,8 +1545,18 @@ class DBImpl : public DB {
|
||||
void SetDbSessionId();
|
||||
|
||||
Status FailIfCfHasTs(const ColumnFamilyHandle* column_family) const;
|
||||
Status FailIfTsMismatchCf(ColumnFamilyHandle* column_family, const Slice& ts,
|
||||
bool ts_for_read) const;
|
||||
Status FailIfTsMismatchCf(ColumnFamilyHandle* column_family,
|
||||
const Slice& ts) const;
|
||||
|
||||
// Check that the read timestamp `ts` is at or above the `full_history_ts_low`
|
||||
// timestamp in a `SuperVersion`. It's necessary to do this check after
|
||||
// grabbing the SuperVersion. If the check passed, the referenced SuperVersion
|
||||
// this read holds on to can ensure the read won't be affected if
|
||||
// `full_history_ts_low` is increased concurrently, and this achieves that
|
||||
// without explicitly locking by piggybacking the SuperVersion.
|
||||
Status FailIfReadCollapsedHistory(const ColumnFamilyData* cfd,
|
||||
const SuperVersion* sv,
|
||||
const Slice& ts) const;
|
||||
|
||||
// recovery_ctx stores the context about version edits and
|
||||
// LogAndApplyForRecovery persist all those edits to new Manifest after
|
||||
@@ -1842,7 +1854,8 @@ class DBImpl : public DB {
|
||||
void ReleaseFileNumberFromPendingOutputs(
|
||||
std::unique_ptr<std::list<uint64_t>::iterator>& v);
|
||||
|
||||
IOStatus SyncClosedLogs(JobContext* job_context, VersionEdit* synced_wals);
|
||||
IOStatus SyncClosedLogs(JobContext* job_context, VersionEdit* synced_wals,
|
||||
bool error_recovery_in_prog);
|
||||
|
||||
// Flush the in-memory write buffer to storage. Switches to a new
|
||||
// log-file/memtable and writes a new descriptor iff successful. Then
|
||||
@@ -2312,15 +2325,18 @@ class DBImpl : public DB {
|
||||
// If callback is non-null, the callback is refreshed with the snapshot
|
||||
// sequence number
|
||||
//
|
||||
// A return value of true indicates that the SuperVersions were obtained
|
||||
// from the ColumnFamilyData, whereas false indicates they are thread
|
||||
// local
|
||||
// `sv_from_thread_local` being set to false indicates that the SuperVersion
|
||||
// obtained from the ColumnFamilyData, whereas true indicates they are thread
|
||||
// local.
|
||||
// A non-OK status will be returned if for a column family that enables
|
||||
// user-defined timestamp feature, the specified `ReadOptions.timestamp`
|
||||
// attemps to read collapsed history.
|
||||
template <class T>
|
||||
bool MultiCFSnapshot(
|
||||
Status MultiCFSnapshot(
|
||||
const ReadOptions& read_options, ReadCallback* callback,
|
||||
std::function<MultiGetColumnFamilyData*(typename T::iterator&)>&
|
||||
iter_deref_func,
|
||||
T* cf_list, SequenceNumber* snapshot);
|
||||
T* cf_list, SequenceNumber* snapshot, bool* sv_from_thread_local);
|
||||
|
||||
// The actual implementation of the batching MultiGet. The caller is expected
|
||||
// to have acquired the SuperVersion and pass in a snapshot sequence number
|
||||
@@ -2331,8 +2347,17 @@ class DBImpl : public DB {
|
||||
autovector<KeyContext*, MultiGetContext::MAX_BATCH_SIZE>* sorted_keys,
|
||||
SuperVersion* sv, SequenceNumber snap_seqnum, ReadCallback* callback);
|
||||
|
||||
void MultiGetWithCallbackImpl(
|
||||
const ReadOptions& read_options, ColumnFamilyHandle* column_family,
|
||||
ReadCallback* callback,
|
||||
autovector<KeyContext*, MultiGetContext::MAX_BATCH_SIZE>* sorted_keys);
|
||||
|
||||
Status DisableFileDeletionsWithLock();
|
||||
|
||||
// Safely decrease `disable_delete_obsolete_files_` by one while holding lock
|
||||
// and return its remaning value.
|
||||
int EnableFileDeletionsWithLock();
|
||||
|
||||
Status IncreaseFullHistoryTsLowImpl(ColumnFamilyData* cfd,
|
||||
std::string ts_low);
|
||||
|
||||
@@ -2620,9 +2645,6 @@ class DBImpl : public DB {
|
||||
// initialized with startup time.
|
||||
uint64_t delete_obsolete_files_last_run_;
|
||||
|
||||
// last time stats were dumped to LOG
|
||||
std::atomic<uint64_t> last_stats_dump_time_microsec_;
|
||||
|
||||
// The thread that wants to switch memtable, can wait on this cv until the
|
||||
// pending writes to memtable finishes.
|
||||
std::condition_variable switch_cv_;
|
||||
@@ -2829,8 +2851,7 @@ inline Status DBImpl::FailIfCfHasTs(
|
||||
}
|
||||
|
||||
inline Status DBImpl::FailIfTsMismatchCf(ColumnFamilyHandle* column_family,
|
||||
const Slice& ts,
|
||||
bool ts_for_read) const {
|
||||
const Slice& ts) const {
|
||||
if (!column_family) {
|
||||
return Status::InvalidArgument("column family handle cannot be null");
|
||||
}
|
||||
@@ -2850,20 +2871,28 @@ inline Status DBImpl::FailIfTsMismatchCf(ColumnFamilyHandle* column_family,
|
||||
<< ts_sz << " given";
|
||||
return Status::InvalidArgument(oss.str());
|
||||
}
|
||||
if (ts_for_read) {
|
||||
auto cfh = static_cast_with_check<ColumnFamilyHandleImpl>(column_family);
|
||||
auto cfd = cfh->cfd();
|
||||
std::string current_ts_low = cfd->GetFullHistoryTsLow();
|
||||
if (!current_ts_low.empty() &&
|
||||
ucmp->CompareTimestamp(ts, current_ts_low) < 0) {
|
||||
std::stringstream oss;
|
||||
oss << "Read timestamp: " << ts.ToString(true)
|
||||
<< " is smaller than full_history_ts_low: "
|
||||
<< Slice(current_ts_low).ToString(true) << std::endl;
|
||||
return Status::InvalidArgument(oss.str());
|
||||
}
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
inline Status DBImpl::FailIfReadCollapsedHistory(const ColumnFamilyData* cfd,
|
||||
const SuperVersion* sv,
|
||||
const Slice& ts) const {
|
||||
// Reaching to this point means the timestamp size matching sanity check in
|
||||
// `DBImpl::FailIfTsMismatchCf` already passed. So we skip that and assume
|
||||
// column family has the same user-defined timestamp format as `ts`.
|
||||
const Comparator* const ucmp = cfd->user_comparator();
|
||||
assert(ucmp);
|
||||
const std::string& full_history_ts_low = sv->full_history_ts_low;
|
||||
assert(full_history_ts_low.empty() ||
|
||||
full_history_ts_low.size() == ts.size());
|
||||
if (!full_history_ts_low.empty() &&
|
||||
ucmp->CompareTimestamp(ts, full_history_ts_low) < 0) {
|
||||
std::stringstream oss;
|
||||
oss << "Read timestamp: " << ts.ToString(true)
|
||||
<< " is smaller than full_history_ts_low: "
|
||||
<< Slice(full_history_ts_low).ToString(true) << std::endl;
|
||||
return Status::InvalidArgument(oss.str());
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
} // namespace ROCKSDB_NAMESPACE
|
||||
@@ -23,6 +23,7 @@
|
||||
#include "util/cast_util.h"
|
||||
#include "util/coding.h"
|
||||
#include "util/concurrent_task_limiter_impl.h"
|
||||
#include "util/udt_util.h"
|
||||
|
||||
namespace ROCKSDB_NAMESPACE {
|
||||
|
||||
@@ -112,7 +113,8 @@ bool DBImpl::ShouldRescheduleFlushRequestToRetainUDT(
|
||||
}
|
||||
|
||||
IOStatus DBImpl::SyncClosedLogs(JobContext* job_context,
|
||||
VersionEdit* synced_wals) {
|
||||
VersionEdit* synced_wals,
|
||||
bool error_recovery_in_prog) {
|
||||
TEST_SYNC_POINT("DBImpl::SyncClosedLogs:Start");
|
||||
InstrumentedMutexLock l(&log_write_mutex_);
|
||||
autovector<log::Writer*, 1> logs_to_sync;
|
||||
@@ -138,7 +140,7 @@ IOStatus DBImpl::SyncClosedLogs(JobContext* job_context,
|
||||
ROCKS_LOG_INFO(immutable_db_options_.info_log,
|
||||
"[JOB %d] Syncing log #%" PRIu64, job_context->job_id,
|
||||
log->get_log_number());
|
||||
if (error_handler_.IsRecoveryInProgress()) {
|
||||
if (error_recovery_in_prog) {
|
||||
log->file()->reset_seen_error();
|
||||
}
|
||||
io_s = log->file()->Sync(immutable_db_options_.use_fsync);
|
||||
@@ -147,7 +149,7 @@ IOStatus DBImpl::SyncClosedLogs(JobContext* job_context,
|
||||
}
|
||||
|
||||
if (immutable_db_options_.recycle_log_file_num > 0) {
|
||||
if (error_handler_.IsRecoveryInProgress()) {
|
||||
if (error_recovery_in_prog) {
|
||||
log->file()->reset_seen_error();
|
||||
}
|
||||
io_s = log->Close();
|
||||
@@ -260,8 +262,10 @@ Status DBImpl::FlushMemTableToOutputFile(
|
||||
// SyncClosedLogs() may unlock and re-lock the log_write_mutex multiple
|
||||
// times.
|
||||
VersionEdit synced_wals;
|
||||
bool error_recovery_in_prog = error_handler_.IsRecoveryInProgress();
|
||||
mutex_.Unlock();
|
||||
log_io_s = SyncClosedLogs(job_context, &synced_wals);
|
||||
log_io_s =
|
||||
SyncClosedLogs(job_context, &synced_wals, error_recovery_in_prog);
|
||||
mutex_.Lock();
|
||||
if (log_io_s.ok() && synced_wals.IsWalAddition()) {
|
||||
const ReadOptions read_options(Env::IOActivity::kFlush);
|
||||
@@ -283,6 +287,24 @@ Status DBImpl::FlushMemTableToOutputFile(
|
||||
// If the log sync failed, we do not need to pick memtable. Otherwise,
|
||||
// num_flush_not_started_ needs to be rollback.
|
||||
TEST_SYNC_POINT("DBImpl::FlushMemTableToOutputFile:BeforePickMemtables");
|
||||
// Exit a flush due to bg error should not set bg error again.
|
||||
bool skip_set_bg_error = false;
|
||||
if (s.ok() && !error_handler_.GetBGError().ok() &&
|
||||
error_handler_.IsBGWorkStopped() &&
|
||||
flush_reason != FlushReason::kErrorRecovery &&
|
||||
flush_reason != FlushReason::kErrorRecoveryRetryFlush) {
|
||||
// Error recovery in progress, should not pick memtable which excludes
|
||||
// them from being picked up by recovery flush.
|
||||
// This ensures that when bg error is set, no new flush can pick
|
||||
// memtables.
|
||||
skip_set_bg_error = true;
|
||||
s = error_handler_.GetBGError();
|
||||
assert(!s.ok());
|
||||
ROCKS_LOG_BUFFER(log_buffer,
|
||||
"[JOB %d] Skip flush due to background error %s",
|
||||
job_context->job_id, s.ToString().c_str());
|
||||
}
|
||||
|
||||
if (s.ok()) {
|
||||
flush_job.PickMemTable();
|
||||
need_cancel = true;
|
||||
@@ -303,7 +325,8 @@ Status DBImpl::FlushMemTableToOutputFile(
|
||||
// is unlocked by the current thread.
|
||||
if (s.ok()) {
|
||||
s = flush_job.Run(&logs_with_prep_tracker_, &file_meta,
|
||||
&switched_to_mempurge);
|
||||
&switched_to_mempurge, &skip_set_bg_error,
|
||||
&error_handler_);
|
||||
need_cancel = false;
|
||||
}
|
||||
|
||||
@@ -344,7 +367,8 @@ Status DBImpl::FlushMemTableToOutputFile(
|
||||
}
|
||||
}
|
||||
|
||||
if (!s.ok() && !s.IsShutdownInProgress() && !s.IsColumnFamilyDropped()) {
|
||||
if (!s.ok() && !s.IsShutdownInProgress() && !s.IsColumnFamilyDropped() &&
|
||||
!skip_set_bg_error) {
|
||||
if (log_io_s.ok()) {
|
||||
// Error while writing to MANIFEST.
|
||||
// In fact, versions_->io_status() can also be the result of renaming
|
||||
@@ -525,8 +549,10 @@ Status DBImpl::AtomicFlushMemTablesToOutputFiles(
|
||||
// TODO (yanqin) investigate whether we should sync the closed logs for
|
||||
// single column family case.
|
||||
VersionEdit synced_wals;
|
||||
bool error_recovery_in_prog = error_handler_.IsRecoveryInProgress();
|
||||
mutex_.Unlock();
|
||||
log_io_s = SyncClosedLogs(job_context, &synced_wals);
|
||||
log_io_s =
|
||||
SyncClosedLogs(job_context, &synced_wals, error_recovery_in_prog);
|
||||
mutex_.Lock();
|
||||
if (log_io_s.ok() && synced_wals.IsWalAddition()) {
|
||||
const ReadOptions read_options(Env::IOActivity::kFlush);
|
||||
@@ -556,6 +582,21 @@ Status DBImpl::AtomicFlushMemTablesToOutputFiles(
|
||||
pick_status.push_back(false);
|
||||
}
|
||||
|
||||
bool flush_for_recovery =
|
||||
bg_flush_args[0].flush_reason_ == FlushReason::kErrorRecovery ||
|
||||
bg_flush_args[0].flush_reason_ == FlushReason::kErrorRecoveryRetryFlush;
|
||||
bool skip_set_bg_error = false;
|
||||
|
||||
if (s.ok() && !error_handler_.GetBGError().ok() &&
|
||||
error_handler_.IsBGWorkStopped() && !flush_for_recovery) {
|
||||
s = error_handler_.GetBGError();
|
||||
skip_set_bg_error = true;
|
||||
assert(!s.ok());
|
||||
ROCKS_LOG_BUFFER(log_buffer,
|
||||
"[JOB %d] Skip flush due to background error %s",
|
||||
job_context->job_id, s.ToString().c_str());
|
||||
}
|
||||
|
||||
if (s.ok()) {
|
||||
for (int i = 0; i != num_cfs; ++i) {
|
||||
jobs[i]->PickMemTable();
|
||||
@@ -620,7 +661,10 @@ Status DBImpl::AtomicFlushMemTablesToOutputFiles(
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
} else if (!skip_set_bg_error) {
|
||||
// When `skip_set_bg_error` is true, no memtable is picked so
|
||||
// there is no need to call Cancel() or RollbackMemtableFlush().
|
||||
//
|
||||
// Need to undo atomic flush if something went wrong, i.e. s is not OK and
|
||||
// it is not because of CF drop.
|
||||
// Have to cancel the flush jobs that have NOT executed because we need to
|
||||
@@ -633,8 +677,8 @@ Status DBImpl::AtomicFlushMemTablesToOutputFiles(
|
||||
for (int i = 0; i != num_cfs; ++i) {
|
||||
if (exec_status[i].second.ok() && exec_status[i].first) {
|
||||
auto& mems = jobs[i]->GetMemTables();
|
||||
cfds[i]->imm()->RollbackMemtableFlush(mems,
|
||||
file_meta[i].fd.GetNumber());
|
||||
cfds[i]->imm()->RollbackMemtableFlush(
|
||||
mems, /*rollback_succeeding_memtables=*/false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -676,10 +720,7 @@ Status DBImpl::AtomicFlushMemTablesToOutputFiles(
|
||||
};
|
||||
|
||||
bool resuming_from_bg_err =
|
||||
error_handler_.IsDBStopped() ||
|
||||
(bg_flush_args[0].flush_reason_ == FlushReason::kErrorRecovery ||
|
||||
bg_flush_args[0].flush_reason_ ==
|
||||
FlushReason::kErrorRecoveryRetryFlush);
|
||||
error_handler_.IsDBStopped() || flush_for_recovery;
|
||||
while ((!resuming_from_bg_err || error_handler_.GetRecoveryError().ok())) {
|
||||
std::pair<Status, bool> res = wait_to_install_func();
|
||||
|
||||
@@ -690,15 +731,27 @@ Status DBImpl::AtomicFlushMemTablesToOutputFiles(
|
||||
s = res.first;
|
||||
break;
|
||||
} else if (!res.second) {
|
||||
// we are the oldest immutable memtable
|
||||
break;
|
||||
}
|
||||
// We are not the oldest immutable memtable
|
||||
TEST_SYNC_POINT_CALLBACK(
|
||||
"DBImpl::AtomicFlushMemTablesToOutputFiles:WaitCV", &res);
|
||||
//
|
||||
// If bg work is stopped, recovery thread first calls
|
||||
// WaitForBackgroundWork() before proceeding to flush for recovery. This
|
||||
// flush can block WaitForBackgroundWork() while waiting for recovery
|
||||
// flush to install result. To avoid this deadlock, we should abort here
|
||||
// if there is background error.
|
||||
if (!flush_for_recovery && error_handler_.IsBGWorkStopped() &&
|
||||
!error_handler_.GetBGError().ok()) {
|
||||
s = error_handler_.GetBGError();
|
||||
assert(!s.ok());
|
||||
break;
|
||||
}
|
||||
atomic_flush_install_cv_.Wait();
|
||||
|
||||
resuming_from_bg_err =
|
||||
error_handler_.IsDBStopped() ||
|
||||
(bg_flush_args[0].flush_reason_ == FlushReason::kErrorRecovery ||
|
||||
bg_flush_args[0].flush_reason_ ==
|
||||
FlushReason::kErrorRecoveryRetryFlush);
|
||||
resuming_from_bg_err = error_handler_.IsDBStopped() || flush_for_recovery;
|
||||
}
|
||||
|
||||
if (!resuming_from_bg_err) {
|
||||
@@ -714,6 +767,17 @@ Status DBImpl::AtomicFlushMemTablesToOutputFiles(
|
||||
// installation.
|
||||
s = error_handler_.GetRecoveryError();
|
||||
}
|
||||
// Since we are not installing these memtables, need to rollback
|
||||
// to allow future flush job to pick up these memtables.
|
||||
if (!s.ok()) {
|
||||
for (int i = 0; i != num_cfs; ++i) {
|
||||
assert(exec_status[i].first);
|
||||
assert(exec_status[i].second.ok());
|
||||
auto& mems = jobs[i]->GetMemTables();
|
||||
cfds[i]->imm()->RollbackMemtableFlush(
|
||||
mems, /*rollback_succeeding_memtables=*/false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (s.ok()) {
|
||||
@@ -817,7 +881,7 @@ Status DBImpl::AtomicFlushMemTablesToOutputFiles(
|
||||
|
||||
// Need to undo atomic flush if something went wrong, i.e. s is not OK and
|
||||
// it is not because of CF drop.
|
||||
if (!s.ok() && !s.IsColumnFamilyDropped()) {
|
||||
if (!s.ok() && !s.IsColumnFamilyDropped() && !skip_set_bg_error) {
|
||||
if (log_io_s.ok()) {
|
||||
// Error while writing to MANIFEST.
|
||||
// In fact, versions_->io_status() can also be the result of renaming
|
||||
@@ -947,26 +1011,14 @@ Status DBImpl::CompactRange(const CompactRangeOptions& options,
|
||||
end_without_ts, "" /*trim_ts*/);
|
||||
}
|
||||
|
||||
std::string begin_str;
|
||||
std::string end_str;
|
||||
std::string begin_str, end_str;
|
||||
auto [begin, end] =
|
||||
MaybeAddTimestampsToRange(begin_without_ts, end_without_ts, ts_sz,
|
||||
&begin_str, &end_str, false /*exclusive_end*/);
|
||||
|
||||
// CompactRange compact all keys: [begin, end] inclusively. Add maximum
|
||||
// timestamp to include all `begin` keys, and add minimal timestamp to include
|
||||
// all `end` keys.
|
||||
if (begin_without_ts != nullptr) {
|
||||
AppendKeyWithMaxTimestamp(&begin_str, *begin_without_ts, ts_sz);
|
||||
}
|
||||
if (end_without_ts != nullptr) {
|
||||
AppendKeyWithMinTimestamp(&end_str, *end_without_ts, ts_sz);
|
||||
}
|
||||
Slice begin(begin_str);
|
||||
Slice end(end_str);
|
||||
|
||||
Slice* begin_with_ts = begin_without_ts ? &begin : nullptr;
|
||||
Slice* end_with_ts = end_without_ts ? &end : nullptr;
|
||||
|
||||
return CompactRangeInternal(options, column_family, begin_with_ts,
|
||||
end_with_ts, "" /*trim_ts*/);
|
||||
return CompactRangeInternal(
|
||||
options, column_family, begin.has_value() ? &begin.value() : nullptr,
|
||||
end.has_value() ? &end.value() : nullptr, "" /*trim_ts*/);
|
||||
}
|
||||
|
||||
Status DBImpl::IncreaseFullHistoryTsLow(ColumnFamilyHandle* column_family,
|
||||
@@ -1473,7 +1525,8 @@ Status DBImpl::CompactFilesImpl(
|
||||
// without releasing the lock, so we're guaranteed a compaction can be formed.
|
||||
assert(c != nullptr);
|
||||
|
||||
c->SetInputVersion(version);
|
||||
c->FinalizeInputInfo(version);
|
||||
|
||||
// deletion compaction currently not allowed in CompactFiles.
|
||||
assert(!c->deletion_compaction());
|
||||
|
||||
@@ -1523,7 +1576,12 @@ Status DBImpl::CompactFilesImpl(
|
||||
TEST_SYNC_POINT("CompactFilesImpl:3");
|
||||
mutex_.Lock();
|
||||
|
||||
Status status = compaction_job.Install(*c->mutable_cf_options());
|
||||
bool compaction_released = false;
|
||||
Status status =
|
||||
compaction_job.Install(*c->mutable_cf_options(), &compaction_released);
|
||||
if (!compaction_released) {
|
||||
c->ReleaseCompactionFiles(s);
|
||||
}
|
||||
if (status.ok()) {
|
||||
assert(compaction_job.io_status().ok());
|
||||
InstallSuperVersionAndScheduleWork(c->column_family_data(),
|
||||
@@ -1534,7 +1592,6 @@ Status DBImpl::CompactFilesImpl(
|
||||
// not check compaction_job.io_status() explicitly if we're not calling
|
||||
// SetBGError
|
||||
compaction_job.io_status().PermitUncheckedError();
|
||||
c->ReleaseCompactionFiles(s);
|
||||
// Need to make sure SstFileManager does its bookkeeping
|
||||
auto sfm = static_cast<SstFileManagerImpl*>(
|
||||
immutable_db_options_.sst_file_manager.get());
|
||||
@@ -2223,9 +2280,13 @@ Status DBImpl::FlushMemTable(ColumnFamilyData* cfd,
|
||||
WaitForPendingWrites();
|
||||
|
||||
if (flush_reason != FlushReason::kErrorRecoveryRetryFlush &&
|
||||
flush_reason != FlushReason::kCatchUpAfterErrorRecovery &&
|
||||
(!cfd->mem()->IsEmpty() || !cached_recoverable_state_empty_.load())) {
|
||||
// Note that, when flush reason is kErrorRecoveryRetryFlush, during the
|
||||
// auto retry resume, we want to avoid creating new small memtables.
|
||||
// If flush reason is kCatchUpAfterErrorRecovery, we try to flush any new
|
||||
// memtable that filled up during recovery, and we also want to avoid
|
||||
// switching memtable to create small memtables.
|
||||
// Therefore, SwitchMemtable will not be called. Also, since ResumeImpl
|
||||
// will iterate through all the CFs and call FlushMemtable during auto
|
||||
// retry resume, it is possible that in some CFs,
|
||||
@@ -2416,7 +2477,8 @@ Status DBImpl::AtomicFlushMemTables(
|
||||
|
||||
for (auto cfd : cfds) {
|
||||
if ((cfd->mem()->IsEmpty() && cached_recoverable_state_empty_.load()) ||
|
||||
flush_reason == FlushReason::kErrorRecoveryRetryFlush) {
|
||||
flush_reason == FlushReason::kErrorRecoveryRetryFlush ||
|
||||
flush_reason == FlushReason::kCatchUpAfterErrorRecovery) {
|
||||
continue;
|
||||
}
|
||||
cfd->Ref();
|
||||
@@ -2684,6 +2746,11 @@ void DBImpl::MaybeScheduleFlushOrCompaction() {
|
||||
// There has been a hard error and this call is not part of the recovery
|
||||
// sequence. Bail out here so we don't get into an endless loop of
|
||||
// scheduling BG work which will again call this function
|
||||
//
|
||||
// Note that a non-recovery flush can still be scheduled if
|
||||
// error_handler_.IsRecoveryInProgress() returns true. We rely on
|
||||
// BackgroundCallFlush() to check flush reason and drop non-recovery
|
||||
// flushes.
|
||||
return;
|
||||
} else if (shutting_down_.load(std::memory_order_acquire)) {
|
||||
// DB is being deleted; no more background compactions
|
||||
@@ -3013,6 +3080,24 @@ Status DBImpl::BackgroundFlush(bool* made_progress, JobContext* job_context,
|
||||
// This cfd is already referenced
|
||||
FlushRequest flush_req = PopFirstFromFlushQueue();
|
||||
FlushReason flush_reason = flush_req.flush_reason;
|
||||
if (!error_handler_.GetBGError().ok() && error_handler_.IsBGWorkStopped() &&
|
||||
flush_reason != FlushReason::kErrorRecovery &&
|
||||
flush_reason != FlushReason::kErrorRecoveryRetryFlush) {
|
||||
// Stop non-recovery flush when bg work is stopped
|
||||
// Note that we drop the flush request here.
|
||||
// Recovery thread should schedule further flushes after bg error
|
||||
// is cleared.
|
||||
status = error_handler_.GetBGError();
|
||||
assert(!status.ok());
|
||||
ROCKS_LOG_BUFFER(log_buffer,
|
||||
"[JOB %d] Abort flush due to background error %s",
|
||||
job_context->job_id, status.ToString().c_str());
|
||||
*reason = flush_reason;
|
||||
for (auto item : flush_req.cfd_to_max_mem_id_to_persist) {
|
||||
item.first->UnrefAndTryDelete();
|
||||
}
|
||||
return status;
|
||||
}
|
||||
if (!immutable_db_options_.atomic_flush &&
|
||||
ShouldRescheduleFlushRequestToRetainUDT(flush_req)) {
|
||||
assert(flush_req.cfd_to_max_mem_id_to_persist.size() == 1);
|
||||
@@ -3155,9 +3240,9 @@ void DBImpl::BackgroundCallFlush(Env::Priority thread_pri) {
|
||||
bg_cv_.SignalAll(); // In case a waiter can proceed despite the error
|
||||
mutex_.Unlock();
|
||||
ROCKS_LOG_ERROR(immutable_db_options_.info_log,
|
||||
"Waiting after background flush error: %s"
|
||||
"[JOB %d] Waiting after background flush error: %s"
|
||||
"Accumulated background error counts: %" PRIu64,
|
||||
s.ToString().c_str(), error_cnt);
|
||||
job_context.job_id, s.ToString().c_str(), error_cnt);
|
||||
log_buffer.FlushBufferToLog();
|
||||
LogFlush(immutable_db_options_.info_log);
|
||||
immutable_db_options_.clock->SleepForMicroseconds(1000000);
|
||||
@@ -3399,8 +3484,6 @@ Status DBImpl::BackgroundCompaction(bool* made_progress,
|
||||
|
||||
std::unique_ptr<TaskLimiterToken> task_token;
|
||||
|
||||
// InternalKey manual_end_storage;
|
||||
// InternalKey* manual_end = &manual_end_storage;
|
||||
bool sfm_reserved_compact_space = false;
|
||||
if (is_manual) {
|
||||
ManualCompactionState* m = manual_compaction;
|
||||
@@ -3536,6 +3619,7 @@ Status DBImpl::BackgroundCompaction(bool* made_progress,
|
||||
}
|
||||
|
||||
IOStatus io_s;
|
||||
bool compaction_released = false;
|
||||
if (!c) {
|
||||
// Nothing to do
|
||||
ROCKS_LOG_BUFFER(log_buffer, "Compaction nothing to do");
|
||||
@@ -3558,7 +3642,12 @@ Status DBImpl::BackgroundCompaction(bool* made_progress,
|
||||
}
|
||||
status = versions_->LogAndApply(
|
||||
c->column_family_data(), *c->mutable_cf_options(), read_options,
|
||||
c->edit(), &mutex_, directories_.GetDbDir());
|
||||
c->edit(), &mutex_, directories_.GetDbDir(),
|
||||
/*new_descriptor_log=*/false, /*column_family_options=*/nullptr,
|
||||
[&c, &compaction_released](const Status& s) {
|
||||
c->ReleaseCompactionFiles(s);
|
||||
compaction_released = true;
|
||||
});
|
||||
io_s = versions_->io_status();
|
||||
InstallSuperVersionAndScheduleWork(c->column_family_data(),
|
||||
&job_context->superversion_contexts[0],
|
||||
@@ -3624,7 +3713,12 @@ Status DBImpl::BackgroundCompaction(bool* made_progress,
|
||||
}
|
||||
status = versions_->LogAndApply(
|
||||
c->column_family_data(), *c->mutable_cf_options(), read_options,
|
||||
c->edit(), &mutex_, directories_.GetDbDir());
|
||||
c->edit(), &mutex_, directories_.GetDbDir(),
|
||||
/*new_descriptor_log=*/false, /*column_family_options=*/nullptr,
|
||||
[&c, &compaction_released](const Status& s) {
|
||||
c->ReleaseCompactionFiles(s);
|
||||
compaction_released = true;
|
||||
});
|
||||
io_s = versions_->io_status();
|
||||
// Use latest MutableCFOptions
|
||||
InstallSuperVersionAndScheduleWork(c->column_family_data(),
|
||||
@@ -3674,6 +3768,7 @@ Status DBImpl::BackgroundCompaction(bool* made_progress,
|
||||
// Transfer requested token, so it doesn't need to do it again.
|
||||
ca->prepicked_compaction->task_token = std::move(task_token);
|
||||
++bg_bottom_compaction_scheduled_;
|
||||
assert(c == nullptr);
|
||||
env_->Schedule(&DBImpl::BGWorkBottomCompaction, ca, Env::Priority::BOTTOM,
|
||||
this, &DBImpl::UnscheduleCompactionCallback);
|
||||
} else {
|
||||
@@ -3717,8 +3812,8 @@ Status DBImpl::BackgroundCompaction(bool* made_progress,
|
||||
compaction_job.Run().PermitUncheckedError();
|
||||
TEST_SYNC_POINT("DBImpl::BackgroundCompaction:NonTrivial:AfterRun");
|
||||
mutex_.Lock();
|
||||
|
||||
status = compaction_job.Install(*c->mutable_cf_options());
|
||||
status =
|
||||
compaction_job.Install(*c->mutable_cf_options(), &compaction_released);
|
||||
io_s = compaction_job.io_status();
|
||||
if (status.ok()) {
|
||||
InstallSuperVersionAndScheduleWork(c->column_family_data(),
|
||||
@@ -3737,7 +3832,23 @@ Status DBImpl::BackgroundCompaction(bool* made_progress,
|
||||
}
|
||||
|
||||
if (c != nullptr) {
|
||||
c->ReleaseCompactionFiles(status);
|
||||
if (!compaction_released) {
|
||||
c->ReleaseCompactionFiles(status);
|
||||
} else {
|
||||
#ifndef NDEBUG
|
||||
// Sanity checking that compaction files are freed.
|
||||
for (size_t i = 0; i < c->num_input_levels(); i++) {
|
||||
for (size_t j = 0; j < c->inputs(i)->size(); j++) {
|
||||
assert(!c->input(i, j)->being_compacted);
|
||||
}
|
||||
}
|
||||
std::unordered_set<Compaction*>* cip = c->column_family_data()
|
||||
->compaction_picker()
|
||||
->compactions_in_progress();
|
||||
assert(cip->find(c.get()) == cip->end());
|
||||
#endif
|
||||
}
|
||||
|
||||
*made_progress = true;
|
||||
|
||||
// Need to make sure SstFileManager does its bookkeeping
|
||||
@@ -3935,7 +4046,12 @@ void DBImpl::BuildCompactionJobInfo(
|
||||
compaction_job_info->base_input_level = c->start_level();
|
||||
compaction_job_info->output_level = c->output_level();
|
||||
compaction_job_info->stats = compaction_job_stats;
|
||||
compaction_job_info->table_properties = c->GetTableProperties();
|
||||
const auto& input_table_properties = c->GetInputTableProperties();
|
||||
const auto& output_table_properties = c->GetOutputTableProperties();
|
||||
compaction_job_info->table_properties.insert(input_table_properties.begin(),
|
||||
input_table_properties.end());
|
||||
compaction_job_info->table_properties.insert(output_table_properties.begin(),
|
||||
output_table_properties.end());
|
||||
compaction_job_info->compaction_reason = c->compaction_reason();
|
||||
compaction_job_info->compression = c->output_compression();
|
||||
|
||||
|
||||
@@ -100,6 +100,14 @@ Status DBImpl::EnableFileDeletions(bool force) {
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
int DBImpl::EnableFileDeletionsWithLock() {
|
||||
mutex_.AssertHeld();
|
||||
// In case others have called EnableFileDeletions(true /* force */) in between
|
||||
disable_delete_obsolete_files_ =
|
||||
std::max(0, disable_delete_obsolete_files_ - 1);
|
||||
return disable_delete_obsolete_files_;
|
||||
}
|
||||
|
||||
bool DBImpl::IsFileDeletionsEnabled() const {
|
||||
return 0 == disable_delete_obsolete_files_;
|
||||
}
|
||||
@@ -457,12 +465,12 @@ void DBImpl::PurgeObsoleteFiles(JobContext& state, bool schedule_only) {
|
||||
std::sort(candidate_files.begin(), candidate_files.end(),
|
||||
[](const JobContext::CandidateFileInfo& lhs,
|
||||
const JobContext::CandidateFileInfo& rhs) {
|
||||
if (lhs.file_name > rhs.file_name) {
|
||||
if (lhs.file_name < rhs.file_name) {
|
||||
return true;
|
||||
} else if (lhs.file_name < rhs.file_name) {
|
||||
} else if (lhs.file_name > rhs.file_name) {
|
||||
return false;
|
||||
} else {
|
||||
return (lhs.file_path > rhs.file_path);
|
||||
return (lhs.file_path < rhs.file_path);
|
||||
}
|
||||
});
|
||||
candidate_files.erase(
|
||||
@@ -995,7 +1003,7 @@ Status DBImpl::DeleteUnreferencedSstFiles(RecoveryContext* recovery_ctx) {
|
||||
if (type == kTableFile && number >= next_file_number &&
|
||||
recovery_ctx->files_to_delete_.find(normalized_fpath) ==
|
||||
recovery_ctx->files_to_delete_.end()) {
|
||||
recovery_ctx->files_to_delete_.emplace(normalized_fpath);
|
||||
recovery_ctx->files_to_delete_.emplace(normalized_fpath, path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+22
-10
@@ -143,13 +143,6 @@ DBOptions SanitizeOptions(const std::string& dbname, const DBOptions& src,
|
||||
result.wal_dir = result.wal_dir.substr(0, result.wal_dir.size() - 1);
|
||||
}
|
||||
|
||||
if (result.compaction_readahead_size == 0) {
|
||||
if (result.use_direct_reads) {
|
||||
TEST_SYNC_POINT_CALLBACK("SanitizeOptions:direct_io", nullptr);
|
||||
}
|
||||
result.compaction_readahead_size = 1024 * 1024 * 2;
|
||||
}
|
||||
|
||||
// Force flush on DB open if 2PC is enabled, since with 2PC we have no
|
||||
// guarantee that consecutive log files have consecutive sequence id, which
|
||||
// make recovery complicated.
|
||||
@@ -934,8 +927,11 @@ Status DBImpl::LogAndApplyForRecovery(const RecoveryContext& recovery_ctx) {
|
||||
recovery_ctx.edit_lists_, &mutex_, directories_.GetDbDir());
|
||||
if (s.ok() && !(recovery_ctx.files_to_delete_.empty())) {
|
||||
mutex_.Unlock();
|
||||
for (const auto& fname : recovery_ctx.files_to_delete_) {
|
||||
s = env_->DeleteFile(fname);
|
||||
for (const auto& stale_sst_file : recovery_ctx.files_to_delete_) {
|
||||
s = DeleteDBFile(&immutable_db_options_, stale_sst_file.first,
|
||||
stale_sst_file.second,
|
||||
/*force_bg=*/false,
|
||||
/*force_fg=*/false);
|
||||
if (!s.ok()) {
|
||||
break;
|
||||
}
|
||||
@@ -1305,7 +1301,7 @@ Status DBImpl::RecoverLogFiles(const std::vector<uint64_t>& wal_numbers,
|
||||
flushed = true;
|
||||
|
||||
cfd->CreateNewMemtable(*cfd->GetLatestMutableCFOptions(),
|
||||
*next_sequence);
|
||||
*next_sequence - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1722,6 +1718,22 @@ Status DBImpl::WriteLevel0TableForRecovery(int job_id, ColumnFamilyData* cfd,
|
||||
for (const auto& blob : blob_file_additions) {
|
||||
edit->AddBlobFile(blob);
|
||||
}
|
||||
|
||||
// For UDT in memtable only feature, move up the cutoff timestamp whenever
|
||||
// a flush happens.
|
||||
const Comparator* ucmp = cfd->user_comparator();
|
||||
size_t ts_sz = ucmp->timestamp_size();
|
||||
if (ts_sz > 0 && !cfd->ioptions()->persist_user_defined_timestamps) {
|
||||
Slice mem_newest_udt = mem->GetNewestUDT();
|
||||
std::string full_history_ts_low = cfd->GetFullHistoryTsLow();
|
||||
if (full_history_ts_low.empty() ||
|
||||
ucmp->CompareTimestamp(mem_newest_udt, full_history_ts_low) >= 0) {
|
||||
std::string new_full_history_ts_low;
|
||||
GetFullHistoryTsLowFromU64CutoffTs(&mem_newest_udt,
|
||||
&new_full_history_ts_low);
|
||||
edit->SetFullHistoryTsLow(new_full_history_ts_low);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
InternalStats::CompactionStats stats(CompactionReason::kFlush, 1);
|
||||
|
||||
@@ -29,42 +29,23 @@ DBImplReadOnly::DBImplReadOnly(const DBOptions& db_options,
|
||||
DBImplReadOnly::~DBImplReadOnly() {}
|
||||
|
||||
// Implementations of the DB interface
|
||||
Status DBImplReadOnly::Get(const ReadOptions& read_options,
|
||||
ColumnFamilyHandle* column_family, const Slice& key,
|
||||
PinnableSlice* pinnable_val) {
|
||||
return Get(read_options, column_family, key, pinnable_val,
|
||||
/*timestamp*/ nullptr);
|
||||
}
|
||||
Status DBImplReadOnly::GetImpl(const ReadOptions& read_options,
|
||||
const Slice& key,
|
||||
GetImplOptions& get_impl_options) {
|
||||
assert(get_impl_options.value != nullptr ||
|
||||
get_impl_options.columns != nullptr);
|
||||
assert(get_impl_options.column_family);
|
||||
|
||||
Status DBImplReadOnly::Get(const ReadOptions& _read_options,
|
||||
ColumnFamilyHandle* column_family, const Slice& key,
|
||||
PinnableSlice* pinnable_val,
|
||||
std::string* timestamp) {
|
||||
if (_read_options.io_activity != Env::IOActivity::kUnknown &&
|
||||
_read_options.io_activity != Env::IOActivity::kGet) {
|
||||
return Status::InvalidArgument(
|
||||
"Can only call Get with `ReadOptions::io_activity` is "
|
||||
"`Env::IOActivity::kUnknown` or `Env::IOActivity::kGet`");
|
||||
}
|
||||
ReadOptions read_options(_read_options);
|
||||
if (read_options.io_activity == Env::IOActivity::kUnknown) {
|
||||
read_options.io_activity = Env::IOActivity::kGet;
|
||||
}
|
||||
assert(pinnable_val != nullptr);
|
||||
PERF_CPU_TIMER_GUARD(get_cpu_nanos, immutable_db_options_.clock);
|
||||
StopWatch sw(immutable_db_options_.clock, stats_, DB_GET);
|
||||
PERF_TIMER_GUARD(get_snapshot_time);
|
||||
Status s;
|
||||
|
||||
assert(column_family);
|
||||
if (read_options.timestamp) {
|
||||
const Status s =
|
||||
FailIfTsMismatchCf(column_family, *(read_options.timestamp),
|
||||
/*ts_for_read=*/true);
|
||||
s = FailIfTsMismatchCf(get_impl_options.column_family,
|
||||
*(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
} else {
|
||||
const Status s = FailIfCfHasTs(column_family);
|
||||
s = FailIfCfHasTs(get_impl_options.column_family);
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
@@ -72,53 +53,80 @@ Status DBImplReadOnly::Get(const ReadOptions& _read_options,
|
||||
|
||||
// Clear the timestamps for returning results so that we can distinguish
|
||||
// between tombstone or key that has never been written
|
||||
if (timestamp) {
|
||||
timestamp->clear();
|
||||
if (get_impl_options.timestamp) {
|
||||
get_impl_options.timestamp->clear();
|
||||
}
|
||||
|
||||
const Comparator* ucmp = column_family->GetComparator();
|
||||
assert(ucmp);
|
||||
std::string* ts = ucmp->timestamp_size() > 0 ? timestamp : nullptr;
|
||||
PERF_CPU_TIMER_GUARD(get_cpu_nanos, immutable_db_options_.clock);
|
||||
StopWatch sw(immutable_db_options_.clock, stats_, DB_GET);
|
||||
PERF_TIMER_GUARD(get_snapshot_time);
|
||||
|
||||
Status s;
|
||||
const Comparator* ucmp = get_impl_options.column_family->GetComparator();
|
||||
assert(ucmp);
|
||||
std::string* ts =
|
||||
ucmp->timestamp_size() > 0 ? get_impl_options.timestamp : nullptr;
|
||||
SequenceNumber snapshot = versions_->LastSequence();
|
||||
GetWithTimestampReadCallback read_cb(snapshot);
|
||||
auto cfh = static_cast_with_check<ColumnFamilyHandleImpl>(column_family);
|
||||
auto cfh = static_cast_with_check<ColumnFamilyHandleImpl>(
|
||||
get_impl_options.column_family);
|
||||
auto cfd = cfh->cfd();
|
||||
if (tracer_) {
|
||||
InstrumentedMutexLock lock(&trace_mutex_);
|
||||
if (tracer_) {
|
||||
tracer_->Get(column_family, key);
|
||||
tracer_->Get(get_impl_options.column_family, key);
|
||||
}
|
||||
}
|
||||
|
||||
// In read-only mode Get(), no super version operation is needed (i.e.
|
||||
// GetAndRefSuperVersion and ReturnAndCleanupSuperVersion)
|
||||
SuperVersion* super_version = cfd->GetSuperVersion();
|
||||
if (read_options.timestamp && read_options.timestamp->size() > 0) {
|
||||
s = FailIfReadCollapsedHistory(cfd, super_version,
|
||||
*(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
MergeContext merge_context;
|
||||
SequenceNumber max_covering_tombstone_seq = 0;
|
||||
LookupKey lkey(key, snapshot, read_options.timestamp);
|
||||
PERF_TIMER_STOP(get_snapshot_time);
|
||||
if (super_version->mem->Get(lkey, pinnable_val->GetSelf(),
|
||||
/*columns=*/nullptr, ts, &s, &merge_context,
|
||||
&max_covering_tombstone_seq, read_options,
|
||||
false /* immutable_memtable */, &read_cb)) {
|
||||
pinnable_val->PinSelf();
|
||||
|
||||
// Look up starts here
|
||||
if (super_version->mem->Get(
|
||||
lkey,
|
||||
get_impl_options.value ? get_impl_options.value->GetSelf() : nullptr,
|
||||
get_impl_options.columns, ts, &s, &merge_context,
|
||||
&max_covering_tombstone_seq, read_options,
|
||||
false /* immutable_memtable */, &read_cb)) {
|
||||
if (get_impl_options.value) {
|
||||
get_impl_options.value->PinSelf();
|
||||
}
|
||||
RecordTick(stats_, MEMTABLE_HIT);
|
||||
} else {
|
||||
PERF_TIMER_GUARD(get_from_output_files_time);
|
||||
PinnedIteratorsManager pinned_iters_mgr;
|
||||
super_version->current->Get(
|
||||
read_options, lkey, pinnable_val, /*columns=*/nullptr, ts, &s,
|
||||
&merge_context, &max_covering_tombstone_seq, &pinned_iters_mgr,
|
||||
read_options, lkey, get_impl_options.value, get_impl_options.columns,
|
||||
ts, &s, &merge_context, &max_covering_tombstone_seq, &pinned_iters_mgr,
|
||||
/*value_found*/ nullptr,
|
||||
/*key_exists*/ nullptr, /*seq*/ nullptr, &read_cb,
|
||||
/*is_blob*/ nullptr,
|
||||
/*do_merge*/ true);
|
||||
RecordTick(stats_, MEMTABLE_MISS);
|
||||
}
|
||||
RecordTick(stats_, NUMBER_KEYS_READ);
|
||||
size_t size = pinnable_val->size();
|
||||
RecordTick(stats_, BYTES_READ, size);
|
||||
RecordInHistogram(stats_, BYTES_PER_READ, size);
|
||||
PERF_COUNTER_ADD(get_read_bytes, size);
|
||||
{
|
||||
RecordTick(stats_, NUMBER_KEYS_READ);
|
||||
size_t size = 0;
|
||||
if (get_impl_options.value) {
|
||||
size = get_impl_options.value->size();
|
||||
} else if (get_impl_options.columns) {
|
||||
size = get_impl_options.columns->serialized_size();
|
||||
}
|
||||
RecordTick(stats_, BYTES_READ, size);
|
||||
RecordInHistogram(stats_, BYTES_PER_READ, size);
|
||||
PERF_COUNTER_ADD(get_read_bytes, size);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -137,8 +145,7 @@ Iterator* DBImplReadOnly::NewIterator(const ReadOptions& _read_options,
|
||||
assert(column_family);
|
||||
if (read_options.timestamp) {
|
||||
const Status s =
|
||||
FailIfTsMismatchCf(column_family, *(read_options.timestamp),
|
||||
/*ts_for_read=*/true);
|
||||
FailIfTsMismatchCf(column_family, *(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
return NewErrorIterator(s);
|
||||
}
|
||||
@@ -151,6 +158,14 @@ Iterator* DBImplReadOnly::NewIterator(const ReadOptions& _read_options,
|
||||
auto cfh = static_cast_with_check<ColumnFamilyHandleImpl>(column_family);
|
||||
auto cfd = cfh->cfd();
|
||||
SuperVersion* super_version = cfd->GetSuperVersion()->Ref();
|
||||
if (read_options.timestamp && read_options.timestamp->size() > 0) {
|
||||
const Status s = FailIfReadCollapsedHistory(cfd, super_version,
|
||||
*(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
cfd->GetSuperVersion()->Unref();
|
||||
return NewErrorIterator(s);
|
||||
}
|
||||
}
|
||||
SequenceNumber latest_snapshot = versions_->LastSequence();
|
||||
SequenceNumber read_seq =
|
||||
read_options.snapshot != nullptr
|
||||
@@ -177,8 +192,7 @@ Status DBImplReadOnly::NewIterators(
|
||||
if (read_options.timestamp) {
|
||||
for (auto* cf : column_families) {
|
||||
assert(cf);
|
||||
const Status s = FailIfTsMismatchCf(cf, *(read_options.timestamp),
|
||||
/*ts_for_read=*/true);
|
||||
const Status s = FailIfTsMismatchCf(cf, *(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
@@ -206,9 +220,27 @@ Status DBImplReadOnly::NewIterators(
|
||||
->number_
|
||||
: latest_snapshot;
|
||||
|
||||
autovector<std::tuple<ColumnFamilyData*, SuperVersion*>> cfd_to_sv;
|
||||
|
||||
const bool check_read_ts =
|
||||
read_options.timestamp && read_options.timestamp->size() > 0;
|
||||
for (auto cfh : column_families) {
|
||||
auto* cfd = static_cast_with_check<ColumnFamilyHandleImpl>(cfh)->cfd();
|
||||
auto* sv = cfd->GetSuperVersion()->Ref();
|
||||
cfd_to_sv.emplace_back(cfd, sv);
|
||||
if (check_read_ts) {
|
||||
const Status s =
|
||||
FailIfReadCollapsedHistory(cfd, sv, *(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
for (auto prev_entry : cfd_to_sv) {
|
||||
std::get<1>(prev_entry)->Unref();
|
||||
}
|
||||
return s;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert(cfd_to_sv.size() == column_families.size());
|
||||
for (auto [cfd, sv] : cfd_to_sv) {
|
||||
auto* db_iter = NewArenaWrappedDbIterator(
|
||||
env_, read_options, *cfd->ioptions(), sv->mutable_cf_options,
|
||||
sv->current, read_seq,
|
||||
|
||||
@@ -24,13 +24,9 @@ class DBImplReadOnly : public DBImpl {
|
||||
virtual ~DBImplReadOnly();
|
||||
|
||||
// Implementations of the DB interface
|
||||
using DB::Get;
|
||||
virtual Status Get(const ReadOptions& options,
|
||||
ColumnFamilyHandle* column_family, const Slice& key,
|
||||
PinnableSlice* value) override;
|
||||
Status Get(const ReadOptions& _read_options,
|
||||
ColumnFamilyHandle* column_family, const Slice& key,
|
||||
PinnableSlice* value, std::string* timestamp) override;
|
||||
using DBImpl::GetImpl;
|
||||
Status GetImpl(const ReadOptions& options, const Slice& key,
|
||||
GetImplOptions& get_impl_options) override;
|
||||
|
||||
// TODO: Implement ReadOnly MultiGet?
|
||||
|
||||
|
||||
@@ -339,105 +339,93 @@ Status DBImplSecondary::RecoverLogFiles(
|
||||
return status;
|
||||
}
|
||||
|
||||
// Implementation of the DB interface
|
||||
Status DBImplSecondary::Get(const ReadOptions& _read_options,
|
||||
ColumnFamilyHandle* column_family, const Slice& key,
|
||||
PinnableSlice* value) {
|
||||
if (_read_options.io_activity != Env::IOActivity::kUnknown &&
|
||||
_read_options.io_activity != Env::IOActivity::kGet) {
|
||||
return Status::InvalidArgument(
|
||||
"Can only call Get with `ReadOptions::io_activity` is "
|
||||
"`Env::IOActivity::kUnknown` or `Env::IOActivity::kGet`");
|
||||
}
|
||||
ReadOptions read_options(_read_options);
|
||||
if (read_options.io_activity == Env::IOActivity::kUnknown) {
|
||||
read_options.io_activity = Env::IOActivity::kGet;
|
||||
}
|
||||
return GetImpl(read_options, column_family, key, value,
|
||||
/*timestamp*/ nullptr);
|
||||
}
|
||||
|
||||
Status DBImplSecondary::Get(const ReadOptions& _read_options,
|
||||
ColumnFamilyHandle* column_family, const Slice& key,
|
||||
PinnableSlice* value, std::string* timestamp) {
|
||||
if (_read_options.io_activity != Env::IOActivity::kUnknown &&
|
||||
_read_options.io_activity != Env::IOActivity::kGet) {
|
||||
return Status::InvalidArgument(
|
||||
"Can only call Get with `ReadOptions::io_activity` is "
|
||||
"`Env::IOActivity::kUnknown` or `Env::IOActivity::kGet`");
|
||||
}
|
||||
ReadOptions read_options(_read_options);
|
||||
if (read_options.io_activity == Env::IOActivity::kUnknown) {
|
||||
read_options.io_activity = Env::IOActivity::kGet;
|
||||
}
|
||||
return GetImpl(read_options, column_family, key, value, timestamp);
|
||||
}
|
||||
|
||||
Status DBImplSecondary::GetImpl(const ReadOptions& read_options,
|
||||
ColumnFamilyHandle* column_family,
|
||||
const Slice& key, PinnableSlice* pinnable_val,
|
||||
std::string* timestamp) {
|
||||
assert(pinnable_val != nullptr);
|
||||
PERF_CPU_TIMER_GUARD(get_cpu_nanos, immutable_db_options_.clock);
|
||||
StopWatch sw(immutable_db_options_.clock, stats_, DB_GET);
|
||||
PERF_TIMER_GUARD(get_snapshot_time);
|
||||
const Slice& key,
|
||||
GetImplOptions& get_impl_options) {
|
||||
assert(get_impl_options.value != nullptr ||
|
||||
get_impl_options.columns != nullptr);
|
||||
assert(get_impl_options.column_family);
|
||||
|
||||
Status s;
|
||||
|
||||
assert(column_family);
|
||||
if (read_options.timestamp) {
|
||||
const Status s = FailIfTsMismatchCf(
|
||||
column_family, *(read_options.timestamp), /*ts_for_read=*/true);
|
||||
s = FailIfTsMismatchCf(get_impl_options.column_family,
|
||||
*(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
} else {
|
||||
const Status s = FailIfCfHasTs(column_family);
|
||||
s = FailIfCfHasTs(get_impl_options.column_family);
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
// Clear the timestamp for returning results so that we can distinguish
|
||||
// between tombstone or key that has never been written later.
|
||||
if (timestamp) {
|
||||
timestamp->clear();
|
||||
// Clear the timestamps for returning results so that we can distinguish
|
||||
// between tombstone or key that has never been written
|
||||
if (get_impl_options.timestamp) {
|
||||
get_impl_options.timestamp->clear();
|
||||
}
|
||||
|
||||
auto cfh = static_cast<ColumnFamilyHandleImpl*>(column_family);
|
||||
ColumnFamilyData* cfd = cfh->cfd();
|
||||
PERF_CPU_TIMER_GUARD(get_cpu_nanos, immutable_db_options_.clock);
|
||||
StopWatch sw(immutable_db_options_.clock, stats_, DB_GET);
|
||||
PERF_TIMER_GUARD(get_snapshot_time);
|
||||
|
||||
const Comparator* ucmp = get_impl_options.column_family->GetComparator();
|
||||
assert(ucmp);
|
||||
std::string* ts =
|
||||
ucmp->timestamp_size() > 0 ? get_impl_options.timestamp : nullptr;
|
||||
SequenceNumber snapshot = versions_->LastSequence();
|
||||
GetWithTimestampReadCallback read_cb(snapshot);
|
||||
auto cfh = static_cast_with_check<ColumnFamilyHandleImpl>(
|
||||
get_impl_options.column_family);
|
||||
auto cfd = cfh->cfd();
|
||||
if (tracer_) {
|
||||
InstrumentedMutexLock lock(&trace_mutex_);
|
||||
if (tracer_) {
|
||||
tracer_->Get(column_family, key);
|
||||
tracer_->Get(get_impl_options.column_family, key);
|
||||
}
|
||||
}
|
||||
|
||||
// Acquire SuperVersion
|
||||
SuperVersion* super_version = GetAndRefSuperVersion(cfd);
|
||||
SequenceNumber snapshot = versions_->LastSequence();
|
||||
GetWithTimestampReadCallback read_cb(snapshot);
|
||||
if (read_options.timestamp && read_options.timestamp->size() > 0) {
|
||||
s = FailIfReadCollapsedHistory(cfd, super_version,
|
||||
*(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
ReturnAndCleanupSuperVersion(cfd, super_version);
|
||||
return s;
|
||||
}
|
||||
}
|
||||
MergeContext merge_context;
|
||||
SequenceNumber max_covering_tombstone_seq = 0;
|
||||
Status s;
|
||||
LookupKey lkey(key, snapshot, read_options.timestamp);
|
||||
PERF_TIMER_STOP(get_snapshot_time);
|
||||
|
||||
bool done = false;
|
||||
const Comparator* ucmp = column_family->GetComparator();
|
||||
assert(ucmp);
|
||||
std::string* ts = ucmp->timestamp_size() > 0 ? timestamp : nullptr;
|
||||
if (super_version->mem->Get(lkey, pinnable_val->GetSelf(),
|
||||
/*columns=*/nullptr, ts, &s, &merge_context,
|
||||
&max_covering_tombstone_seq, read_options,
|
||||
false /* immutable_memtable */, &read_cb)) {
|
||||
|
||||
// Look up starts here
|
||||
if (super_version->mem->Get(
|
||||
lkey,
|
||||
get_impl_options.value ? get_impl_options.value->GetSelf() : nullptr,
|
||||
get_impl_options.columns, ts, &s, &merge_context,
|
||||
&max_covering_tombstone_seq, read_options,
|
||||
false /* immutable_memtable */, &read_cb)) {
|
||||
done = true;
|
||||
pinnable_val->PinSelf();
|
||||
if (get_impl_options.value) {
|
||||
get_impl_options.value->PinSelf();
|
||||
}
|
||||
RecordTick(stats_, MEMTABLE_HIT);
|
||||
} else if ((s.ok() || s.IsMergeInProgress()) &&
|
||||
super_version->imm->Get(
|
||||
lkey, pinnable_val->GetSelf(), /*columns=*/nullptr, ts, &s,
|
||||
&merge_context, &max_covering_tombstone_seq, read_options,
|
||||
&read_cb)) {
|
||||
lkey,
|
||||
get_impl_options.value ? get_impl_options.value->GetSelf()
|
||||
: nullptr,
|
||||
get_impl_options.columns, ts, &s, &merge_context,
|
||||
&max_covering_tombstone_seq, read_options, &read_cb)) {
|
||||
done = true;
|
||||
pinnable_val->PinSelf();
|
||||
if (get_impl_options.value) {
|
||||
get_impl_options.value->PinSelf();
|
||||
}
|
||||
RecordTick(stats_, MEMTABLE_HIT);
|
||||
}
|
||||
if (!done && !s.ok() && !s.IsMergeInProgress()) {
|
||||
@@ -448,8 +436,8 @@ Status DBImplSecondary::GetImpl(const ReadOptions& read_options,
|
||||
PERF_TIMER_GUARD(get_from_output_files_time);
|
||||
PinnedIteratorsManager pinned_iters_mgr;
|
||||
super_version->current->Get(
|
||||
read_options, lkey, pinnable_val, /*columns=*/nullptr, ts, &s,
|
||||
&merge_context, &max_covering_tombstone_seq, &pinned_iters_mgr,
|
||||
read_options, lkey, get_impl_options.value, get_impl_options.columns,
|
||||
ts, &s, &merge_context, &max_covering_tombstone_seq, &pinned_iters_mgr,
|
||||
/*value_found*/ nullptr,
|
||||
/*key_exists*/ nullptr, /*seq*/ nullptr, &read_cb, /*is_blob*/ nullptr,
|
||||
/*do_merge*/ true);
|
||||
@@ -459,7 +447,12 @@ Status DBImplSecondary::GetImpl(const ReadOptions& read_options,
|
||||
PERF_TIMER_GUARD(get_post_process_time);
|
||||
ReturnAndCleanupSuperVersion(cfd, super_version);
|
||||
RecordTick(stats_, NUMBER_KEYS_READ);
|
||||
size_t size = pinnable_val->size();
|
||||
size_t size = 0;
|
||||
if (get_impl_options.value) {
|
||||
size = get_impl_options.value->size();
|
||||
} else if (get_impl_options.columns) {
|
||||
size = get_impl_options.columns->serialized_size();
|
||||
}
|
||||
RecordTick(stats_, BYTES_READ, size);
|
||||
RecordTimeToHistogram(stats_, BYTES_PER_READ, size);
|
||||
PERF_COUNTER_ADD(get_read_bytes, size);
|
||||
@@ -491,8 +484,7 @@ Iterator* DBImplSecondary::NewIterator(const ReadOptions& _read_options,
|
||||
assert(column_family);
|
||||
if (read_options.timestamp) {
|
||||
const Status s =
|
||||
FailIfTsMismatchCf(column_family, *(read_options.timestamp),
|
||||
/*ts_for_read=*/true);
|
||||
FailIfTsMismatchCf(column_family, *(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
return NewErrorIterator(s);
|
||||
}
|
||||
@@ -516,17 +508,25 @@ Iterator* DBImplSecondary::NewIterator(const ReadOptions& _read_options,
|
||||
Status::NotSupported("snapshot not supported in secondary mode"));
|
||||
} else {
|
||||
SequenceNumber snapshot(kMaxSequenceNumber);
|
||||
result = NewIteratorImpl(read_options, cfd, snapshot, read_callback);
|
||||
SuperVersion* sv = cfd->GetReferencedSuperVersion(this);
|
||||
if (read_options.timestamp && read_options.timestamp->size() > 0) {
|
||||
const Status s =
|
||||
FailIfReadCollapsedHistory(cfd, sv, *(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
CleanupSuperVersion(sv);
|
||||
return NewErrorIterator(s);
|
||||
}
|
||||
}
|
||||
result = NewIteratorImpl(read_options, cfd, sv, snapshot, read_callback);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
ArenaWrappedDBIter* DBImplSecondary::NewIteratorImpl(
|
||||
const ReadOptions& read_options, ColumnFamilyData* cfd,
|
||||
SequenceNumber snapshot, ReadCallback* read_callback,
|
||||
bool expose_blob_index, bool allow_refresh) {
|
||||
SuperVersion* super_version, SequenceNumber snapshot,
|
||||
ReadCallback* read_callback, bool expose_blob_index, bool allow_refresh) {
|
||||
assert(nullptr != cfd);
|
||||
SuperVersion* super_version = cfd->GetReferencedSuperVersion(this);
|
||||
assert(snapshot == kMaxSequenceNumber);
|
||||
snapshot = versions_->LastSequence();
|
||||
assert(snapshot != kMaxSequenceNumber);
|
||||
@@ -535,7 +535,7 @@ ArenaWrappedDBIter* DBImplSecondary::NewIteratorImpl(
|
||||
super_version->current, snapshot,
|
||||
super_version->mutable_cf_options.max_sequential_skip_in_iterations,
|
||||
super_version->version_number, read_callback, this, cfd,
|
||||
expose_blob_index, read_options.snapshot ? false : allow_refresh);
|
||||
expose_blob_index, allow_refresh);
|
||||
auto internal_iter = NewInternalIterator(
|
||||
db_iter->GetReadOptions(), cfd, super_version, db_iter->GetArena(),
|
||||
snapshot, /* allow_unprepared_value */ true, db_iter);
|
||||
@@ -572,8 +572,7 @@ Status DBImplSecondary::NewIterators(
|
||||
if (read_options.timestamp) {
|
||||
for (auto* cf : column_families) {
|
||||
assert(cf);
|
||||
const Status s = FailIfTsMismatchCf(cf, *(read_options.timestamp),
|
||||
/*ts_for_read=*/true);
|
||||
const Status s = FailIfTsMismatchCf(cf, *(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
@@ -597,10 +596,28 @@ Status DBImplSecondary::NewIterators(
|
||||
return Status::NotSupported("snapshot not supported in secondary mode");
|
||||
} else {
|
||||
SequenceNumber read_seq(kMaxSequenceNumber);
|
||||
autovector<std::tuple<ColumnFamilyData*, SuperVersion*>> cfd_to_sv;
|
||||
const bool check_read_ts =
|
||||
read_options.timestamp && read_options.timestamp->size() > 0;
|
||||
for (auto cfh : column_families) {
|
||||
ColumnFamilyData* cfd = static_cast<ColumnFamilyHandleImpl*>(cfh)->cfd();
|
||||
SuperVersion* sv = cfd->GetReferencedSuperVersion(this);
|
||||
cfd_to_sv.emplace_back(cfd, sv);
|
||||
if (check_read_ts) {
|
||||
const Status s =
|
||||
FailIfReadCollapsedHistory(cfd, sv, *(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
for (auto prev_entry : cfd_to_sv) {
|
||||
CleanupSuperVersion(std::get<1>(prev_entry));
|
||||
}
|
||||
return s;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert(cfd_to_sv.size() == column_families.size());
|
||||
for (auto [cfd, sv] : cfd_to_sv) {
|
||||
iterators->push_back(
|
||||
NewIteratorImpl(read_options, cfd, read_seq, read_callback));
|
||||
NewIteratorImpl(read_options, cfd, sv, read_seq, read_callback));
|
||||
}
|
||||
}
|
||||
return Status::OK();
|
||||
@@ -868,7 +885,7 @@ Status DBImplSecondary::CompactWithoutInstallation(
|
||||
*mutable_cf_options, mutable_db_options_, 0));
|
||||
assert(c != nullptr);
|
||||
|
||||
c->SetInputVersion(version);
|
||||
c->FinalizeInputInfo(version);
|
||||
|
||||
// Create output directory if it's not existed yet
|
||||
std::unique_ptr<FSDirectory> output_dir;
|
||||
|
||||
@@ -85,8 +85,6 @@ class DBImplSecondary : public DBImpl {
|
||||
bool error_if_data_exists_in_wals, uint64_t* = nullptr,
|
||||
RecoveryContext* recovery_ctx = nullptr) override;
|
||||
|
||||
// Implementations of the DB interface.
|
||||
using DB::Get;
|
||||
// Can return IOError due to files being deleted by the primary. To avoid
|
||||
// IOError in this case, application can coordinate between primary and
|
||||
// secondaries so that primary will not delete files that are currently being
|
||||
@@ -96,17 +94,9 @@ class DBImplSecondary : public DBImpl {
|
||||
// workaround, the secondaries can be opened with `max_open_files=-1` so that
|
||||
// it eagerly keeps all talbe files open and is able to access the contents of
|
||||
// deleted files via prior open fd.
|
||||
Status Get(const ReadOptions& _read_options,
|
||||
ColumnFamilyHandle* column_family, const Slice& key,
|
||||
PinnableSlice* value) override;
|
||||
|
||||
Status Get(const ReadOptions& _read_options,
|
||||
ColumnFamilyHandle* column_family, const Slice& key,
|
||||
PinnableSlice* value, std::string* timestamp) override;
|
||||
|
||||
Status GetImpl(const ReadOptions& options, ColumnFamilyHandle* column_family,
|
||||
const Slice& key, PinnableSlice* value,
|
||||
std::string* timestamp);
|
||||
using DBImpl::GetImpl;
|
||||
Status GetImpl(const ReadOptions& options, const Slice& key,
|
||||
GetImplOptions& get_impl_options) override;
|
||||
|
||||
using DBImpl::NewIterator;
|
||||
// Operations on the created iterators can return IOError due to files being
|
||||
@@ -122,7 +112,7 @@ class DBImplSecondary : public DBImpl {
|
||||
ColumnFamilyHandle* column_family) override;
|
||||
|
||||
ArenaWrappedDBIter* NewIteratorImpl(const ReadOptions& read_options,
|
||||
ColumnFamilyData* cfd,
|
||||
ColumnFamilyData* cfd, SuperVersion* sv,
|
||||
SequenceNumber snapshot,
|
||||
ReadCallback* read_callback,
|
||||
bool expose_blob_index = false,
|
||||
|
||||
@@ -30,7 +30,7 @@ Status DBImpl::Put(const WriteOptions& o, ColumnFamilyHandle* column_family,
|
||||
|
||||
Status DBImpl::Put(const WriteOptions& o, ColumnFamilyHandle* column_family,
|
||||
const Slice& key, const Slice& ts, const Slice& val) {
|
||||
const Status s = FailIfTsMismatchCf(column_family, ts, /*ts_for_read=*/false);
|
||||
const Status s = FailIfTsMismatchCf(column_family, ts);
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
@@ -64,7 +64,7 @@ Status DBImpl::Merge(const WriteOptions& o, ColumnFamilyHandle* column_family,
|
||||
|
||||
Status DBImpl::Merge(const WriteOptions& o, ColumnFamilyHandle* column_family,
|
||||
const Slice& key, const Slice& ts, const Slice& val) {
|
||||
const Status s = FailIfTsMismatchCf(column_family, ts, /*ts_for_read=*/false);
|
||||
const Status s = FailIfTsMismatchCf(column_family, ts);
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
@@ -83,7 +83,7 @@ Status DBImpl::Delete(const WriteOptions& write_options,
|
||||
Status DBImpl::Delete(const WriteOptions& write_options,
|
||||
ColumnFamilyHandle* column_family, const Slice& key,
|
||||
const Slice& ts) {
|
||||
const Status s = FailIfTsMismatchCf(column_family, ts, /*ts_for_read=*/false);
|
||||
const Status s = FailIfTsMismatchCf(column_family, ts);
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
@@ -103,7 +103,7 @@ Status DBImpl::SingleDelete(const WriteOptions& write_options,
|
||||
Status DBImpl::SingleDelete(const WriteOptions& write_options,
|
||||
ColumnFamilyHandle* column_family, const Slice& key,
|
||||
const Slice& ts) {
|
||||
const Status s = FailIfTsMismatchCf(column_family, ts, /*ts_for_read=*/false);
|
||||
const Status s = FailIfTsMismatchCf(column_family, ts);
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
@@ -124,7 +124,7 @@ Status DBImpl::DeleteRange(const WriteOptions& write_options,
|
||||
ColumnFamilyHandle* column_family,
|
||||
const Slice& begin_key, const Slice& end_key,
|
||||
const Slice& ts) {
|
||||
const Status s = FailIfTsMismatchCf(column_family, ts, /*ts_for_read=*/false);
|
||||
const Status s = FailIfTsMismatchCf(column_family, ts);
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -34,6 +34,12 @@ void DumpDBFileSummary(const ImmutableDBOptions& options,
|
||||
std::string file_info, wal_info;
|
||||
|
||||
Header(options.info_log, "DB SUMMARY\n");
|
||||
{
|
||||
std::string hostname;
|
||||
if (env->GetHostNameString(&hostname).ok()) {
|
||||
Header(options.info_log, "Host name (Env): %s\n", hostname.c_str());
|
||||
}
|
||||
}
|
||||
Header(options.info_log, "DB Session ID: %s\n", session_id.c_str());
|
||||
|
||||
Status s;
|
||||
|
||||
+83
-55
@@ -18,6 +18,7 @@
|
||||
#include "db/merge_helper.h"
|
||||
#include "db/pinned_iterators_manager.h"
|
||||
#include "db/wide/wide_column_serialization.h"
|
||||
#include "db/wide/wide_columns_helper.h"
|
||||
#include "file/filename.h"
|
||||
#include "logging/logging.h"
|
||||
#include "memory/arena.h"
|
||||
@@ -82,7 +83,8 @@ DBIter::DBIter(Env* _env, const ReadOptions& read_options,
|
||||
cfd_(cfd),
|
||||
timestamp_ub_(read_options.timestamp),
|
||||
timestamp_lb_(read_options.iter_start_ts),
|
||||
timestamp_size_(timestamp_ub_ ? timestamp_ub_->size() : 0) {
|
||||
timestamp_size_(timestamp_ub_ ? timestamp_ub_->size() : 0),
|
||||
auto_readahead_size_(read_options.auto_readahead_size) {
|
||||
RecordTick(statistics_, NO_ITERATOR_CREATED);
|
||||
if (pin_thru_lifetime_) {
|
||||
pinned_iters_mgr_.StartPinning();
|
||||
@@ -230,14 +232,38 @@ bool DBIter::SetValueAndColumnsFromEntity(Slice slice) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!wide_columns_.empty() &&
|
||||
wide_columns_[0].name() == kDefaultWideColumnName) {
|
||||
value_ = wide_columns_[0].value();
|
||||
if (WideColumnsHelper::HasDefaultColumn(wide_columns_)) {
|
||||
value_ = WideColumnsHelper::GetDefaultColumn(wide_columns_);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool DBIter::SetValueAndColumnsFromMergeResult(const Status& merge_status,
|
||||
ValueType result_type) {
|
||||
if (!merge_status.ok()) {
|
||||
valid_ = false;
|
||||
status_ = merge_status;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (result_type == kTypeWideColumnEntity) {
|
||||
if (!SetValueAndColumnsFromEntity(saved_value_)) {
|
||||
assert(!valid_);
|
||||
return false;
|
||||
}
|
||||
|
||||
valid_ = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
assert(result_type == kTypeValue);
|
||||
SetValueAndColumnsFromPlain(pinned_value_.data() ? pinned_value_
|
||||
: saved_value_);
|
||||
valid_ = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
// PRE: saved_key_ has the current user key if skipping_saved_key
|
||||
// POST: saved_key_ should have the next user key if valid_,
|
||||
// if the current entry is a result of merge
|
||||
@@ -554,8 +580,7 @@ bool DBIter::MergeValuesNewToOld() {
|
||||
if (kTypeValue == ikey.type) {
|
||||
// hit a put, merge the put value with operands and store the
|
||||
// final result in saved_value_. We are done!
|
||||
const Slice val = iter_.value();
|
||||
if (!Merge(&val, ikey.user_key)) {
|
||||
if (!MergeWithPlainBaseValue(iter_.value(), ikey.user_key)) {
|
||||
return false;
|
||||
}
|
||||
// iter_ is positioned after put
|
||||
@@ -584,7 +609,7 @@ bool DBIter::MergeValuesNewToOld() {
|
||||
return false;
|
||||
}
|
||||
valid_ = true;
|
||||
if (!Merge(&blob_value_, ikey.user_key)) {
|
||||
if (!MergeWithPlainBaseValue(blob_value_, ikey.user_key)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -598,7 +623,7 @@ bool DBIter::MergeValuesNewToOld() {
|
||||
}
|
||||
return true;
|
||||
} else if (kTypeWideColumnEntity == ikey.type) {
|
||||
if (!MergeEntity(iter_.value(), ikey.user_key)) {
|
||||
if (!MergeWithWideColumnBaseValue(iter_.value(), ikey.user_key)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -628,7 +653,7 @@ bool DBIter::MergeValuesNewToOld() {
|
||||
// a deletion marker.
|
||||
// feed null as the existing value to the merge operator, such that
|
||||
// client can differentiate this scenario and do things accordingly.
|
||||
if (!Merge(nullptr, saved_key_.GetUserKey())) {
|
||||
if (!MergeWithNoBaseValue(saved_key_.GetUserKey())) {
|
||||
return false;
|
||||
}
|
||||
assert(status_.ok());
|
||||
@@ -719,15 +744,22 @@ bool DBIter::ReverseToBackward() {
|
||||
// When current_entry_is_merged_ is true, iter_ may be positioned on the next
|
||||
// key, which may not exist or may have prefix different from current.
|
||||
// If that's the case, seek to saved_key_.
|
||||
if (current_entry_is_merged_ &&
|
||||
(!expect_total_order_inner_iter() || !iter_.Valid())) {
|
||||
//
|
||||
// In case of auto_readahead_size enabled, index_iter moves forward during
|
||||
// forward scan for block cache lookup and points to different block. If Prev
|
||||
// op is called, it needs to call SeekForPrev to point to right index_iter_ in
|
||||
// BlockBasedTableIterator. This only happens when direction is changed from
|
||||
// forward to backward.
|
||||
if ((current_entry_is_merged_ &&
|
||||
(!expect_total_order_inner_iter() || !iter_.Valid())) ||
|
||||
auto_readahead_size_) {
|
||||
IterKey last_key;
|
||||
// Using kMaxSequenceNumber and kValueTypeForSeek
|
||||
// (not kValueTypeForSeekForPrev) to seek to a key strictly smaller
|
||||
// than saved_key_.
|
||||
last_key.SetInternalKey(ParsedInternalKey(
|
||||
saved_key_.GetUserKey(), kMaxSequenceNumber, kValueTypeForSeek));
|
||||
if (!expect_total_order_inner_iter()) {
|
||||
if (!expect_total_order_inner_iter() || auto_readahead_size_) {
|
||||
iter_.SeekForPrev(last_key.GetInternalKey());
|
||||
} else {
|
||||
// Some iterators may not support SeekForPrev(), so we avoid using it
|
||||
@@ -979,7 +1011,7 @@ bool DBIter::FindValueForCurrentKey() {
|
||||
if (last_not_merge_type == kTypeDeletion ||
|
||||
last_not_merge_type == kTypeSingleDeletion ||
|
||||
last_not_merge_type == kTypeDeletionWithTimestamp) {
|
||||
if (!Merge(nullptr, saved_key_.GetUserKey())) {
|
||||
if (!MergeWithNoBaseValue(saved_key_.GetUserKey())) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@@ -994,7 +1026,7 @@ bool DBIter::FindValueForCurrentKey() {
|
||||
return false;
|
||||
}
|
||||
valid_ = true;
|
||||
if (!Merge(&blob_value_, saved_key_.GetUserKey())) {
|
||||
if (!MergeWithPlainBaseValue(blob_value_, saved_key_.GetUserKey())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1002,14 +1034,15 @@ bool DBIter::FindValueForCurrentKey() {
|
||||
|
||||
return true;
|
||||
} else if (last_not_merge_type == kTypeWideColumnEntity) {
|
||||
if (!MergeEntity(pinned_value_, saved_key_.GetUserKey())) {
|
||||
if (!MergeWithWideColumnBaseValue(pinned_value_,
|
||||
saved_key_.GetUserKey())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
} else {
|
||||
assert(last_not_merge_type == kTypeValue);
|
||||
if (!Merge(&pinned_value_, saved_key_.GetUserKey())) {
|
||||
if (!MergeWithPlainBaseValue(pinned_value_, saved_key_.GetUserKey())) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@@ -1185,8 +1218,7 @@ bool DBIter::FindValueForCurrentKeyUsingSeek() {
|
||||
}
|
||||
|
||||
if (ikey.type == kTypeValue) {
|
||||
const Slice val = iter_.value();
|
||||
if (!Merge(&val, saved_key_.GetUserKey())) {
|
||||
if (!MergeWithPlainBaseValue(iter_.value(), saved_key_.GetUserKey())) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@@ -1205,7 +1237,7 @@ bool DBIter::FindValueForCurrentKeyUsingSeek() {
|
||||
return false;
|
||||
}
|
||||
valid_ = true;
|
||||
if (!Merge(&blob_value_, saved_key_.GetUserKey())) {
|
||||
if (!MergeWithPlainBaseValue(blob_value_, saved_key_.GetUserKey())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1213,7 +1245,8 @@ bool DBIter::FindValueForCurrentKeyUsingSeek() {
|
||||
|
||||
return true;
|
||||
} else if (ikey.type == kTypeWideColumnEntity) {
|
||||
if (!MergeEntity(iter_.value(), saved_key_.GetUserKey())) {
|
||||
if (!MergeWithWideColumnBaseValue(iter_.value(),
|
||||
saved_key_.GetUserKey())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1227,7 +1260,7 @@ bool DBIter::FindValueForCurrentKeyUsingSeek() {
|
||||
}
|
||||
}
|
||||
|
||||
if (!Merge(nullptr, saved_key_.GetUserKey())) {
|
||||
if (!MergeWithNoBaseValue(saved_key_.GetUserKey())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1250,47 +1283,42 @@ bool DBIter::FindValueForCurrentKeyUsingSeek() {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool DBIter::Merge(const Slice* val, const Slice& user_key) {
|
||||
bool DBIter::MergeWithNoBaseValue(const Slice& user_key) {
|
||||
// `op_failure_scope` (an output parameter) is not provided (set to nullptr)
|
||||
// since a failure must be propagated regardless of its value.
|
||||
Status s = MergeHelper::TimedFullMerge(
|
||||
merge_operator_, user_key, val, merge_context_.GetOperands(),
|
||||
&saved_value_, logger_, statistics_, clock_, &pinned_value_,
|
||||
/* update_num_ops_stats */ true,
|
||||
/* op_failure_scope */ nullptr);
|
||||
if (!s.ok()) {
|
||||
valid_ = false;
|
||||
status_ = s;
|
||||
return false;
|
||||
}
|
||||
|
||||
SetValueAndColumnsFromPlain(pinned_value_.data() ? pinned_value_
|
||||
: saved_value_);
|
||||
|
||||
valid_ = true;
|
||||
return true;
|
||||
ValueType result_type;
|
||||
const Status s = MergeHelper::TimedFullMerge(
|
||||
merge_operator_, user_key, MergeHelper::kNoBaseValue,
|
||||
merge_context_.GetOperands(), logger_, statistics_, clock_,
|
||||
/* update_num_ops_stats */ true, &saved_value_, &pinned_value_,
|
||||
&result_type, /* op_failure_scope */ nullptr);
|
||||
return SetValueAndColumnsFromMergeResult(s, result_type);
|
||||
}
|
||||
|
||||
bool DBIter::MergeEntity(const Slice& entity, const Slice& user_key) {
|
||||
bool DBIter::MergeWithPlainBaseValue(const Slice& value,
|
||||
const Slice& user_key) {
|
||||
// `op_failure_scope` (an output parameter) is not provided (set to nullptr)
|
||||
// since a failure must be propagated regardless of its value.
|
||||
Status s = MergeHelper::TimedFullMergeWithEntity(
|
||||
merge_operator_, user_key, entity, merge_context_.GetOperands(),
|
||||
&saved_value_, logger_, statistics_, clock_,
|
||||
/* update_num_ops_stats */ true,
|
||||
/* op_failure_scope */ nullptr);
|
||||
if (!s.ok()) {
|
||||
valid_ = false;
|
||||
status_ = s;
|
||||
return false;
|
||||
}
|
||||
ValueType result_type;
|
||||
const Status s = MergeHelper::TimedFullMerge(
|
||||
merge_operator_, user_key, MergeHelper::kPlainBaseValue, value,
|
||||
merge_context_.GetOperands(), logger_, statistics_, clock_,
|
||||
/* update_num_ops_stats */ true, &saved_value_, &pinned_value_,
|
||||
&result_type, /* op_failure_scope */ nullptr);
|
||||
return SetValueAndColumnsFromMergeResult(s, result_type);
|
||||
}
|
||||
|
||||
if (!SetValueAndColumnsFromEntity(saved_value_)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
valid_ = true;
|
||||
return true;
|
||||
bool DBIter::MergeWithWideColumnBaseValue(const Slice& entity,
|
||||
const Slice& user_key) {
|
||||
// `op_failure_scope` (an output parameter) is not provided (set to nullptr)
|
||||
// since a failure must be propagated regardless of its value.
|
||||
ValueType result_type;
|
||||
const Status s = MergeHelper::TimedFullMerge(
|
||||
merge_operator_, user_key, MergeHelper::kWideBaseValue, entity,
|
||||
merge_context_.GetOperands(), logger_, statistics_, clock_,
|
||||
/* update_num_ops_stats */ true, &saved_value_, &pinned_value_,
|
||||
&result_type, /* op_failure_scope */ nullptr);
|
||||
return SetValueAndColumnsFromMergeResult(s, result_type);
|
||||
}
|
||||
|
||||
// Move backwards until the key smaller than saved_key_.
|
||||
|
||||
+10
-2
@@ -209,6 +209,7 @@ class DBIter final : public Iterator {
|
||||
if (read_callback_) {
|
||||
read_callback_->Refresh(s);
|
||||
}
|
||||
iter_.SetRangeDelReadSeqno(s);
|
||||
}
|
||||
void set_valid(bool v) { valid_ = v; }
|
||||
|
||||
@@ -312,14 +313,20 @@ class DBIter final : public Iterator {
|
||||
|
||||
bool SetValueAndColumnsFromEntity(Slice slice);
|
||||
|
||||
bool SetValueAndColumnsFromMergeResult(const Status& merge_status,
|
||||
ValueType result_type);
|
||||
|
||||
void ResetValueAndColumns() {
|
||||
value_.clear();
|
||||
wide_columns_.clear();
|
||||
}
|
||||
|
||||
// The following methods perform the actual merge operation for the
|
||||
// no base value/plain base value/wide-column base value cases.
|
||||
// If user-defined timestamp is enabled, `user_key` includes timestamp.
|
||||
bool Merge(const Slice* val, const Slice& user_key);
|
||||
bool MergeEntity(const Slice& entity, const Slice& user_key);
|
||||
bool MergeWithNoBaseValue(const Slice& user_key);
|
||||
bool MergeWithPlainBaseValue(const Slice& value, const Slice& user_key);
|
||||
bool MergeWithWideColumnBaseValue(const Slice& entity, const Slice& user_key);
|
||||
|
||||
const SliceTransform* prefix_extractor_;
|
||||
Env* const env_;
|
||||
@@ -395,6 +402,7 @@ class DBIter final : public Iterator {
|
||||
const Slice* const timestamp_lb_;
|
||||
const size_t timestamp_size_;
|
||||
std::string saved_timestamp_;
|
||||
bool auto_readahead_size_;
|
||||
};
|
||||
|
||||
// Return a new iterator that converts internal keys (yielded by
|
||||
|
||||
+257
-20
@@ -107,7 +107,10 @@ class DBIteratorTest : public DBIteratorBaseTest,
|
||||
read_callbacks_.push_back(
|
||||
std::unique_ptr<DummyReadCallback>(read_callback));
|
||||
}
|
||||
return dbfull()->NewIteratorImpl(read_options, cfd, seq, read_callback);
|
||||
DBImpl* db_impl = dbfull();
|
||||
SuperVersion* super_version = cfd->GetReferencedSuperVersion(db_impl);
|
||||
return db_impl->NewIteratorImpl(read_options, cfd, super_version, seq,
|
||||
read_callback);
|
||||
}
|
||||
|
||||
private:
|
||||
@@ -2418,32 +2421,92 @@ TEST_P(DBIteratorTest, Refresh) {
|
||||
}
|
||||
|
||||
TEST_P(DBIteratorTest, RefreshWithSnapshot) {
|
||||
ASSERT_OK(Put("x", "y"));
|
||||
// L1 file, uses LevelIterator internally
|
||||
ASSERT_OK(Put(Key(0), "val0"));
|
||||
ASSERT_OK(Put(Key(5), "val5"));
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(1);
|
||||
|
||||
// L0 file, uses table iterator internally
|
||||
ASSERT_OK(Put(Key(1), "val1"));
|
||||
ASSERT_OK(Put(Key(4), "val4"));
|
||||
ASSERT_OK(Flush());
|
||||
|
||||
// Memtable
|
||||
ASSERT_OK(Put(Key(2), "val2"));
|
||||
ASSERT_OK(Put(Key(3), "val3"));
|
||||
const Snapshot* snapshot = db_->GetSnapshot();
|
||||
ASSERT_OK(Put(Key(2), "new val"));
|
||||
ASSERT_OK(db_->DeleteRange(WriteOptions(), db_->DefaultColumnFamily(), Key(4),
|
||||
Key(7)));
|
||||
const Snapshot* snapshot2 = db_->GetSnapshot();
|
||||
|
||||
ASSERT_EQ(1, NumTableFilesAtLevel(1));
|
||||
ASSERT_EQ(1, NumTableFilesAtLevel(0));
|
||||
|
||||
ReadOptions options;
|
||||
options.snapshot = snapshot;
|
||||
Iterator* iter = NewIterator(options);
|
||||
ASSERT_OK(Put(Key(6), "val6"));
|
||||
ASSERT_OK(iter->status());
|
||||
|
||||
iter->Seek(Slice("a"));
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_EQ(iter->key().compare(Slice("x")), 0);
|
||||
iter->Next();
|
||||
ASSERT_FALSE(iter->Valid());
|
||||
auto verify_iter = [&](int start, int end, bool new_key2 = false) {
|
||||
for (int i = start; i < end; ++i) {
|
||||
ASSERT_OK(iter->status());
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_EQ(iter->key(), Key(i));
|
||||
if (i == 2 && new_key2) {
|
||||
ASSERT_EQ(iter->value(), "new val");
|
||||
} else {
|
||||
ASSERT_EQ(iter->value(), "val" + std::to_string(i));
|
||||
}
|
||||
iter->Next();
|
||||
}
|
||||
};
|
||||
|
||||
ASSERT_OK(Put("c", "d"));
|
||||
for (int j = 0; j < 2; j++) {
|
||||
iter->Seek(Key(1));
|
||||
verify_iter(1, 3);
|
||||
// Refresh to same snapshot
|
||||
ASSERT_OK(iter->Refresh(snapshot));
|
||||
ASSERT_TRUE(iter->status().ok() && !iter->Valid());
|
||||
iter->Seek(Key(3));
|
||||
verify_iter(3, 6);
|
||||
ASSERT_TRUE(iter->status().ok() && !iter->Valid());
|
||||
|
||||
iter->Seek(Slice("a"));
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_EQ(iter->key().compare(Slice("x")), 0);
|
||||
iter->Next();
|
||||
ASSERT_FALSE(iter->Valid());
|
||||
// Refresh to a newer snapshot
|
||||
ASSERT_OK(iter->Refresh(snapshot2));
|
||||
ASSERT_TRUE(iter->status().ok() && !iter->Valid());
|
||||
iter->SeekToFirst();
|
||||
verify_iter(0, 4, /*new_key2=*/true);
|
||||
ASSERT_TRUE(iter->status().ok() && !iter->Valid());
|
||||
|
||||
// Refresh to an older snapshot
|
||||
ASSERT_OK(iter->Refresh(snapshot));
|
||||
ASSERT_TRUE(iter->status().ok() && !iter->Valid());
|
||||
iter->Seek(Key(3));
|
||||
verify_iter(3, 6);
|
||||
ASSERT_TRUE(iter->status().ok() && !iter->Valid());
|
||||
|
||||
// Refresh to no snapshot
|
||||
ASSERT_OK(iter->Refresh());
|
||||
ASSERT_TRUE(iter->status().ok() && !iter->Valid());
|
||||
iter->Seek(Key(2));
|
||||
verify_iter(2, 4, /*new_key2=*/true);
|
||||
verify_iter(6, 7);
|
||||
ASSERT_TRUE(iter->status().ok() && !iter->Valid());
|
||||
|
||||
// Change LSM shape, new SuperVersion is created.
|
||||
ASSERT_OK(Flush());
|
||||
|
||||
// Refresh back to original snapshot
|
||||
ASSERT_OK(iter->Refresh(snapshot));
|
||||
}
|
||||
|
||||
ASSERT_OK(iter->status());
|
||||
Status s = iter->Refresh();
|
||||
ASSERT_TRUE(s.IsNotSupported());
|
||||
db_->ReleaseSnapshot(snapshot);
|
||||
delete iter;
|
||||
db_->ReleaseSnapshot(snapshot);
|
||||
db_->ReleaseSnapshot(snapshot2);
|
||||
ASSERT_OK(db_->Close());
|
||||
}
|
||||
|
||||
TEST_P(DBIteratorTest, CreationFailure) {
|
||||
@@ -3130,8 +3193,10 @@ TEST_F(DBIteratorWithReadCallbackTest, ReadCallback) {
|
||||
static_cast_with_check<ColumnFamilyHandleImpl>(db_->DefaultColumnFamily())
|
||||
->cfd();
|
||||
// The iterator are suppose to see data before seq1.
|
||||
Iterator* iter =
|
||||
dbfull()->NewIteratorImpl(ReadOptions(), cfd, seq2, &callback1);
|
||||
DBImpl* db_impl = dbfull();
|
||||
SuperVersion* super_version = cfd->GetReferencedSuperVersion(db_impl);
|
||||
Iterator* iter = db_impl->NewIteratorImpl(ReadOptions(), cfd, super_version,
|
||||
seq2, &callback1);
|
||||
|
||||
// Seek
|
||||
// The latest value of "foo" before seq1 is "v3"
|
||||
@@ -3209,7 +3274,9 @@ TEST_F(DBIteratorWithReadCallbackTest, ReadCallback) {
|
||||
SequenceNumber seq4 = db_->GetLatestSequenceNumber();
|
||||
|
||||
// The iterator is suppose to see data before seq3.
|
||||
iter = dbfull()->NewIteratorImpl(ReadOptions(), cfd, seq4, &callback2);
|
||||
super_version = cfd->GetReferencedSuperVersion(db_impl);
|
||||
iter = db_impl->NewIteratorImpl(ReadOptions(), cfd, super_version, seq4,
|
||||
&callback2);
|
||||
// Seek to "z", which is visible.
|
||||
iter->Seek("z");
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
@@ -3295,6 +3362,176 @@ TEST_F(DBIteratorTest, IteratorRefreshReturnSV) {
|
||||
Close();
|
||||
}
|
||||
|
||||
TEST_F(DBIteratorTest, ErrorWhenReadFile) {
|
||||
// This is to test a bug that is fixed in
|
||||
// https://github.com/facebook/rocksdb/pull/11782.
|
||||
//
|
||||
// Ingest error when reading from a file, and
|
||||
// see if Iterator handles it correctly.
|
||||
Options opts = CurrentOptions();
|
||||
opts.num_levels = 7;
|
||||
opts.compression = kNoCompression;
|
||||
BlockBasedTableOptions bbto;
|
||||
// Always do I/O
|
||||
bbto.no_block_cache = true;
|
||||
opts.table_factory.reset(NewBlockBasedTableFactory(bbto));
|
||||
DestroyAndReopen(opts);
|
||||
|
||||
// Set up LSM
|
||||
// L5: F1 [key0, key99], F2 [key100, key199]
|
||||
// L6: F3 [key50, key149]
|
||||
Random rnd(301);
|
||||
const int kValLen = 100;
|
||||
for (int i = 50; i < 150; ++i) {
|
||||
ASSERT_OK(Put(Key(i), rnd.RandomString(kValLen)));
|
||||
}
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(6);
|
||||
|
||||
std::vector<std::string> values;
|
||||
for (int i = 0; i < 100; ++i) {
|
||||
values.emplace_back(rnd.RandomString(kValLen));
|
||||
ASSERT_OK(Put(Key(i), values.back()));
|
||||
}
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(5);
|
||||
|
||||
for (int i = 100; i < 200; ++i) {
|
||||
values.emplace_back(rnd.RandomString(kValLen));
|
||||
ASSERT_OK(Put(Key(i), values.back()));
|
||||
}
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(5);
|
||||
|
||||
ASSERT_EQ(2, NumTableFilesAtLevel(5));
|
||||
ASSERT_EQ(1, NumTableFilesAtLevel(6));
|
||||
|
||||
std::vector<LiveFileMetaData> files;
|
||||
db_->GetLiveFilesMetaData(&files);
|
||||
// Get file names for F1, F2 and F3.
|
||||
// These are file names, not full paths.
|
||||
std::string f1, f2, f3;
|
||||
for (auto& file_meta : files) {
|
||||
if (file_meta.level == 6) {
|
||||
f3 = file_meta.name;
|
||||
} else {
|
||||
if (file_meta.smallestkey == Key(0)) {
|
||||
f1 = file_meta.name;
|
||||
} else {
|
||||
f2 = file_meta.name;
|
||||
}
|
||||
}
|
||||
}
|
||||
ASSERT_TRUE(!f1.empty());
|
||||
ASSERT_TRUE(!f2.empty());
|
||||
ASSERT_TRUE(!f3.empty());
|
||||
|
||||
std::string error_file;
|
||||
SyncPoint::GetInstance()->SetCallBack(
|
||||
"RandomAccessFileReader::Read::BeforeReturn",
|
||||
[&error_file](void* io_s_ptr) {
|
||||
auto p =
|
||||
reinterpret_cast<std::pair<std::string*, IOStatus*>*>(io_s_ptr);
|
||||
if (p->first->find(error_file) != std::string::npos) {
|
||||
*p->second = IOStatus::IOError();
|
||||
p->second->SetRetryable(true);
|
||||
}
|
||||
});
|
||||
SyncPoint::GetInstance()->EnableProcessing();
|
||||
// Error reading F1
|
||||
error_file = f1;
|
||||
std::unique_ptr<Iterator> iter{db_->NewIterator(ReadOptions())};
|
||||
iter->SeekToFirst();
|
||||
ASSERT_NOK(iter->status());
|
||||
ASSERT_TRUE(iter->status().IsIOError());
|
||||
// This does not require reading the first block.
|
||||
iter->Seek(Key(90));
|
||||
ASSERT_OK(iter->status());
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_EQ(iter->value(), values[90]);
|
||||
// iter has ok status before this Seek.
|
||||
iter->Seek(Key(1));
|
||||
ASSERT_NOK(iter->status());
|
||||
ASSERT_TRUE(iter->status().IsIOError());
|
||||
|
||||
// Error reading F2
|
||||
error_file = f2;
|
||||
iter.reset(db_->NewIterator(ReadOptions()));
|
||||
iter->Seek(Key(99));
|
||||
ASSERT_OK(iter->status());
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_EQ(iter->value(), values[99]);
|
||||
// Need to read from F2.
|
||||
iter->Next();
|
||||
ASSERT_NOK(iter->status());
|
||||
ASSERT_TRUE(iter->status().IsIOError());
|
||||
iter->Seek(Key(190));
|
||||
ASSERT_OK(iter->status());
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_EQ(iter->value(), values[190]);
|
||||
// Seek for first key of F2.
|
||||
iter->Seek(Key(100));
|
||||
ASSERT_NOK(iter->status());
|
||||
ASSERT_TRUE(iter->status().IsIOError());
|
||||
iter->SeekToLast();
|
||||
ASSERT_OK(iter->status());
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_EQ(iter->value(), values[199]);
|
||||
// SeekForPrev for first key of F2.
|
||||
iter->SeekForPrev(Key(100));
|
||||
ASSERT_NOK(iter->status());
|
||||
ASSERT_TRUE(iter->status().IsIOError());
|
||||
// Does not read first block (offset 0).
|
||||
iter->SeekForPrev(Key(98));
|
||||
ASSERT_OK(iter->status());
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_EQ(iter->value(), values[98]);
|
||||
|
||||
// Error reading F3
|
||||
error_file = f3;
|
||||
iter.reset(db_->NewIterator(ReadOptions()));
|
||||
iter->SeekToFirst();
|
||||
ASSERT_NOK(iter->status());
|
||||
ASSERT_TRUE(iter->status().IsIOError());
|
||||
iter->Seek(Key(50));
|
||||
ASSERT_NOK(iter->status());
|
||||
ASSERT_TRUE(iter->status().IsIOError());
|
||||
iter->SeekForPrev(Key(50));
|
||||
ASSERT_NOK(iter->status());
|
||||
ASSERT_TRUE(iter->status().IsIOError());
|
||||
// Does not read file 3
|
||||
iter->Seek(Key(150));
|
||||
ASSERT_OK(iter->status());
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_EQ(iter->value(), values[150]);
|
||||
|
||||
// Test when file read error occurs during Prev().
|
||||
// This requires returning an error when reading near the end of a file
|
||||
// instead of offset 0.
|
||||
SyncPoint::GetInstance()->ClearAllCallBacks();
|
||||
SyncPoint::GetInstance()->SetCallBack(
|
||||
"RandomAccessFileReader::Read::AnyOffset", [&f1](void* pair_ptr) {
|
||||
auto p =
|
||||
reinterpret_cast<std::pair<std::string*, IOStatus*>*>(pair_ptr);
|
||||
if (p->first->find(f1) != std::string::npos) {
|
||||
*p->second = IOStatus::IOError();
|
||||
p->second->SetRetryable(true);
|
||||
}
|
||||
});
|
||||
iter->SeekForPrev(Key(101));
|
||||
ASSERT_OK(iter->status());
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_EQ(iter->value(), values[101]);
|
||||
// DBIter will not stop at Key(100) since it needs
|
||||
// to make sure the key it returns has the max sequence number for Key(100).
|
||||
// So it will call MergingIterator::Prev() which will read F1.
|
||||
iter->Prev();
|
||||
ASSERT_NOK(iter->status());
|
||||
ASSERT_TRUE(iter->status().IsIOError());
|
||||
SyncPoint::GetInstance()->DisableProcessing();
|
||||
iter->Reset();
|
||||
}
|
||||
|
||||
} // namespace ROCKSDB_NAMESPACE
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
|
||||
@@ -145,6 +145,41 @@ TEST_F(DBTestXactLogIterator, TransactionLogIteratorRace) {
|
||||
} while (ChangeCompactOptions());
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(DBTestXactLogIterator, TransactionLogIteratorCheckWhenArchive) {
|
||||
do {
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearTrace();
|
||||
Options options = OptionsForLogIterTest();
|
||||
DestroyAndReopen(options);
|
||||
ColumnFamilyHandle* cf;
|
||||
auto s = dbfull()->CreateColumnFamily(ColumnFamilyOptions(), "CF", &cf);
|
||||
ASSERT_TRUE(s.ok());
|
||||
|
||||
ASSERT_OK(dbfull()->Put(WriteOptions(), cf, "key1", DummyString(1024)));
|
||||
|
||||
ASSERT_OK(dbfull()->Put(WriteOptions(), "key2", DummyString(1024)));
|
||||
|
||||
ASSERT_OK(dbfull()->Flush(FlushOptions()));
|
||||
|
||||
ASSERT_OK(dbfull()->Put(WriteOptions(), "key3", DummyString(1024)));
|
||||
|
||||
ASSERT_OK(dbfull()->Flush(FlushOptions()));
|
||||
|
||||
ASSERT_OK(dbfull()->Put(WriteOptions(), "key4", DummyString(1024)));
|
||||
ASSERT_OK(dbfull()->Flush(FlushOptions()));
|
||||
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
|
||||
"WalManager::PurgeObsoleteFiles:1", [&](void*) {
|
||||
auto iter = OpenTransactionLogIter(0);
|
||||
ExpectRecords(4, iter);
|
||||
});
|
||||
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
|
||||
ASSERT_OK(dbfull()->Flush(FlushOptions(), cf));
|
||||
|
||||
delete cf;
|
||||
} while (ChangeCompactOptions());
|
||||
}
|
||||
#endif
|
||||
|
||||
TEST_F(DBTestXactLogIterator, TransactionLogIteratorStallAtLastRecord) {
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#include "db/forward_iterator.h"
|
||||
#include "port/stack_trace.h"
|
||||
#include "rocksdb/merge_operator.h"
|
||||
#include "rocksdb/snapshot.h"
|
||||
#include "util/random.h"
|
||||
#include "utilities/merge_operators.h"
|
||||
#include "utilities/merge_operators/string_append/stringappend2.h"
|
||||
@@ -202,7 +203,6 @@ TEST_F(DBMergeOperatorTest, MergeErrorOnIteration) {
|
||||
VerifyDBInternal({{"k1", "v1"}, {"k2", "corrupted"}, {"k2", "v2"}});
|
||||
}
|
||||
|
||||
|
||||
TEST_F(DBMergeOperatorTest, MergeOperatorFailsWithMustMerge) {
|
||||
// This is like a mini-stress test dedicated to `OpFailureScope::kMustMerge`.
|
||||
// Some or most of it might be deleted upon adding that option to the actual
|
||||
@@ -358,6 +358,98 @@ TEST_F(DBMergeOperatorTest, MergeOperatorFailsWithMustMerge) {
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(DBMergeOperatorTest, MergeOperandThresholdExceeded) {
|
||||
Options options = CurrentOptions();
|
||||
options.create_if_missing = true;
|
||||
options.merge_operator = MergeOperators::CreatePutOperator();
|
||||
options.env = env_;
|
||||
Reopen(options);
|
||||
|
||||
std::vector<Slice> keys{"foo", "bar", "baz"};
|
||||
|
||||
// Write base values.
|
||||
for (const auto& key : keys) {
|
||||
ASSERT_OK(Put(key, key.ToString() + "0"));
|
||||
}
|
||||
|
||||
// Write merge operands. Note that the first key has 1 merge operand, the
|
||||
// second one has 2 merge operands, and the third one has 3 merge operands.
|
||||
// Also, we'll take some snapshots to make sure the merge operands are
|
||||
// preserved during flush.
|
||||
std::vector<ManagedSnapshot> snapshots;
|
||||
snapshots.reserve(3);
|
||||
|
||||
for (size_t i = 0; i < keys.size(); ++i) {
|
||||
snapshots.emplace_back(db_);
|
||||
|
||||
const std::string suffix = std::to_string(i + 1);
|
||||
|
||||
for (size_t j = i; j < keys.size(); ++j) {
|
||||
ASSERT_OK(Merge(keys[j], keys[j].ToString() + suffix));
|
||||
}
|
||||
}
|
||||
|
||||
// Verify the results and status codes of various types of point lookups.
|
||||
auto verify = [&](const std::optional<size_t>& threshold) {
|
||||
ReadOptions read_options;
|
||||
read_options.merge_operand_count_threshold = threshold;
|
||||
|
||||
// Check Get()
|
||||
{
|
||||
for (size_t i = 0; i < keys.size(); ++i) {
|
||||
PinnableSlice value;
|
||||
const Status status =
|
||||
db_->Get(read_options, db_->DefaultColumnFamily(), keys[i], &value);
|
||||
ASSERT_OK(status);
|
||||
ASSERT_EQ(status.IsOkMergeOperandThresholdExceeded(),
|
||||
threshold.has_value() && i + 1 > threshold.value());
|
||||
ASSERT_EQ(value, keys[i].ToString() + std::to_string(i + 1));
|
||||
}
|
||||
}
|
||||
|
||||
// Check old-style MultiGet()
|
||||
{
|
||||
std::vector<std::string> values;
|
||||
std::vector<Status> statuses = db_->MultiGet(read_options, keys, &values);
|
||||
|
||||
for (size_t i = 0; i < keys.size(); ++i) {
|
||||
ASSERT_OK(statuses[i]);
|
||||
ASSERT_EQ(statuses[i].IsOkMergeOperandThresholdExceeded(),
|
||||
threshold.has_value() && i + 1 > threshold.value());
|
||||
ASSERT_EQ(values[i], keys[i].ToString() + std::to_string(i + 1));
|
||||
}
|
||||
}
|
||||
|
||||
// Check batched MultiGet()
|
||||
{
|
||||
std::vector<PinnableSlice> values(keys.size());
|
||||
std::vector<Status> statuses(keys.size());
|
||||
db_->MultiGet(read_options, db_->DefaultColumnFamily(), keys.size(),
|
||||
keys.data(), values.data(), statuses.data());
|
||||
|
||||
for (size_t i = 0; i < keys.size(); ++i) {
|
||||
ASSERT_OK(statuses[i]);
|
||||
ASSERT_EQ(statuses[i].IsOkMergeOperandThresholdExceeded(),
|
||||
threshold.has_value() && i + 1 > threshold.value());
|
||||
ASSERT_EQ(values[i], keys[i].ToString() + std::to_string(i + 1));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Test the case when the feature is disabled as well as various thresholds.
|
||||
verify(std::nullopt);
|
||||
for (size_t i = 0; i < 5; ++i) {
|
||||
verify(i);
|
||||
}
|
||||
|
||||
// Flush and try again to test the case when results are served from SSTs.
|
||||
ASSERT_OK(Flush());
|
||||
verify(std::nullopt);
|
||||
for (size_t i = 0; i < 5; ++i) {
|
||||
verify(i);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(DBMergeOperatorTest, DataBlockBinaryAndHash) {
|
||||
// Basic test to check that merge operator works with data block index type
|
||||
// DataBlockBinaryAndHash.
|
||||
|
||||
+28
-21
@@ -1034,30 +1034,37 @@ TEST_F(DBOptionsTest, SetFIFOCompactionOptions) {
|
||||
}
|
||||
|
||||
TEST_F(DBOptionsTest, CompactionReadaheadSizeChange) {
|
||||
SpecialEnv env(env_);
|
||||
Options options;
|
||||
options.env = &env;
|
||||
for (bool use_direct_reads : {true, false}) {
|
||||
SpecialEnv env(env_);
|
||||
Options options;
|
||||
options.env = &env;
|
||||
|
||||
options.compaction_readahead_size = 0;
|
||||
options.level0_file_num_compaction_trigger = 2;
|
||||
const std::string kValue(1024, 'v');
|
||||
Reopen(options);
|
||||
options.use_direct_reads = use_direct_reads;
|
||||
options.level0_file_num_compaction_trigger = 2;
|
||||
const std::string kValue(1024, 'v');
|
||||
Status s = TryReopen(options);
|
||||
if (use_direct_reads && (s.IsNotSupported() || s.IsInvalidArgument())) {
|
||||
continue;
|
||||
} else {
|
||||
ASSERT_OK(s);
|
||||
}
|
||||
|
||||
ASSERT_EQ(1024 * 1024 * 2,
|
||||
dbfull()->GetDBOptions().compaction_readahead_size);
|
||||
ASSERT_OK(dbfull()->SetDBOptions({{"compaction_readahead_size", "256"}}));
|
||||
ASSERT_EQ(256, dbfull()->GetDBOptions().compaction_readahead_size);
|
||||
for (int i = 0; i < 1024; i++) {
|
||||
ASSERT_OK(Put(Key(i), kValue));
|
||||
ASSERT_EQ(1024 * 1024 * 2,
|
||||
dbfull()->GetDBOptions().compaction_readahead_size);
|
||||
ASSERT_OK(dbfull()->SetDBOptions({{"compaction_readahead_size", "256"}}));
|
||||
ASSERT_EQ(256, dbfull()->GetDBOptions().compaction_readahead_size);
|
||||
for (int i = 0; i < 1024; i++) {
|
||||
ASSERT_OK(Put(Key(i), kValue));
|
||||
}
|
||||
ASSERT_OK(Flush());
|
||||
for (int i = 0; i < 1024 * 2; i++) {
|
||||
ASSERT_OK(Put(Key(i), kValue));
|
||||
}
|
||||
ASSERT_OK(Flush());
|
||||
ASSERT_OK(dbfull()->TEST_WaitForCompact());
|
||||
ASSERT_EQ(256, env_->compaction_readahead_size_);
|
||||
Close();
|
||||
}
|
||||
ASSERT_OK(Flush());
|
||||
for (int i = 0; i < 1024 * 2; i++) {
|
||||
ASSERT_OK(Put(Key(i), kValue));
|
||||
}
|
||||
ASSERT_OK(Flush());
|
||||
ASSERT_OK(dbfull()->TEST_WaitForCompact());
|
||||
ASSERT_EQ(256, env_->compaction_readahead_size_);
|
||||
Close();
|
||||
}
|
||||
|
||||
TEST_F(DBOptionsTest, FIFOTtlBackwardCompatible) {
|
||||
|
||||
@@ -3511,6 +3511,256 @@ TEST_F(DBRangeDelTest, MemtableMaxRangeDeletions) {
|
||||
ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
|
||||
ASSERT_EQ(3, NumTableFilesAtLevel(0));
|
||||
}
|
||||
|
||||
TEST_F(DBRangeDelTest, RangeDelReseekAfterFileReadError) {
|
||||
// This is to test a bug that is fixed in
|
||||
// https://github.com/facebook/rocksdb/pull/11786.
|
||||
Options opts = CurrentOptions();
|
||||
opts.num_levels = 7;
|
||||
|
||||
// Set up LSM
|
||||
//
|
||||
// L4: F1: [key1] F2: [key2]
|
||||
// L5: F3:[DeleteRange(key3, key6)]
|
||||
// L6: F4:[key3, key6]
|
||||
// Will inject error when reading from F2.
|
||||
// SeekToFirst() should land on key1.
|
||||
// Next() should encounter error when reading from F2,
|
||||
// and range del reseek should not reset this status.
|
||||
Random rnd(301);
|
||||
// L6
|
||||
ASSERT_OK(Put(Key(3), rnd.RandomString(100)));
|
||||
ASSERT_OK(Put(Key(6), rnd.RandomString(100)));
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(6);
|
||||
// L5
|
||||
ASSERT_OK(db_->DeleteRange(WriteOptions(), db_->DefaultColumnFamily(), Key(3),
|
||||
Key(6)));
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(5);
|
||||
// L4
|
||||
ASSERT_OK(Put(Key(2), rnd.RandomString(100)));
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(4);
|
||||
std::string fname;
|
||||
std::vector<LiveFileMetaData> live_files;
|
||||
db_->GetLiveFilesMetaData(&live_files);
|
||||
for (auto& meta : live_files) {
|
||||
if (meta.level == 4) {
|
||||
fname = meta.name;
|
||||
break;
|
||||
}
|
||||
}
|
||||
ASSERT_TRUE(!fname.empty());
|
||||
ASSERT_OK(Put(Key(1), rnd.RandomString(100)));
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(4);
|
||||
|
||||
SyncPoint::GetInstance()->SetCallBack(
|
||||
"RandomAccessFileReader::Read::BeforeReturn", [&fname](void* pair_ptr) {
|
||||
auto p =
|
||||
reinterpret_cast<std::pair<std::string*, IOStatus*>*>(pair_ptr);
|
||||
if (p->first->find(fname) != std::string::npos) {
|
||||
*p->second = IOStatus::IOError();
|
||||
p->second->SetRetryable(true);
|
||||
}
|
||||
});
|
||||
SyncPoint::GetInstance()->EnableProcessing();
|
||||
std::unique_ptr<Iterator> iter{db_->NewIterator(ReadOptions())};
|
||||
iter->SeekToFirst();
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_OK(iter->status());
|
||||
ASSERT_EQ(iter->key(), Key(1));
|
||||
iter->Next();
|
||||
ASSERT_FALSE(iter->Valid());
|
||||
ASSERT_NOK(iter->status());
|
||||
ASSERT_TRUE(iter->status().IsIOError());
|
||||
iter.reset();
|
||||
SyncPoint::GetInstance()->ClearAllCallBacks();
|
||||
SyncPoint::GetInstance()->DisableProcessing();
|
||||
|
||||
// Reverse scan
|
||||
// LSM setup
|
||||
// L4: F1: [key2] F2: [key7, key8]
|
||||
// L5: F3:[[key3, key6)]
|
||||
// L6: F4:[key1, key5]
|
||||
// Ingest error when read from F1.
|
||||
// SeekToLast() should land on key8.
|
||||
// During Prev(), MergingIterator will encounter error when reading from F1
|
||||
// and do a range del reseek (it sees key5 covered by a range tombstone).
|
||||
DestroyAndReopen(opts);
|
||||
// L6
|
||||
ASSERT_OK(Put(Key(1), rnd.RandomString(100)));
|
||||
ASSERT_OK(Put(Key(5), rnd.RandomString(100)));
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(6);
|
||||
// L5
|
||||
ASSERT_OK(db_->DeleteRange(WriteOptions(), db_->DefaultColumnFamily(), Key(3),
|
||||
Key(6)));
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(5);
|
||||
// L4
|
||||
ASSERT_OK(Put(Key(2), rnd.RandomString(100)));
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(4);
|
||||
live_files.clear();
|
||||
db_->GetLiveFilesMetaData(&live_files);
|
||||
for (auto& meta : live_files) {
|
||||
if (meta.level == 4) {
|
||||
fname = meta.name;
|
||||
break;
|
||||
}
|
||||
}
|
||||
ASSERT_TRUE(!fname.empty());
|
||||
ASSERT_OK(Put(Key(7), rnd.RandomString(100)));
|
||||
ASSERT_OK(Put(Key(8), rnd.RandomString(100)));
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(4);
|
||||
|
||||
SyncPoint::GetInstance()->SetCallBack(
|
||||
"RandomAccessFileReader::Read::AnyOffset", [&fname](void* pair_ptr) {
|
||||
auto p =
|
||||
reinterpret_cast<std::pair<std::string*, IOStatus*>*>(pair_ptr);
|
||||
if (p->first->find(fname) != std::string::npos) {
|
||||
*p->second = IOStatus::IOError();
|
||||
p->second->SetRetryable(true);
|
||||
}
|
||||
});
|
||||
SyncPoint::GetInstance()->EnableProcessing();
|
||||
iter.reset(db_->NewIterator(ReadOptions()));
|
||||
iter->SeekToLast();
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_OK(iter->status());
|
||||
ASSERT_EQ(iter->key(), Key(8));
|
||||
// Note that for reverse scan, DBIter will need to ensure
|
||||
// the key it returns is the one with the highest sequence number.
|
||||
// To return key7, it internally calls MergingIterator::Prev()
|
||||
// until it reaches a previous user key.
|
||||
iter->Prev();
|
||||
ASSERT_FALSE(iter->Valid());
|
||||
ASSERT_NOK(iter->status());
|
||||
ASSERT_TRUE(iter->status().IsIOError());
|
||||
|
||||
iter.reset();
|
||||
}
|
||||
|
||||
TEST_F(DBRangeDelTest, ReleaseSnapshotAfterIteratorCreation) {
|
||||
// Test that range tombstone code path in LevelIterator
|
||||
// does access ReadOptions::snapshot after Iterator creation.
|
||||
//
|
||||
// Put some data in L2 so that range tombstone in L1 will not be dropped.
|
||||
ASSERT_OK(Put(Key(0), "v"));
|
||||
ASSERT_OK(Put(Key(100), "v"));
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(2);
|
||||
|
||||
// two L1 file with range del
|
||||
ASSERT_OK(Put(Key(1), "v"));
|
||||
ASSERT_OK(Put(Key(2), "v"));
|
||||
ASSERT_OK(db_->DeleteRange(WriteOptions(), db_->DefaultColumnFamily(), Key(3),
|
||||
Key(4)));
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(1);
|
||||
|
||||
ASSERT_OK(Put(Key(5), "v"));
|
||||
ASSERT_OK(Put(Key(6), "v"));
|
||||
ASSERT_OK(db_->DeleteRange(WriteOptions(), db_->DefaultColumnFamily(), Key(5),
|
||||
Key(6)));
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(1);
|
||||
|
||||
ASSERT_EQ(2, NumTableFilesAtLevel(1));
|
||||
ASSERT_EQ(1, NumTableFilesAtLevel(2));
|
||||
|
||||
const Snapshot* snapshot = db_->GetSnapshot();
|
||||
ReadOptions ro;
|
||||
ro.snapshot = snapshot;
|
||||
|
||||
Iterator* iter = db_->NewIterator(ro);
|
||||
db_->ReleaseSnapshot(snapshot);
|
||||
|
||||
iter->Seek(Key(1));
|
||||
std::vector<int> expected_keys{1, 2, 6, 100};
|
||||
for (int i : expected_keys) {
|
||||
ASSERT_OK(iter->status());
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_EQ(iter->key(), Key(i));
|
||||
iter->Next();
|
||||
}
|
||||
ASSERT_TRUE(!iter->Valid() && iter->status().ok());
|
||||
|
||||
delete iter;
|
||||
}
|
||||
|
||||
TEST_F(DBRangeDelTest, RefreshWithSnapshot) {
|
||||
ASSERT_OK(Put(Key(4), "4"));
|
||||
ASSERT_OK(Put(Key(6), "6"));
|
||||
const Snapshot* snapshot = db_->GetSnapshot();
|
||||
ASSERT_OK(db_->DeleteRange(WriteOptions(), db_->DefaultColumnFamily(), Key(3),
|
||||
Key(5)));
|
||||
|
||||
std::unique_ptr<Iterator> iter{db_->NewIterator(ReadOptions())};
|
||||
// Live Memtable
|
||||
iter->SeekToFirst();
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_EQ(iter->key(), Key(6));
|
||||
ASSERT_OK(iter->Refresh(snapshot));
|
||||
iter->SeekToFirst();
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_EQ(iter->key(), Key(4));
|
||||
// Immutable Memtable
|
||||
ASSERT_OK(dbfull()->TEST_SwitchMemtable());
|
||||
ASSERT_OK(iter->Refresh(nullptr));
|
||||
iter->SeekToFirst();
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_EQ(iter->key(), Key(6));
|
||||
ASSERT_OK(iter->Refresh(snapshot));
|
||||
iter->SeekToFirst();
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_EQ(iter->key(), Key(4));
|
||||
// L0
|
||||
ASSERT_OK(Flush());
|
||||
ASSERT_EQ(1, NumTableFilesAtLevel(0));
|
||||
ASSERT_OK(iter->Refresh(nullptr));
|
||||
iter->SeekToFirst();
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_EQ(iter->key(), Key(6));
|
||||
ASSERT_OK(iter->Refresh(snapshot));
|
||||
iter->SeekToFirst();
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_EQ(iter->key(), Key(4));
|
||||
// L1
|
||||
MoveFilesToLevel(1);
|
||||
ASSERT_EQ(1, NumTableFilesAtLevel(1));
|
||||
ASSERT_OK(iter->Refresh(nullptr));
|
||||
iter->SeekToFirst();
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_EQ(iter->key(), Key(6));
|
||||
ASSERT_OK(iter->Refresh(snapshot));
|
||||
iter->SeekToFirst();
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_EQ(iter->key(), Key(4));
|
||||
// L1 with two file.
|
||||
// Test that when LevelIterator enters a new file,
|
||||
// it remembers which snapshot sequence number to use.
|
||||
ASSERT_OK(Put(Key(2), "2"));
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(1);
|
||||
ASSERT_EQ(2, NumTableFilesAtLevel(1));
|
||||
ASSERT_OK(iter->Refresh(nullptr));
|
||||
iter->SeekToFirst();
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
// LevelIterator is at the first file
|
||||
ASSERT_EQ(iter->key(), Key(2));
|
||||
ASSERT_OK(iter->Refresh(snapshot));
|
||||
// Will enter the second file, and create a new range tombstone iterator.
|
||||
// It should use the snapshot sequence number.
|
||||
iter->SeekToFirst();
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_EQ(iter->key(), Key(4));
|
||||
iter.reset();
|
||||
db_->ReleaseSnapshot(snapshot);
|
||||
}
|
||||
} // namespace ROCKSDB_NAMESPACE
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
|
||||
@@ -336,6 +336,53 @@ TEST_F(DBReadOnlyTestWithTimestamp, Iterators) {
|
||||
Close();
|
||||
}
|
||||
|
||||
TEST_F(DBReadOnlyTestWithTimestamp, FullHistoryTsLowSanityCheckFail) {
|
||||
Options options = CurrentOptions();
|
||||
options.env = env_;
|
||||
options.comparator = test::BytewiseComparatorWithU64TsWrapper();
|
||||
// Use UDT in memtable only feature for this test, so we can control that
|
||||
// newly set `full_history_ts_low` collapse history when Flush happens.
|
||||
options.persist_user_defined_timestamps = false;
|
||||
options.allow_concurrent_memtable_write = false;
|
||||
DestroyAndReopen(options);
|
||||
|
||||
std::string write_ts;
|
||||
PutFixed64(&write_ts, 1);
|
||||
ASSERT_OK(db_->Put(WriteOptions(), "foo", write_ts, "val1"));
|
||||
|
||||
std::string full_history_ts_low;
|
||||
PutFixed64(&full_history_ts_low, 3);
|
||||
ASSERT_OK(db_->IncreaseFullHistoryTsLow(db_->DefaultColumnFamily(),
|
||||
full_history_ts_low));
|
||||
ASSERT_OK(Flush(0));
|
||||
|
||||
// Reopen the database in read only mode to test its timestamp support.
|
||||
Close();
|
||||
ASSERT_OK(ReadOnlyReopen(options));
|
||||
|
||||
// Reading below full_history_ts_low fails a sanity check.
|
||||
std::string read_ts;
|
||||
PutFixed64(&read_ts, 2);
|
||||
Slice read_ts_slice = read_ts;
|
||||
ReadOptions read_opts;
|
||||
read_opts.timestamp = &read_ts_slice;
|
||||
|
||||
// Get()
|
||||
std::string value;
|
||||
ASSERT_TRUE(db_->Get(read_opts, "foo", &value).IsInvalidArgument());
|
||||
// NewIterator()
|
||||
std::unique_ptr<Iterator> iter(
|
||||
db_->NewIterator(read_opts, db_->DefaultColumnFamily()));
|
||||
ASSERT_TRUE(iter->status().IsInvalidArgument());
|
||||
|
||||
// NewIterators()
|
||||
std::vector<ColumnFamilyHandle*> cfhs = {db_->DefaultColumnFamily()};
|
||||
std::vector<Iterator*> iterators;
|
||||
ASSERT_TRUE(
|
||||
db_->NewIterators(read_opts, cfhs, &iterators).IsInvalidArgument());
|
||||
Close();
|
||||
}
|
||||
|
||||
TEST_F(DBReadOnlyTestWithTimestamp, IteratorsReadTimestampSizeMismatch) {
|
||||
const int kNumKeysPerFile = 128;
|
||||
const uint64_t kMaxKey = 1024;
|
||||
|
||||
+63
-1
@@ -164,12 +164,22 @@ TEST_F(DBSecondaryTest, ReopenAsSecondary) {
|
||||
Reopen(options);
|
||||
ASSERT_OK(Put("foo", "foo_value"));
|
||||
ASSERT_OK(Put("bar", "bar_value"));
|
||||
WideColumns columns{{kDefaultWideColumnName, "attr_default_val"},
|
||||
{"attr_name1", "attr_value_1"},
|
||||
{"attr_name2", "attr_value_2"}};
|
||||
ASSERT_OK(db_->PutEntity(WriteOptions(), db_->DefaultColumnFamily(), "baz",
|
||||
columns));
|
||||
ASSERT_OK(dbfull()->Flush(FlushOptions()));
|
||||
Close();
|
||||
|
||||
ASSERT_OK(ReopenAsSecondary(options));
|
||||
ASSERT_EQ("foo_value", Get("foo"));
|
||||
ASSERT_EQ("bar_value", Get("bar"));
|
||||
PinnableWideColumns result;
|
||||
ASSERT_OK(db_->GetEntity(ReadOptions(), db_->DefaultColumnFamily(), "baz",
|
||||
&result));
|
||||
ASSERT_EQ(result.columns(), columns);
|
||||
|
||||
ReadOptions ropts;
|
||||
ropts.verify_checksums = true;
|
||||
auto db1 = static_cast<DBImplSecondary*>(db_);
|
||||
@@ -182,13 +192,16 @@ TEST_F(DBSecondaryTest, ReopenAsSecondary) {
|
||||
ASSERT_EQ("bar", iter->key().ToString());
|
||||
ASSERT_EQ("bar_value", iter->value().ToString());
|
||||
} else if (1 == count) {
|
||||
ASSERT_EQ("baz", iter->key().ToString());
|
||||
ASSERT_EQ(columns, iter->columns());
|
||||
} else if (2 == count) {
|
||||
ASSERT_EQ("foo", iter->key().ToString());
|
||||
ASSERT_EQ("foo_value", iter->value().ToString());
|
||||
}
|
||||
++count;
|
||||
}
|
||||
delete iter;
|
||||
ASSERT_EQ(2, count);
|
||||
ASSERT_EQ(3, count);
|
||||
}
|
||||
|
||||
TEST_F(DBSecondaryTest, SimpleInternalCompaction) {
|
||||
@@ -1561,6 +1574,55 @@ TEST_F(DBSecondaryTestWithTimestamp, IteratorsReadTimestampSizeMismatch) {
|
||||
Close();
|
||||
}
|
||||
|
||||
TEST_F(DBSecondaryTestWithTimestamp, FullHistoryTsLowSanityCheckFail) {
|
||||
Options options = CurrentOptions();
|
||||
options.env = env_;
|
||||
options.comparator = test::BytewiseComparatorWithU64TsWrapper();
|
||||
// Use UDT in memtable only feature for this test, so we can control that
|
||||
// newly set `full_history_ts_low` collapse history when Flush happens.
|
||||
options.persist_user_defined_timestamps = false;
|
||||
options.allow_concurrent_memtable_write = false;
|
||||
DestroyAndReopen(options);
|
||||
|
||||
std::string write_ts;
|
||||
PutFixed64(&write_ts, 1);
|
||||
ASSERT_OK(db_->Put(WriteOptions(), "foo", write_ts, "val1"));
|
||||
|
||||
std::string full_history_ts_low;
|
||||
PutFixed64(&full_history_ts_low, 3);
|
||||
ASSERT_OK(db_->IncreaseFullHistoryTsLow(db_->DefaultColumnFamily(),
|
||||
full_history_ts_low));
|
||||
ASSERT_OK(Flush(0));
|
||||
|
||||
// Reopen the database as secondary instance to test its timestamp support.
|
||||
Close();
|
||||
options.max_open_files = -1;
|
||||
ASSERT_OK(ReopenAsSecondary(options));
|
||||
|
||||
// Reading below full_history_ts_low fails a sanity check.
|
||||
std::string read_ts;
|
||||
PutFixed64(&read_ts, 2);
|
||||
Slice read_ts_slice = read_ts;
|
||||
ReadOptions read_opts;
|
||||
read_opts.timestamp = &read_ts_slice;
|
||||
|
||||
// Get()
|
||||
std::string value;
|
||||
ASSERT_TRUE(db_->Get(read_opts, "foo", &value).IsInvalidArgument());
|
||||
|
||||
// NewIterator()
|
||||
std::unique_ptr<Iterator> iter(
|
||||
db_->NewIterator(read_opts, db_->DefaultColumnFamily()));
|
||||
ASSERT_TRUE(iter->status().IsInvalidArgument());
|
||||
|
||||
// NewIterators()
|
||||
std::vector<ColumnFamilyHandle*> cfhs = {db_->DefaultColumnFamily()};
|
||||
std::vector<Iterator*> iterators;
|
||||
ASSERT_TRUE(
|
||||
db_->NewIterators(read_opts, cfhs, &iterators).IsInvalidArgument());
|
||||
Close();
|
||||
}
|
||||
|
||||
TEST_F(DBSecondaryTestWithTimestamp,
|
||||
IteratorsReadTimestampSpecifiedWithoutWriteTimestamp) {
|
||||
const int kNumKeysPerFile = 128;
|
||||
|
||||
+21
-3
@@ -937,12 +937,21 @@ INSTANTIATE_TEST_CASE_P(DBWALTestWithParam, DBWALTestWithParam,
|
||||
::testing::Values(std::make_tuple("", true),
|
||||
std::make_tuple("_wal_dir", false)));
|
||||
|
||||
TEST_F(DBSSTTest, OpenDBWithExistingTrash) {
|
||||
TEST_F(DBSSTTest, OpenDBWithExistingTrashAndObsoleteSstFile) {
|
||||
Options options = CurrentOptions();
|
||||
|
||||
options.sst_file_manager.reset(
|
||||
NewSstFileManager(env_, nullptr, "", 1024 * 1024 /* 1 MB/sec */));
|
||||
auto sfm = static_cast<SstFileManagerImpl*>(options.sst_file_manager.get());
|
||||
// Set an extra high trash ratio to prevent immediate/non-rate limited
|
||||
// deletions
|
||||
sfm->SetDeleteRateBytesPerSecond(1024 * 1024);
|
||||
sfm->delete_scheduler()->SetMaxTrashDBRatio(1000.0);
|
||||
|
||||
int bg_delete_file = 0;
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
|
||||
"DeleteScheduler::DeleteTrashFile:DeleteFile",
|
||||
[&](void* /*arg*/) { bg_delete_file++; });
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
|
||||
|
||||
Destroy(last_options_);
|
||||
|
||||
@@ -951,13 +960,22 @@ TEST_F(DBSSTTest, OpenDBWithExistingTrash) {
|
||||
ASSERT_OK(WriteStringToFile(env_, "abc", dbname_ + "/" + "001.sst.trash"));
|
||||
ASSERT_OK(WriteStringToFile(env_, "abc", dbname_ + "/" + "002.sst.trash"));
|
||||
ASSERT_OK(WriteStringToFile(env_, "abc", dbname_ + "/" + "003.sst.trash"));
|
||||
// Manually add an obsolete sst file. Obsolete SST files are discovered and
|
||||
// deleted upon recovery.
|
||||
constexpr uint64_t kSstFileNumber = 100;
|
||||
const std::string kObsoleteSstFile =
|
||||
MakeTableFileName(dbname_, kSstFileNumber);
|
||||
ASSERT_OK(WriteStringToFile(env_, "abc", kObsoleteSstFile));
|
||||
|
||||
// Reopen the DB and verify that it deletes existing trash files
|
||||
// Reopen the DB and verify that it deletes existing trash files and obsolete
|
||||
// SST files with rate limiting.
|
||||
Reopen(options);
|
||||
sfm->WaitForEmptyTrash();
|
||||
ASSERT_NOK(env_->FileExists(dbname_ + "/" + "001.sst.trash"));
|
||||
ASSERT_NOK(env_->FileExists(dbname_ + "/" + "002.sst.trash"));
|
||||
ASSERT_NOK(env_->FileExists(dbname_ + "/" + "003.sst.trash"));
|
||||
ASSERT_NOK(env_->FileExists(kObsoleteSstFile));
|
||||
ASSERT_EQ(bg_delete_file, 4);
|
||||
}
|
||||
|
||||
// Create a DB with 2 db_paths, and generate multiple files in the 2
|
||||
|
||||
+128
-30
@@ -644,6 +644,33 @@ TEST_F(DBTest, ReadFromPersistedTier) {
|
||||
ASSERT_OK(db_->Get(ropt, handles_[1], "bar", &value));
|
||||
}
|
||||
|
||||
const auto check_multiget_func =
|
||||
[&](const ReadOptions& read_opts,
|
||||
std::vector<ColumnFamilyHandle*> cfhs, std::vector<Slice>& keys,
|
||||
std::vector<std::string>& values,
|
||||
bool batched) -> std::vector<Status> {
|
||||
if (!batched) {
|
||||
return db_->MultiGet(read_opts, cfhs, keys, &values);
|
||||
} else {
|
||||
size_t num_keys = keys.size();
|
||||
std::vector<Status> statuses;
|
||||
std::vector<PinnableSlice> pinnable_values;
|
||||
statuses.resize(num_keys);
|
||||
pinnable_values.resize(num_keys);
|
||||
values.resize(num_keys);
|
||||
db_->MultiGet(read_opts, cfhs[0], num_keys, keys.data(),
|
||||
pinnable_values.data(), statuses.data(), false);
|
||||
for (size_t i = 0; i < statuses.size(); ++i) {
|
||||
if (statuses[i].ok()) {
|
||||
values[i].assign(pinnable_values[i].data(),
|
||||
pinnable_values[i].size());
|
||||
pinnable_values[i].Reset();
|
||||
}
|
||||
}
|
||||
return statuses;
|
||||
}
|
||||
};
|
||||
|
||||
// Multiget
|
||||
std::vector<ColumnFamilyHandle*> multiget_cfs;
|
||||
multiget_cfs.push_back(handles_[1]);
|
||||
@@ -652,14 +679,17 @@ TEST_F(DBTest, ReadFromPersistedTier) {
|
||||
multiget_keys.push_back("foo");
|
||||
multiget_keys.push_back("bar");
|
||||
std::vector<std::string> multiget_values;
|
||||
auto statuses =
|
||||
db_->MultiGet(ropt, multiget_cfs, multiget_keys, &multiget_values);
|
||||
if (wopt.disableWAL) {
|
||||
ASSERT_TRUE(statuses[0].IsNotFound());
|
||||
ASSERT_TRUE(statuses[1].IsNotFound());
|
||||
} else {
|
||||
ASSERT_OK(statuses[0]);
|
||||
ASSERT_OK(statuses[1]);
|
||||
for (int i = 0; i < 2; i++) {
|
||||
bool batched = i == 0;
|
||||
auto statuses = check_multiget_func(ropt, multiget_cfs, multiget_keys,
|
||||
multiget_values, batched);
|
||||
if (wopt.disableWAL) {
|
||||
ASSERT_TRUE(statuses[0].IsNotFound());
|
||||
ASSERT_TRUE(statuses[1].IsNotFound());
|
||||
} else {
|
||||
ASSERT_OK(statuses[0]);
|
||||
ASSERT_OK(statuses[1]);
|
||||
}
|
||||
}
|
||||
|
||||
// 2nd round: flush and put a new value in memtable.
|
||||
@@ -683,16 +713,21 @@ TEST_F(DBTest, ReadFromPersistedTier) {
|
||||
// Expect same result in multiget
|
||||
multiget_cfs.push_back(handles_[1]);
|
||||
multiget_keys.push_back("rocksdb");
|
||||
statuses =
|
||||
db_->MultiGet(ropt, multiget_cfs, multiget_keys, &multiget_values);
|
||||
ASSERT_TRUE(statuses[0].ok());
|
||||
ASSERT_EQ("first", multiget_values[0]);
|
||||
ASSERT_TRUE(statuses[1].ok());
|
||||
ASSERT_EQ("one", multiget_values[1]);
|
||||
if (wopt.disableWAL) {
|
||||
ASSERT_TRUE(statuses[2].IsNotFound());
|
||||
} else {
|
||||
ASSERT_OK(statuses[2]);
|
||||
multiget_values.clear();
|
||||
|
||||
for (int i = 0; i < 2; i++) {
|
||||
bool batched = i == 0;
|
||||
auto statuses = check_multiget_func(ropt, multiget_cfs, multiget_keys,
|
||||
multiget_values, batched);
|
||||
ASSERT_TRUE(statuses[0].ok());
|
||||
ASSERT_EQ("first", multiget_values[0]);
|
||||
ASSERT_TRUE(statuses[1].ok());
|
||||
ASSERT_EQ("one", multiget_values[1]);
|
||||
if (wopt.disableWAL) {
|
||||
ASSERT_TRUE(statuses[2].IsNotFound());
|
||||
} else {
|
||||
ASSERT_OK(statuses[2]);
|
||||
}
|
||||
}
|
||||
|
||||
// 3rd round: delete and flush
|
||||
@@ -712,17 +747,21 @@ TEST_F(DBTest, ReadFromPersistedTier) {
|
||||
ASSERT_TRUE(db_->Get(ropt, handles_[1], "rocksdb", &value).ok());
|
||||
ASSERT_EQ(value, "hello");
|
||||
|
||||
statuses =
|
||||
db_->MultiGet(ropt, multiget_cfs, multiget_keys, &multiget_values);
|
||||
ASSERT_TRUE(statuses[0].IsNotFound());
|
||||
if (wopt.disableWAL) {
|
||||
ASSERT_TRUE(statuses[1].ok());
|
||||
ASSERT_EQ("one", multiget_values[1]);
|
||||
} else {
|
||||
ASSERT_TRUE(statuses[1].IsNotFound());
|
||||
multiget_values.clear();
|
||||
for (int i = 0; i < 2; i++) {
|
||||
bool batched = i == 0;
|
||||
auto statuses = check_multiget_func(ropt, multiget_cfs, multiget_keys,
|
||||
multiget_values, batched);
|
||||
ASSERT_TRUE(statuses[0].IsNotFound());
|
||||
if (wopt.disableWAL) {
|
||||
ASSERT_TRUE(statuses[1].ok());
|
||||
ASSERT_EQ("one", multiget_values[1]);
|
||||
} else {
|
||||
ASSERT_TRUE(statuses[1].IsNotFound());
|
||||
}
|
||||
ASSERT_TRUE(statuses[2].ok());
|
||||
ASSERT_EQ("hello", multiget_values[2]);
|
||||
}
|
||||
ASSERT_TRUE(statuses[2].ok());
|
||||
ASSERT_EQ("hello", multiget_values[2]);
|
||||
if (wopt.disableWAL == 0) {
|
||||
DestroyAndReopen(options);
|
||||
}
|
||||
@@ -6040,6 +6079,64 @@ TEST_P(DBTestWithParam, FilterCompactionTimeTest) {
|
||||
delete itr;
|
||||
}
|
||||
|
||||
#ifndef OS_WIN
|
||||
// CPUMicros() is not supported. See WinClock::CPUMicros().
|
||||
TEST_P(DBTestWithParam, CompactionTotalTimeTest) {
|
||||
int record_count = 0;
|
||||
class TestStatistics : public StatisticsImpl {
|
||||
public:
|
||||
explicit TestStatistics(int* record_count)
|
||||
: StatisticsImpl(nullptr), record_count_(record_count) {}
|
||||
void recordTick(uint32_t ticker_type, uint64_t count) override {
|
||||
if (ticker_type == COMPACTION_CPU_TOTAL_TIME) {
|
||||
ASSERT_GT(count, 0);
|
||||
(*record_count_)++;
|
||||
}
|
||||
StatisticsImpl::recordTick(ticker_type, count);
|
||||
}
|
||||
|
||||
int* record_count_;
|
||||
};
|
||||
|
||||
Options options = CurrentOptions();
|
||||
options.disable_auto_compactions = true;
|
||||
options.create_if_missing = true;
|
||||
options.statistics = std::make_shared<TestStatistics>(&record_count);
|
||||
options.statistics->set_stats_level(kExceptTimeForMutex);
|
||||
options.max_subcompactions = max_subcompactions_;
|
||||
DestroyAndReopen(options);
|
||||
|
||||
int n = 0;
|
||||
for (int table = 0; table < 4; ++table) {
|
||||
for (int i = 0; i < 1000; ++i) {
|
||||
ASSERT_OK(Put(std::to_string(table * 1000 + i), "val"));
|
||||
++n;
|
||||
}
|
||||
// Overlapping tables
|
||||
ASSERT_OK(Put(std::to_string(0), "val"));
|
||||
++n;
|
||||
ASSERT_OK(Flush());
|
||||
}
|
||||
|
||||
CompactRangeOptions cro;
|
||||
cro.exclusive_manual_compaction = exclusive_manual_compaction_;
|
||||
ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
|
||||
|
||||
// Hard-coded number in CompactionJob::ProcessKeyValueCompaction().
|
||||
const int kRecordStatsEvery = 1000;
|
||||
// The stat COMPACTION_CPU_TOTAL_TIME should be recorded
|
||||
// during compaction and once more after compaction.
|
||||
ASSERT_EQ(n / kRecordStatsEvery + 1, record_count);
|
||||
|
||||
// Check that COMPACTION_CPU_TOTAL_TIME correctly
|
||||
// records compaction time after a compaction.
|
||||
HistogramData h;
|
||||
options.statistics->histogramData(COMPACTION_CPU_TIME, &h);
|
||||
ASSERT_EQ(1, h.count);
|
||||
ASSERT_EQ(h.max, TestGetTickerCount(options, COMPACTION_CPU_TOTAL_TIME));
|
||||
}
|
||||
#endif
|
||||
|
||||
TEST_F(DBTest, TestLogCleanup) {
|
||||
Options options = CurrentOptions();
|
||||
options.write_buffer_size = 64 * 1024; // very small
|
||||
@@ -6934,8 +7031,9 @@ TEST_F(DBTest, RowCache) {
|
||||
using CacheWrapper::CacheWrapper;
|
||||
const char* Name() const override { return "FailInsertionCache"; }
|
||||
Status Insert(const Slice&, Cache::ObjectPtr, const CacheItemHelper*,
|
||||
size_t, Handle** = nullptr,
|
||||
Priority = Priority::LOW) override {
|
||||
size_t, Handle** = nullptr, Priority = Priority::LOW,
|
||||
const Slice& /*compressed*/ = Slice(),
|
||||
CompressionType /*type*/ = kNoCompression) override {
|
||||
return Status::MemoryLimit();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -6876,6 +6876,7 @@ TEST_F(DBTest2, LastLevelTemperatureUniversal) {
|
||||
TEST_F(DBTest2, LastLevelStatistics) {
|
||||
Options options = CurrentOptions();
|
||||
options.bottommost_temperature = Temperature::kWarm;
|
||||
options.default_temperature = Temperature::kHot;
|
||||
options.level0_file_num_compaction_trigger = 2;
|
||||
options.level_compaction_dynamic_level_bytes = true;
|
||||
options.statistics = CreateDBStatistics();
|
||||
@@ -6889,6 +6890,10 @@ TEST_F(DBTest2, LastLevelStatistics) {
|
||||
|
||||
ASSERT_GT(options.statistics->getTickerCount(NON_LAST_LEVEL_READ_BYTES), 0);
|
||||
ASSERT_GT(options.statistics->getTickerCount(NON_LAST_LEVEL_READ_COUNT), 0);
|
||||
ASSERT_EQ(options.statistics->getTickerCount(NON_LAST_LEVEL_READ_BYTES),
|
||||
options.statistics->getTickerCount(HOT_FILE_READ_BYTES));
|
||||
ASSERT_EQ(options.statistics->getTickerCount(NON_LAST_LEVEL_READ_COUNT),
|
||||
options.statistics->getTickerCount(HOT_FILE_READ_COUNT));
|
||||
ASSERT_EQ(options.statistics->getTickerCount(LAST_LEVEL_READ_BYTES), 0);
|
||||
ASSERT_EQ(options.statistics->getTickerCount(LAST_LEVEL_READ_COUNT), 0);
|
||||
|
||||
@@ -6899,6 +6904,10 @@ TEST_F(DBTest2, LastLevelStatistics) {
|
||||
ASSERT_OK(dbfull()->TEST_WaitForCompact());
|
||||
ASSERT_EQ("bar", Get("bar"));
|
||||
|
||||
ASSERT_EQ(options.statistics->getTickerCount(NON_LAST_LEVEL_READ_BYTES),
|
||||
options.statistics->getTickerCount(HOT_FILE_READ_BYTES));
|
||||
ASSERT_EQ(options.statistics->getTickerCount(NON_LAST_LEVEL_READ_COUNT),
|
||||
options.statistics->getTickerCount(HOT_FILE_READ_COUNT));
|
||||
ASSERT_EQ(options.statistics->getTickerCount(LAST_LEVEL_READ_BYTES),
|
||||
options.statistics->getTickerCount(WARM_FILE_READ_BYTES));
|
||||
ASSERT_EQ(options.statistics->getTickerCount(LAST_LEVEL_READ_COUNT),
|
||||
@@ -6919,6 +6928,30 @@ TEST_F(DBTest2, LastLevelStatistics) {
|
||||
pre_bytes);
|
||||
ASSERT_GT(options.statistics->getTickerCount(NON_LAST_LEVEL_READ_COUNT),
|
||||
pre_count);
|
||||
ASSERT_EQ(options.statistics->getTickerCount(NON_LAST_LEVEL_READ_BYTES),
|
||||
options.statistics->getTickerCount(HOT_FILE_READ_BYTES));
|
||||
ASSERT_EQ(options.statistics->getTickerCount(NON_LAST_LEVEL_READ_COUNT),
|
||||
options.statistics->getTickerCount(HOT_FILE_READ_COUNT));
|
||||
ASSERT_EQ(options.statistics->getTickerCount(LAST_LEVEL_READ_BYTES),
|
||||
options.statistics->getTickerCount(WARM_FILE_READ_BYTES));
|
||||
ASSERT_EQ(options.statistics->getTickerCount(LAST_LEVEL_READ_COUNT),
|
||||
options.statistics->getTickerCount(WARM_FILE_READ_COUNT));
|
||||
|
||||
// Not a realistic setting to make last level kWarm and default temp kCold.
|
||||
// This is just for testing default temp can be reset on reopen while the
|
||||
// last level temp is consistent across DB reopen because those file's temp
|
||||
// are persisted in manifest.
|
||||
options.default_temperature = Temperature::kCold;
|
||||
ASSERT_OK(options.statistics->Reset());
|
||||
Reopen(options);
|
||||
ASSERT_EQ("bar", Get("bar"));
|
||||
|
||||
ASSERT_EQ(0, options.statistics->getTickerCount(HOT_FILE_READ_BYTES));
|
||||
|
||||
ASSERT_EQ(options.statistics->getTickerCount(NON_LAST_LEVEL_READ_BYTES),
|
||||
options.statistics->getTickerCount(COLD_FILE_READ_BYTES));
|
||||
ASSERT_EQ(options.statistics->getTickerCount(NON_LAST_LEVEL_READ_COUNT),
|
||||
options.statistics->getTickerCount(COLD_FILE_READ_COUNT));
|
||||
ASSERT_EQ(options.statistics->getTickerCount(LAST_LEVEL_READ_BYTES),
|
||||
options.statistics->getTickerCount(WARM_FILE_READ_BYTES));
|
||||
ASSERT_EQ(options.statistics->getTickerCount(LAST_LEVEL_READ_COUNT),
|
||||
|
||||
+6
-6
@@ -1716,12 +1716,12 @@ TargetCacheChargeTrackingCache<R>::TargetCacheChargeTrackingCache(
|
||||
cache_charge_increments_sum_(0) {}
|
||||
|
||||
template <CacheEntryRole R>
|
||||
Status TargetCacheChargeTrackingCache<R>::Insert(const Slice& key,
|
||||
ObjectPtr value,
|
||||
const CacheItemHelper* helper,
|
||||
size_t charge, Handle** handle,
|
||||
Priority priority) {
|
||||
Status s = target_->Insert(key, value, helper, charge, handle, priority);
|
||||
Status TargetCacheChargeTrackingCache<R>::Insert(
|
||||
const Slice& key, ObjectPtr value, const CacheItemHelper* helper,
|
||||
size_t charge, Handle** handle, Priority priority, const Slice& compressed,
|
||||
CompressionType type) {
|
||||
Status s = target_->Insert(key, value, helper, charge, handle, priority,
|
||||
compressed, type);
|
||||
if (helper == kCrmHelper) {
|
||||
if (last_peak_tracked_) {
|
||||
cache_charge_peak_ = 0;
|
||||
|
||||
+3
-2
@@ -936,8 +936,9 @@ class TargetCacheChargeTrackingCache : public CacheWrapper {
|
||||
|
||||
Status Insert(const Slice& key, ObjectPtr value,
|
||||
const CacheItemHelper* helper, size_t charge,
|
||||
Handle** handle = nullptr,
|
||||
Priority priority = Priority::LOW) override;
|
||||
Handle** handle = nullptr, Priority priority = Priority::LOW,
|
||||
const Slice& compressed = Slice(),
|
||||
CompressionType type = kNoCompression) override;
|
||||
|
||||
using Cache::Release;
|
||||
bool Release(Handle* handle, bool erase_if_last_ref = false) override;
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
#include "port/stack_trace.h"
|
||||
#include "rocksdb/file_system.h"
|
||||
#include "test_util/sync_point.h"
|
||||
#include "util/udt_util.h"
|
||||
#include "utilities/fault_injection_env.h"
|
||||
#include "utilities/fault_injection_fs.h"
|
||||
|
||||
@@ -384,6 +385,7 @@ TEST_P(DBWALTestWithTimestamp, RecoverAndNoFlush) {
|
||||
ts_options.persist_user_defined_timestamps = persist_udt;
|
||||
bool avoid_flush_during_recovery = true;
|
||||
|
||||
std::string full_history_ts_low;
|
||||
ReadOptions read_opts;
|
||||
do {
|
||||
Slice ts_slice = ts1;
|
||||
@@ -439,6 +441,8 @@ TEST_P(DBWALTestWithTimestamp, RecoverAndNoFlush) {
|
||||
CheckGet(read_opts, 1, "foo", "v4", ts3);
|
||||
CheckGet(read_opts, 1, "bar", "v2", ts2);
|
||||
CheckGet(read_opts, 1, "baz", "v5", ts1);
|
||||
ASSERT_OK(db_->GetFullHistoryTsLow(handles_[1], &full_history_ts_low));
|
||||
ASSERT_TRUE(full_history_ts_low.empty());
|
||||
} while (ChangeWalOptions());
|
||||
}
|
||||
|
||||
@@ -470,6 +474,8 @@ TEST_P(DBWALTestWithTimestamp, RecoverAndFlush) {
|
||||
|
||||
std::vector<std::vector<FileMetaData>> level_to_files;
|
||||
dbfull()->TEST_GetFilesMetaData(handles_[1], &level_to_files);
|
||||
std::string full_history_ts_low;
|
||||
ASSERT_OK(db_->GetFullHistoryTsLow(handles_[1], &full_history_ts_low));
|
||||
ASSERT_GT(level_to_files.size(), 1);
|
||||
// L0 only has one SST file.
|
||||
ASSERT_EQ(level_to_files[0].size(), 1);
|
||||
@@ -477,9 +483,14 @@ TEST_P(DBWALTestWithTimestamp, RecoverAndFlush) {
|
||||
if (persist_udt) {
|
||||
ASSERT_EQ(smallest_ukey_without_ts + write_ts, meta.smallest.user_key());
|
||||
ASSERT_EQ(largest_ukey_without_ts + write_ts, meta.largest.user_key());
|
||||
ASSERT_TRUE(full_history_ts_low.empty());
|
||||
} else {
|
||||
ASSERT_EQ(smallest_ukey_without_ts + min_ts, meta.smallest.user_key());
|
||||
ASSERT_EQ(largest_ukey_without_ts + min_ts, meta.largest.user_key());
|
||||
std::string effective_cutoff;
|
||||
Slice write_ts_slice = write_ts;
|
||||
GetFullHistoryTsLowFromU64CutoffTs(&write_ts_slice, &effective_cutoff);
|
||||
ASSERT_EQ(effective_cutoff, full_history_ts_low);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1617,6 +1617,105 @@ TEST_F(DBBasicTestWithTimestamp, MultiGetRangeFiltering) {
|
||||
Close();
|
||||
}
|
||||
|
||||
TEST_F(DBBasicTestWithTimestamp, GetWithRowCache) {
|
||||
Options options = CurrentOptions();
|
||||
options.env = env_;
|
||||
options.create_if_missing = true;
|
||||
options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
|
||||
LRUCacheOptions cache_options;
|
||||
cache_options.capacity = 8192;
|
||||
options.row_cache = cache_options.MakeSharedRowCache();
|
||||
|
||||
const size_t kTimestampSize = Timestamp(0, 0).size();
|
||||
TestComparator test_cmp(kTimestampSize);
|
||||
options.comparator = &test_cmp;
|
||||
DestroyAndReopen(options);
|
||||
|
||||
WriteOptions write_opts;
|
||||
std::string ts_early = Timestamp(1, 0);
|
||||
std::string ts_later = Timestamp(10, 0);
|
||||
Slice ts_later_slice = ts_later;
|
||||
|
||||
const Snapshot* snap_with_nothing = db_->GetSnapshot();
|
||||
ASSERT_OK(db_->Put(write_opts, "foo", ts_early, "bar"));
|
||||
const Snapshot* snap_with_foo = db_->GetSnapshot();
|
||||
|
||||
// Ensure file has sequence number greater than snapshot_with_foo
|
||||
for (int i = 0; i < 10; i++) {
|
||||
std::string numStr = std::to_string(i);
|
||||
ASSERT_OK(db_->Put(write_opts, numStr, ts_later, numStr));
|
||||
}
|
||||
ASSERT_OK(Flush());
|
||||
ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), 0);
|
||||
ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), 0);
|
||||
|
||||
ReadOptions read_opts;
|
||||
read_opts.timestamp = &ts_later_slice;
|
||||
|
||||
std::string read_value;
|
||||
std::string read_ts;
|
||||
Status s = db_->Get(read_opts, "foo", &read_value, &read_ts);
|
||||
ASSERT_OK(s);
|
||||
ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), 0);
|
||||
ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), 1);
|
||||
ASSERT_EQ(read_ts, ts_early);
|
||||
|
||||
s = db_->Get(read_opts, "foo", &read_value, &read_ts);
|
||||
ASSERT_OK(s);
|
||||
ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), 1);
|
||||
ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), 1);
|
||||
// Row cache is not storing the ts when record is inserted/updated.
|
||||
// To be fixed after enabling ROW_CACHE with timestamp.
|
||||
// ASSERT_EQ(read_ts, ts_early);
|
||||
|
||||
{
|
||||
std::string ts_nothing = Timestamp(0, 0);
|
||||
Slice ts_nothing_slice = ts_nothing;
|
||||
read_opts.timestamp = &ts_nothing_slice;
|
||||
s = db_->Get(read_opts, "foo", &read_value, &read_ts);
|
||||
ASSERT_TRUE(s.IsNotFound());
|
||||
ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), 1);
|
||||
ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), 2);
|
||||
|
||||
read_opts.timestamp = &ts_later_slice;
|
||||
s = db_->Get(read_opts, "foo", &read_value, &read_ts);
|
||||
ASSERT_OK(s);
|
||||
ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), 2);
|
||||
ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), 2);
|
||||
}
|
||||
|
||||
{
|
||||
read_opts.snapshot = snap_with_foo;
|
||||
|
||||
s = db_->Get(read_opts, "foo", &read_value, &read_ts);
|
||||
ASSERT_OK(s);
|
||||
ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), 2);
|
||||
ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), 3);
|
||||
|
||||
s = db_->Get(read_opts, "foo", &read_value, &read_ts);
|
||||
ASSERT_OK(s);
|
||||
ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), 3);
|
||||
ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), 3);
|
||||
}
|
||||
|
||||
{
|
||||
read_opts.snapshot = snap_with_nothing;
|
||||
s = db_->Get(read_opts, "foo", &read_value, &read_ts);
|
||||
ASSERT_TRUE(s.IsNotFound());
|
||||
ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), 3);
|
||||
ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), 4);
|
||||
|
||||
s = db_->Get(read_opts, "foo", &read_value, &read_ts);
|
||||
ASSERT_TRUE(s.IsNotFound());
|
||||
ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), 3);
|
||||
ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), 5);
|
||||
}
|
||||
|
||||
db_->ReleaseSnapshot(snap_with_nothing);
|
||||
db_->ReleaseSnapshot(snap_with_foo);
|
||||
Close();
|
||||
}
|
||||
|
||||
TEST_P(DBBasicTestWithTimestampTableOptions, MultiGetPrefixFilter) {
|
||||
Options options = CurrentOptions();
|
||||
options.env = env_;
|
||||
@@ -3416,6 +3515,225 @@ TEST_F(DBBasicTestWithTimestamp, EnableDisableUDT) {
|
||||
Close();
|
||||
}
|
||||
|
||||
// Tests that as long as the
|
||||
// `ReadOptions.timestamp >= SuperVersion.full_history_ts_low` sanity check
|
||||
// passes. The read will be consistent even if the column family's
|
||||
// full_history_ts_low is concurrently increased and collapsed some history
|
||||
// above `ReadOptions.timestamp`.
|
||||
TEST_F(DBBasicTestWithTimestamp,
|
||||
FullHistoryTsLowSanityCheckPassReadIsConsistent) {
|
||||
Options options = CurrentOptions();
|
||||
options.env = env_;
|
||||
options.comparator = test::BytewiseComparatorWithU64TsWrapper();
|
||||
// Use UDT in memtable only feature for this test, so we can control that
|
||||
// newly set `full_history_ts_low` collapse history when Flush happens.
|
||||
options.persist_user_defined_timestamps = false;
|
||||
options.allow_concurrent_memtable_write = false;
|
||||
DestroyAndReopen(options);
|
||||
std::string min_ts;
|
||||
PutFixed64(&min_ts, 0);
|
||||
|
||||
// Write two versions of the key (1, v1), (3, v3), and always read with
|
||||
// timestamp 2.
|
||||
std::string write_ts;
|
||||
PutFixed64(&write_ts, 1);
|
||||
ASSERT_OK(db_->Put(WriteOptions(), "foo", write_ts, "val1"));
|
||||
|
||||
std::string read_ts;
|
||||
PutFixed64(&read_ts, 2);
|
||||
Slice read_ts_slice = read_ts;
|
||||
ReadOptions read_opts;
|
||||
read_opts.timestamp = &read_ts_slice;
|
||||
|
||||
// First read, no full_history_ts_low set, sanity check pass.
|
||||
std::string value;
|
||||
std::string timestamp;
|
||||
ASSERT_OK(db_->Get(read_opts, "foo", &value, ×tamp));
|
||||
ASSERT_EQ("val1", value);
|
||||
ASSERT_EQ(write_ts, timestamp);
|
||||
|
||||
std::string full_history_ts_low;
|
||||
std::string marked_ts_low;
|
||||
PutFixed64(&full_history_ts_low, 2);
|
||||
marked_ts_low = full_history_ts_low;
|
||||
ASSERT_OK(db_->IncreaseFullHistoryTsLow(db_->DefaultColumnFamily(),
|
||||
full_history_ts_low));
|
||||
ASSERT_OK(Flush(0));
|
||||
|
||||
// Write the (3, v3) entry after flush, otherwise with UDT in memtable only
|
||||
// the previous Flush(0) with full_history_ts_low = 2 will be postponed
|
||||
// waiting for (3, v3) to expire too.
|
||||
write_ts.clear();
|
||||
PutFixed64(&write_ts, 3);
|
||||
ASSERT_OK(db_->Put(WriteOptions(), "foo", write_ts, "val3"));
|
||||
|
||||
// Second read:
|
||||
// ReadOptions.timestamp(2) >= SuperVersion.full_history_ts_low(2),
|
||||
// and ReadOptions.timestamp(2) >= ColumnFamilyData.full_history_ts_low(2).
|
||||
// history below 2 is collapsed. Reading at 2 or above 2 is ok.
|
||||
// Sanity check pass. Read return consistent value, but timestamp is already
|
||||
// collapsed.
|
||||
ASSERT_OK(db_->Get(read_opts, "foo", &value, ×tamp));
|
||||
ASSERT_EQ("val1", value);
|
||||
ASSERT_EQ(min_ts, timestamp);
|
||||
|
||||
SyncPoint::GetInstance()->SetCallBack(
|
||||
"DBImpl::GetImpl:AfterAcquireSv", [&](void* /*arg*/) {
|
||||
// Concurrently increasing full_history_ts_low and flush to create a
|
||||
// new SuperVersion
|
||||
std::string current_ts_low;
|
||||
ASSERT_OK(db_->GetFullHistoryTsLow(db_->DefaultColumnFamily(),
|
||||
¤t_ts_low));
|
||||
if (current_ts_low.empty() || current_ts_low != marked_ts_low) {
|
||||
return;
|
||||
}
|
||||
full_history_ts_low.clear();
|
||||
PutFixed64(&full_history_ts_low, 4);
|
||||
ASSERT_OK(db_->IncreaseFullHistoryTsLow(db_->DefaultColumnFamily(),
|
||||
full_history_ts_low));
|
||||
ASSERT_OK(Flush(0));
|
||||
});
|
||||
|
||||
SyncPoint::GetInstance()->EnableProcessing();
|
||||
|
||||
// Third read:
|
||||
// ReadOptions.timestamp(2) >= SuperVersion.full_history_ts_low(2),
|
||||
// but ReadOptions.timestamp(2) < ColumnFamilyData.full_history_ts_low(4).
|
||||
// History below 4 is collapsed in the newly installed SuperVersion. But the
|
||||
// SuperVersion attached to this read still has the history below 4 available.
|
||||
// Sanity check pass. Read return consistent value, timestamp is collapsed.
|
||||
ASSERT_OK(db_->Get(read_opts, "foo", &value, ×tamp));
|
||||
ASSERT_EQ("val1", value);
|
||||
ASSERT_EQ(min_ts, timestamp);
|
||||
|
||||
// Fourth read:
|
||||
// ReadOptions.timestamp(2) < SuperVersion.full_history_ts_low(4).
|
||||
// Sanity check fails. Had it succeeded, the read would return "v3",
|
||||
// which is inconsistent.
|
||||
ASSERT_TRUE(
|
||||
db_->Get(read_opts, "foo", &value, ×tamp).IsInvalidArgument());
|
||||
Close();
|
||||
|
||||
SyncPoint::GetInstance()->DisableProcessing();
|
||||
SyncPoint::GetInstance()->ClearAllCallBacks();
|
||||
}
|
||||
|
||||
// Tests that in cases when
|
||||
// `ReadOptions.timestamp >= SuperVersion.full_history_ts_low` sanity check
|
||||
// fails. The referenced SuperVersion is dereferenced and cleaned up properly
|
||||
// for all read APIs that involves this sanity check.
|
||||
TEST_F(DBBasicTestWithTimestamp, FullHistoryTsLowSanityCheckFail) {
|
||||
Options options = CurrentOptions();
|
||||
options.env = env_;
|
||||
options.comparator = test::BytewiseComparatorWithU64TsWrapper();
|
||||
// Use UDT in memtable only feature for this test, so we can control that
|
||||
// newly set `full_history_ts_low` collapse history when Flush happens.
|
||||
options.persist_user_defined_timestamps = false;
|
||||
options.allow_concurrent_memtable_write = false;
|
||||
DestroyAndReopen(options);
|
||||
|
||||
ColumnFamilyHandle* handle2 = nullptr;
|
||||
Status s = db_->CreateColumnFamily(options, "data", &handle2);
|
||||
ASSERT_OK(s);
|
||||
|
||||
std::string write_ts;
|
||||
PutFixed64(&write_ts, 1);
|
||||
ASSERT_OK(db_->Put(WriteOptions(), "foo", write_ts, "val1"));
|
||||
ASSERT_OK(db_->Put(WriteOptions(), handle2, "foo", write_ts, "val1"));
|
||||
|
||||
std::string full_history_ts_low;
|
||||
PutFixed64(&full_history_ts_low, 3);
|
||||
ASSERT_OK(db_->IncreaseFullHistoryTsLow(db_->DefaultColumnFamily(),
|
||||
full_history_ts_low));
|
||||
ASSERT_OK(db_->IncreaseFullHistoryTsLow(handle2, full_history_ts_low));
|
||||
ASSERT_OK(Flush(0));
|
||||
ASSERT_OK(db_->Flush(FlushOptions(), handle2));
|
||||
|
||||
std::string read_ts;
|
||||
PutFixed64(&read_ts, 2);
|
||||
Slice read_ts_slice = read_ts;
|
||||
ReadOptions read_opts;
|
||||
read_opts.timestamp = &read_ts_slice;
|
||||
|
||||
// Get()
|
||||
std::string value;
|
||||
ASSERT_TRUE(db_->Get(read_opts, "foo", &value).IsInvalidArgument());
|
||||
|
||||
// MultiGet()
|
||||
std::vector<ColumnFamilyHandle*> cfhs = {db_->DefaultColumnFamily(), handle2};
|
||||
{
|
||||
std::vector<std::string> key_vals = {"foo", "foo"};
|
||||
std::vector<Slice> keys;
|
||||
std::vector<std::string> values;
|
||||
for (size_t j = 0; j < 2; ++j) {
|
||||
keys.push_back(key_vals[j]);
|
||||
}
|
||||
|
||||
std::vector<Status> statuses =
|
||||
db_->MultiGet(read_opts, cfhs, keys, &values);
|
||||
for (auto status : statuses) {
|
||||
ASSERT_TRUE(status.IsInvalidArgument());
|
||||
}
|
||||
}
|
||||
|
||||
// MultiGet with only one column family
|
||||
{
|
||||
std::vector<ColumnFamilyHandle*> one_cfh = {db_->DefaultColumnFamily()};
|
||||
std::vector<std::string> key_vals = {"foo"};
|
||||
std::vector<Slice> keys;
|
||||
std::vector<std::string> values;
|
||||
for (size_t j = 0; j < 1; ++j) {
|
||||
keys.push_back(key_vals[j]);
|
||||
}
|
||||
|
||||
std::vector<Status> statuses =
|
||||
db_->MultiGet(read_opts, one_cfh, keys, &values);
|
||||
for (auto status : statuses) {
|
||||
ASSERT_TRUE(status.IsInvalidArgument());
|
||||
}
|
||||
}
|
||||
|
||||
// Overloaded version of MultiGet
|
||||
ColumnFamilyHandle* column_families[] = {db_->DefaultColumnFamily(), handle2};
|
||||
{
|
||||
Slice keys[] = {"foo", "foo"};
|
||||
PinnableSlice values[] = {PinnableSlice(), PinnableSlice()};
|
||||
Status statuses[] = {Status::OK(), Status::OK()};
|
||||
db_->MultiGet(read_opts, /*num_keys=*/2, &column_families[0], &keys[0],
|
||||
&values[0], &statuses[0], /*sorted_input=*/false);
|
||||
for (auto status : statuses) {
|
||||
ASSERT_TRUE(status.IsInvalidArgument());
|
||||
}
|
||||
}
|
||||
|
||||
// Overloaded versions of MultiGet with one column family
|
||||
{
|
||||
ColumnFamilyHandle* one_column_family[] = {db_->DefaultColumnFamily()};
|
||||
Slice keys[] = {"foo"};
|
||||
PinnableSlice values[] = {PinnableSlice()};
|
||||
Status statuses[] = {Status::OK()};
|
||||
db_->MultiGet(read_opts, /*num_keys=*/1, &one_column_family[0], &keys[0],
|
||||
&values[0], &statuses[0], /*sorted_input=*/false);
|
||||
for (auto status : statuses) {
|
||||
ASSERT_TRUE(status.IsInvalidArgument());
|
||||
}
|
||||
}
|
||||
|
||||
// NewIterator()
|
||||
std::unique_ptr<Iterator> iter(
|
||||
db_->NewIterator(read_opts, db_->DefaultColumnFamily()));
|
||||
ASSERT_TRUE(iter->status().IsInvalidArgument());
|
||||
std::unique_ptr<Iterator> iter2(db_->NewIterator(read_opts, handle2));
|
||||
ASSERT_TRUE(iter2->status().IsInvalidArgument());
|
||||
|
||||
// NewIterators()
|
||||
std::vector<Iterator*> iterators;
|
||||
ASSERT_TRUE(
|
||||
db_->NewIterators(read_opts, cfhs, &iterators).IsInvalidArgument());
|
||||
delete handle2;
|
||||
Close();
|
||||
}
|
||||
|
||||
TEST_F(DBBasicTestWithTimestamp,
|
||||
GCPreserveRangeTombstoneWhenNoOrSmallFullHistoryLow) {
|
||||
Options options = CurrentOptions();
|
||||
@@ -4156,4 +4474,4 @@ int main(int argc, char** argv) {
|
||||
::testing::InitGoogleTest(&argc, argv);
|
||||
RegisterCustomObjects(argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
}
|
||||
+54
-34
@@ -320,7 +320,7 @@ const Status& ErrorHandler::HandleKnownErrors(const Status& bg_err,
|
||||
// Check if recovery is currently in progress. If it is, we will save this
|
||||
// error so we can check it at the end to see if recovery succeeded or not
|
||||
if (recovery_in_prog_ && recovery_error_.ok()) {
|
||||
recovery_error_ = new_bg_err;
|
||||
recovery_error_ = status_to_io_status(Status(new_bg_err));
|
||||
}
|
||||
|
||||
bool auto_recovery = auto_recovery_;
|
||||
@@ -396,14 +396,13 @@ const Status& ErrorHandler::SetBGError(const Status& bg_status,
|
||||
ROCKS_LOG_WARN(db_options_.info_log, "Background IO error %s",
|
||||
bg_io_err.ToString().c_str());
|
||||
|
||||
if (recovery_in_prog_ && recovery_io_error_.ok()) {
|
||||
recovery_io_error_ = bg_io_err;
|
||||
}
|
||||
if (BackgroundErrorReason::kManifestWrite == reason ||
|
||||
BackgroundErrorReason::kManifestWriteNoWAL == reason) {
|
||||
if (!recovery_disabled_file_deletion_ &&
|
||||
(BackgroundErrorReason::kManifestWrite == reason ||
|
||||
BackgroundErrorReason::kManifestWriteNoWAL == reason)) {
|
||||
// Always returns ok
|
||||
ROCKS_LOG_INFO(db_options_.info_log, "Disabling File Deletions");
|
||||
db_->DisableFileDeletionsWithLock().PermitUncheckedError();
|
||||
recovery_disabled_file_deletion_ = true;
|
||||
}
|
||||
|
||||
Status new_bg_io_err = bg_io_err;
|
||||
@@ -472,6 +471,8 @@ const Status& ErrorHandler::SetBGError(const Status& bg_status,
|
||||
ROCKS_LOG_INFO(
|
||||
db_options_.info_log,
|
||||
"ErrorHandler: Compaction will schedule by itself to resume\n");
|
||||
// Not used in this code path.
|
||||
new_bg_io_err.PermitUncheckedError();
|
||||
return bg_error_;
|
||||
} else if (BackgroundErrorReason::kFlushNoWAL == reason ||
|
||||
BackgroundErrorReason::kManifestWriteNoWAL == reason) {
|
||||
@@ -500,10 +501,6 @@ const Status& ErrorHandler::SetBGError(const Status& bg_status,
|
||||
RecordTick(bg_error_stats_.get(),
|
||||
ERROR_HANDLER_BG_IO_ERROR_COUNT_MISSPELLED);
|
||||
}
|
||||
// HandleKnownErrors() will use recovery_error_, so ignore
|
||||
// recovery_io_error_.
|
||||
// TODO: Do some refactoring and use only one recovery_error_
|
||||
recovery_io_error_.PermitUncheckedError();
|
||||
return HandleKnownErrors(new_bg_io_err, reason);
|
||||
}
|
||||
}
|
||||
@@ -560,11 +557,23 @@ Status ErrorHandler::ClearBGError() {
|
||||
old_bg_error.PermitUncheckedError();
|
||||
// Clear and check the recovery IO and BG error
|
||||
bg_error_ = Status::OK();
|
||||
recovery_io_error_ = IOStatus::OK();
|
||||
recovery_error_ = IOStatus::OK();
|
||||
bg_error_.PermitUncheckedError();
|
||||
recovery_io_error_.PermitUncheckedError();
|
||||
recovery_error_.PermitUncheckedError();
|
||||
recovery_in_prog_ = false;
|
||||
soft_error_no_bg_work_ = false;
|
||||
if (recovery_disabled_file_deletion_) {
|
||||
recovery_disabled_file_deletion_ = false;
|
||||
int remain_counter = db_->EnableFileDeletionsWithLock();
|
||||
if (remain_counter == 0) {
|
||||
ROCKS_LOG_INFO(db_options_.info_log, "File Deletions Enabled");
|
||||
} else {
|
||||
ROCKS_LOG_WARN(
|
||||
db_options_.info_log,
|
||||
"File Deletions Enable, but not really enabled. Counter: %d",
|
||||
remain_counter);
|
||||
}
|
||||
}
|
||||
EventHelpers::NotifyOnErrorRecoveryEnd(db_options_.listeners, old_bg_error,
|
||||
bg_error_, db_mutex_);
|
||||
}
|
||||
@@ -600,14 +609,14 @@ Status ErrorHandler::RecoverFromBGError(bool is_manual) {
|
||||
if (bg_error_.severity() == Status::Severity::kSoftError &&
|
||||
recover_context_.flush_reason == FlushReason::kErrorRecovery) {
|
||||
// Simply clear the background error and return
|
||||
recovery_error_ = Status::OK();
|
||||
recovery_error_ = IOStatus::OK();
|
||||
return ClearBGError();
|
||||
}
|
||||
|
||||
// Reset recovery_error_. We will use this to record any errors that happen
|
||||
// during the recovery process. While recovering, the only operations that
|
||||
// can generate background errors should be the flush operations
|
||||
recovery_error_ = Status::OK();
|
||||
recovery_error_ = IOStatus::OK();
|
||||
recovery_error_.PermitUncheckedError();
|
||||
Status s = db_->ResumeImpl(recover_context_);
|
||||
if (s.ok()) {
|
||||
@@ -643,20 +652,27 @@ const Status& ErrorHandler::StartRecoverFromRetryableBGIOError(
|
||||
ROCKS_LOG_INFO(
|
||||
db_options_.info_log,
|
||||
"ErrorHandler: Call StartRecoverFromRetryableBGIOError to resume\n");
|
||||
// Needs to be set in the same lock hold as setting BG error, otherwise
|
||||
// intervening writes could see a BG error without a recovery and bail out.
|
||||
recovery_in_prog_ = true;
|
||||
|
||||
if (recovery_thread_) {
|
||||
// Ensure only one thread can execute the join().
|
||||
std::unique_ptr<port::Thread> old_recovery_thread(
|
||||
std::move(recovery_thread_));
|
||||
// In this case, if recovery_in_prog_ is false, current thread should
|
||||
// wait the previous recover thread to finish and create a new thread
|
||||
// to recover from the bg error.
|
||||
db_mutex_->Unlock();
|
||||
recovery_thread_->join();
|
||||
old_recovery_thread->join();
|
||||
db_mutex_->Lock();
|
||||
}
|
||||
|
||||
recovery_in_prog_ = true;
|
||||
TEST_SYNC_POINT("StartRecoverFromRetryableBGIOError::in_progress");
|
||||
recovery_thread_.reset(
|
||||
new port::Thread(&ErrorHandler::RecoverFromRetryableBGIOError, this));
|
||||
|
||||
if (recovery_io_error_.ok() && recovery_error_.ok()) {
|
||||
if (recovery_error_.ok()) {
|
||||
return recovery_error_;
|
||||
} else {
|
||||
return bg_error_;
|
||||
@@ -667,14 +683,18 @@ const Status& ErrorHandler::StartRecoverFromRetryableBGIOError(
|
||||
// mutex is released.
|
||||
void ErrorHandler::RecoverFromRetryableBGIOError() {
|
||||
TEST_SYNC_POINT("RecoverFromRetryableBGIOError:BeforeStart");
|
||||
TEST_SYNC_POINT("RecoverFromRetryableBGIOError:BeforeStart2");
|
||||
InstrumentedMutexLock l(db_mutex_);
|
||||
if (end_recovery_) {
|
||||
EventHelpers::NotifyOnErrorRecoveryEnd(db_options_.listeners, bg_error_,
|
||||
Status::ShutdownInProgress(),
|
||||
db_mutex_);
|
||||
|
||||
recovery_in_prog_ = false;
|
||||
return;
|
||||
}
|
||||
DBRecoverContext context = recover_context_;
|
||||
context.flush_after_recovery = true;
|
||||
int resume_count = db_options_.max_bgerror_resume_count;
|
||||
uint64_t wait_interval = db_options_.bgerror_resume_retry_interval;
|
||||
uint64_t retry_count = 0;
|
||||
@@ -684,12 +704,12 @@ void ErrorHandler::RecoverFromRetryableBGIOError() {
|
||||
EventHelpers::NotifyOnErrorRecoveryEnd(db_options_.listeners, bg_error_,
|
||||
Status::ShutdownInProgress(),
|
||||
db_mutex_);
|
||||
recovery_in_prog_ = false;
|
||||
return;
|
||||
}
|
||||
TEST_SYNC_POINT("RecoverFromRetryableBGIOError:BeforeResume0");
|
||||
TEST_SYNC_POINT("RecoverFromRetryableBGIOError:BeforeResume1");
|
||||
recovery_io_error_ = IOStatus::OK();
|
||||
recovery_error_ = Status::OK();
|
||||
recovery_error_ = IOStatus::OK();
|
||||
retry_count++;
|
||||
Status s = db_->ResumeImpl(context);
|
||||
if (bg_error_stats_ != nullptr) {
|
||||
@@ -709,9 +729,9 @@ void ErrorHandler::RecoverFromRetryableBGIOError() {
|
||||
bg_error_, db_mutex_);
|
||||
return;
|
||||
}
|
||||
if (!recovery_io_error_.ok() &&
|
||||
if (!recovery_error_.ok() &&
|
||||
recovery_error_.severity() <= Status::Severity::kHardError &&
|
||||
recovery_io_error_.GetRetryable()) {
|
||||
recovery_error_.GetRetryable()) {
|
||||
// If new BG IO error happens during auto recovery and it is retryable
|
||||
// and its severity is Hard Error or lower, the auto resmue sleep for
|
||||
// a period of time and redo auto resume if it is allowed.
|
||||
@@ -720,10 +740,10 @@ void ErrorHandler::RecoverFromRetryableBGIOError() {
|
||||
int64_t wait_until = db_options_.clock->NowMicros() + wait_interval;
|
||||
cv_.TimedWait(wait_until);
|
||||
} else {
|
||||
// There are three possibility: 1) recover_io_error is set during resume
|
||||
// There are three possibility: 1) recovery_error_ is set during resume
|
||||
// and the error is not retryable, 2) recover is successful, 3) other
|
||||
// error happens during resume and cannot be resumed here.
|
||||
if (recovery_io_error_.ok() && recovery_error_.ok() && s.ok()) {
|
||||
if (recovery_error_.ok() && s.ok()) {
|
||||
// recover from the retryable IO error and no other BG errors. Clean
|
||||
// the bg_error and notify user.
|
||||
TEST_SYNC_POINT("RecoverFromRetryableBGIOError:RecoverSuccess");
|
||||
@@ -745,8 +765,8 @@ void ErrorHandler::RecoverFromRetryableBGIOError() {
|
||||
}
|
||||
return;
|
||||
} else {
|
||||
// In this case: 1) recovery_io_error is more serious or not retryable
|
||||
// 2) other Non IO recovery_error happens. The auto recovery stops.
|
||||
// In this case: 1) recovery_error_ is more serious or not retryable
|
||||
// 2) other error happens. The auto recovery stops.
|
||||
recovery_in_prog_ = false;
|
||||
if (bg_error_stats_ != nullptr) {
|
||||
RecordInHistogram(bg_error_stats_.get(),
|
||||
@@ -754,10 +774,7 @@ void ErrorHandler::RecoverFromRetryableBGIOError() {
|
||||
}
|
||||
EventHelpers::NotifyOnErrorRecoveryEnd(
|
||||
db_options_.listeners, bg_error_,
|
||||
!recovery_io_error_.ok()
|
||||
? recovery_io_error_
|
||||
: (!recovery_error_.ok() ? recovery_error_ : s),
|
||||
db_mutex_);
|
||||
!recovery_error_.ok() ? recovery_error_ : s, db_mutex_);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -777,7 +794,7 @@ void ErrorHandler::RecoverFromRetryableBGIOError() {
|
||||
|
||||
void ErrorHandler::CheckAndSetRecoveryAndBGError(const Status& bg_err) {
|
||||
if (recovery_in_prog_ && recovery_error_.ok()) {
|
||||
recovery_error_ = bg_err;
|
||||
recovery_error_ = status_to_io_status(Status(bg_err));
|
||||
}
|
||||
if (bg_err.severity() > bg_error_.severity()) {
|
||||
bg_error_ = bg_err;
|
||||
@@ -793,12 +810,15 @@ void ErrorHandler::EndAutoRecovery() {
|
||||
if (!end_recovery_) {
|
||||
end_recovery_ = true;
|
||||
}
|
||||
cv_.SignalAll();
|
||||
db_mutex_->Unlock();
|
||||
if (recovery_thread_) {
|
||||
recovery_thread_->join();
|
||||
// Ensure only one thread can execute the join().
|
||||
std::unique_ptr<port::Thread> old_recovery_thread(
|
||||
std::move(recovery_thread_));
|
||||
db_mutex_->Unlock();
|
||||
cv_.SignalAll();
|
||||
old_recovery_thread->join();
|
||||
db_mutex_->Lock();
|
||||
}
|
||||
db_mutex_->Lock();
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
+13
-9
@@ -19,10 +19,13 @@ class DBImpl;
|
||||
// FlushReason, which tells the flush job why this flush is called.
|
||||
struct DBRecoverContext {
|
||||
FlushReason flush_reason;
|
||||
bool flush_after_recovery;
|
||||
|
||||
DBRecoverContext() : flush_reason(FlushReason::kErrorRecovery) {}
|
||||
|
||||
DBRecoverContext(FlushReason reason) : flush_reason(reason) {}
|
||||
DBRecoverContext()
|
||||
: flush_reason(FlushReason::kErrorRecovery),
|
||||
flush_after_recovery(false) {}
|
||||
DBRecoverContext(FlushReason reason)
|
||||
: flush_reason(reason), flush_after_recovery(false) {}
|
||||
};
|
||||
|
||||
class ErrorHandler {
|
||||
@@ -39,11 +42,11 @@ class ErrorHandler {
|
||||
recovery_in_prog_(false),
|
||||
soft_error_no_bg_work_(false),
|
||||
is_db_stopped_(false),
|
||||
bg_error_stats_(db_options.statistics) {
|
||||
bg_error_stats_(db_options.statistics),
|
||||
recovery_disabled_file_deletion_(false) {
|
||||
// Clear the checked flag for uninitialized errors
|
||||
bg_error_.PermitUncheckedError();
|
||||
recovery_error_.PermitUncheckedError();
|
||||
recovery_io_error_.PermitUncheckedError();
|
||||
}
|
||||
|
||||
void EnableAutoRecovery() { auto_recovery_ = true; }
|
||||
@@ -84,10 +87,7 @@ class ErrorHandler {
|
||||
Status bg_error_;
|
||||
// A separate Status variable used to record any errors during the
|
||||
// recovery process from hard errors
|
||||
Status recovery_error_;
|
||||
// A separate IO Status variable used to record any IO errors during
|
||||
// the recovery process. At the same time, recovery_error_ is also set.
|
||||
IOStatus recovery_io_error_;
|
||||
IOStatus recovery_error_;
|
||||
// The condition variable used with db_mutex during auto resume for time
|
||||
// wait.
|
||||
InstrumentedCondVar cv_;
|
||||
@@ -109,6 +109,10 @@ class ErrorHandler {
|
||||
// The pointer of DB statistics.
|
||||
std::shared_ptr<Statistics> bg_error_stats_;
|
||||
|
||||
// Tracks whether the recovery has disabled file deletion. This boolean flag
|
||||
// is updated while holding db mutex.
|
||||
bool recovery_disabled_file_deletion_;
|
||||
|
||||
const Status& HandleKnownErrors(const Status& bg_err,
|
||||
BackgroundErrorReason reason);
|
||||
Status OverrideNoSpaceError(const Status& bg_error, bool* auto_recovery);
|
||||
|
||||
@@ -240,6 +240,8 @@ void EventHelpers::NotifyOnErrorRecoveryEnd(
|
||||
info.new_bg_error.PermitUncheckedError();
|
||||
}
|
||||
db_mutex->Lock();
|
||||
} else {
|
||||
old_bg_error.PermitUncheckedError();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -226,7 +226,8 @@ Status ExternalSstFileIngestionJob::Prepare(
|
||||
&generated_checksum_func_name,
|
||||
ingestion_options_.verify_checksums_readahead_size,
|
||||
db_options_.allow_mmap_reads, io_tracer_,
|
||||
db_options_.rate_limiter.get(), ro);
|
||||
db_options_.rate_limiter.get(), ro, db_options_.stats,
|
||||
db_options_.clock);
|
||||
if (!io_s.ok()) {
|
||||
status = io_s;
|
||||
ROCKS_LOG_WARN(db_options_.info_log,
|
||||
@@ -1067,7 +1068,7 @@ IOStatus ExternalSstFileIngestionJob::GenerateChecksumForIngestedFile(
|
||||
&file_checksum, &file_checksum_func_name,
|
||||
ingestion_options_.verify_checksums_readahead_size,
|
||||
db_options_.allow_mmap_reads, io_tracer_, db_options_.rate_limiter.get(),
|
||||
ro);
|
||||
ro, db_options_.stats, db_options_.clock);
|
||||
if (!io_s.ok()) {
|
||||
return io_s;
|
||||
}
|
||||
|
||||
@@ -588,6 +588,63 @@ TEST_F(ExternalSSTFileTest, BasicWideColumn) {
|
||||
kRangeDelSkipConfigs));
|
||||
}
|
||||
|
||||
TEST_F(ExternalSSTFileTest, BasicMixed) {
|
||||
do {
|
||||
Options options = CurrentOptions();
|
||||
|
||||
SstFileWriter sst_file_writer(EnvOptions(), options);
|
||||
|
||||
// Current file size should be 0 after sst_file_writer init and before open
|
||||
// a file.
|
||||
ASSERT_EQ(sst_file_writer.FileSize(), 0);
|
||||
|
||||
std::string file = sst_files_dir_ + "mixed_file.sst";
|
||||
ASSERT_OK(sst_file_writer.Open(file));
|
||||
for (int k = 0; k < 100; k++) {
|
||||
if (k % 5 == 0) {
|
||||
std::string val1 = Key(k) + "_attr_1_val";
|
||||
std::string val2 = Key(k) + "_attr_2_val";
|
||||
WideColumns columns{{"attr_1", val1}, {"attr_2", val2}};
|
||||
ASSERT_OK(sst_file_writer.PutEntity(Key(k), columns));
|
||||
} else {
|
||||
ASSERT_OK(sst_file_writer.Put(Key(k), Key(k) + "_val"));
|
||||
}
|
||||
}
|
||||
ExternalSstFileInfo file_info;
|
||||
ASSERT_OK(sst_file_writer.Finish(&file_info));
|
||||
|
||||
// Current file size should be non-zero after success write.
|
||||
ASSERT_GT(sst_file_writer.FileSize(), 0);
|
||||
|
||||
ASSERT_EQ(file_info.file_path, file);
|
||||
ASSERT_EQ(file_info.num_entries, 100);
|
||||
ASSERT_EQ(file_info.smallest_key, Key(0));
|
||||
ASSERT_EQ(file_info.largest_key, Key(99));
|
||||
ASSERT_EQ(file_info.num_range_del_entries, 0);
|
||||
ASSERT_EQ(file_info.smallest_range_del_key, "");
|
||||
ASSERT_EQ(file_info.largest_range_del_key, "");
|
||||
|
||||
DestroyAndReopen(options);
|
||||
// Add file using file path
|
||||
ASSERT_OK(DeprecatedAddFile({file}));
|
||||
ASSERT_EQ(db_->GetLatestSequenceNumber(), 0U);
|
||||
for (int k = 0; k < 10; k++) {
|
||||
if (k % 5 == 0) {
|
||||
PinnableWideColumns result;
|
||||
ASSERT_OK(db_->GetEntity(ReadOptions(), db_->DefaultColumnFamily(),
|
||||
Key(k), &result));
|
||||
std::string val1 = Key(k) + "_attr_1_val";
|
||||
std::string val2 = Key(k) + "_attr_2_val";
|
||||
WideColumns expected_columns{{"attr_1", val1}, {"attr_2", val2}};
|
||||
ASSERT_EQ(result.columns(), expected_columns);
|
||||
} else {
|
||||
ASSERT_EQ(Get(Key(k)), Key(k) + "_val");
|
||||
}
|
||||
}
|
||||
} while (ChangeOptions(kSkipPlainTable | kSkipFIFOCompaction |
|
||||
kRangeDelSkipConfigs));
|
||||
}
|
||||
|
||||
class SstFileWriterCollector : public TablePropertiesCollector {
|
||||
public:
|
||||
explicit SstFileWriterCollector(const std::string prefix) : prefix_(prefix) {
|
||||
|
||||
+38
-22
@@ -79,6 +79,8 @@ const char* GetFlushReasonString(FlushReason flush_reason) {
|
||||
return "Error Recovery Retry Flush";
|
||||
case FlushReason::kWalFull:
|
||||
return "WAL Full";
|
||||
case FlushReason::kCatchUpAfterErrorRecovery:
|
||||
return "Catch Up After Error Recovery";
|
||||
default:
|
||||
return "Invalid";
|
||||
}
|
||||
@@ -215,7 +217,8 @@ void FlushJob::PickMemTable() {
|
||||
}
|
||||
|
||||
Status FlushJob::Run(LogsWithPrepTracker* prep_tracker, FileMetaData* file_meta,
|
||||
bool* switched_to_mempurge) {
|
||||
bool* switched_to_mempurge, bool* skipped_since_bg_error,
|
||||
ErrorHandler* error_handler) {
|
||||
TEST_SYNC_POINT("FlushJob::Start");
|
||||
db_mutex_->AssertHeld();
|
||||
assert(pick_memtable_called);
|
||||
@@ -303,17 +306,32 @@ Status FlushJob::Run(LogsWithPrepTracker* prep_tracker, FileMetaData* file_meta,
|
||||
}
|
||||
|
||||
if (!s.ok()) {
|
||||
cfd_->imm()->RollbackMemtableFlush(mems_, meta_.fd.GetNumber());
|
||||
cfd_->imm()->RollbackMemtableFlush(
|
||||
mems_, /*rollback_succeeding_memtables=*/!db_options_.atomic_flush);
|
||||
} else if (write_manifest_) {
|
||||
TEST_SYNC_POINT("FlushJob::InstallResults");
|
||||
// Replace immutable memtable with the generated Table
|
||||
s = cfd_->imm()->TryInstallMemtableFlushResults(
|
||||
cfd_, mutable_cf_options_, mems_, prep_tracker, versions_, db_mutex_,
|
||||
meta_.fd.GetNumber(), &job_context_->memtables_to_free, db_directory_,
|
||||
log_buffer_, &committed_flush_jobs_info_,
|
||||
!(mempurge_s.ok()) /* write_edit : true if no mempurge happened (or if aborted),
|
||||
assert(!db_options_.atomic_flush);
|
||||
if (!db_options_.atomic_flush &&
|
||||
flush_reason_ != FlushReason::kErrorRecovery &&
|
||||
flush_reason_ != FlushReason::kErrorRecoveryRetryFlush &&
|
||||
error_handler && !error_handler->GetBGError().ok() &&
|
||||
error_handler->IsBGWorkStopped()) {
|
||||
cfd_->imm()->RollbackMemtableFlush(
|
||||
mems_, /*rollback_succeeding_memtables=*/!db_options_.atomic_flush);
|
||||
s = error_handler->GetBGError();
|
||||
if (skipped_since_bg_error) {
|
||||
*skipped_since_bg_error = true;
|
||||
}
|
||||
} else {
|
||||
TEST_SYNC_POINT("FlushJob::InstallResults");
|
||||
// Replace immutable memtable with the generated Table
|
||||
s = cfd_->imm()->TryInstallMemtableFlushResults(
|
||||
cfd_, mutable_cf_options_, mems_, prep_tracker, versions_, db_mutex_,
|
||||
meta_.fd.GetNumber(), &job_context_->memtables_to_free, db_directory_,
|
||||
log_buffer_, &committed_flush_jobs_info_,
|
||||
!(mempurge_s.ok()) /* write_edit : true if no mempurge happened (or if aborted),
|
||||
but 'false' if mempurge successful: no new min log number
|
||||
or new level 0 file path to write to manifest. */);
|
||||
}
|
||||
}
|
||||
|
||||
if (s.ok() && file_meta != nullptr) {
|
||||
@@ -965,6 +983,7 @@ Status FlushJob::WriteLevel0Table() {
|
||||
&table_properties_, write_hint, full_history_ts_low,
|
||||
blob_callback_, base_, &num_input_entries,
|
||||
&memtable_payload_bytes, &memtable_garbage_bytes);
|
||||
TEST_SYNC_POINT_CALLBACK("FlushJob::WriteLevel0Table:s", &s);
|
||||
// TODO: Cleanup io_status in BuildTable and table builders
|
||||
assert(!s.ok() || io_s.ok());
|
||||
io_s.PermitUncheckedError();
|
||||
@@ -1122,16 +1141,16 @@ void FlushJob::GetEffectiveCutoffUDTForPickedMemTables() {
|
||||
cfd_->ioptions()->persist_user_defined_timestamps) {
|
||||
return;
|
||||
}
|
||||
// Find the newest user-defined timestamps from all the flushed memtables.
|
||||
for (MemTable* m : mems_) {
|
||||
Slice table_newest_udt = m->GetNewestUDT();
|
||||
// The picked Memtables should have ascending ID, and should have
|
||||
// non-decreasing newest user-defined timestamps.
|
||||
if (!cutoff_udt_.empty()) {
|
||||
assert(table_newest_udt.size() == cutoff_udt_.size());
|
||||
assert(ucmp->CompareTimestamp(table_newest_udt, cutoff_udt_) >= 0);
|
||||
cutoff_udt_.clear();
|
||||
if (cutoff_udt_.empty() ||
|
||||
ucmp->CompareTimestamp(table_newest_udt, cutoff_udt_) > 0) {
|
||||
if (!cutoff_udt_.empty()) {
|
||||
assert(table_newest_udt.size() == cutoff_udt_.size());
|
||||
}
|
||||
cutoff_udt_.assign(table_newest_udt.data(), table_newest_udt.size());
|
||||
}
|
||||
cutoff_udt_.assign(table_newest_udt.data(), table_newest_udt.size());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1147,16 +1166,13 @@ Status FlushJob::MaybeIncreaseFullHistoryTsLowToAboveCutoffUDT() {
|
||||
ucmp->CompareTimestamp(cutoff_udt_, full_history_ts_low) < 0)) {
|
||||
return Status::OK();
|
||||
}
|
||||
Slice cutoff_udt_slice = cutoff_udt_;
|
||||
uint64_t cutoff_udt_ts = 0;
|
||||
bool format_res = GetFixed64(&cutoff_udt_slice, &cutoff_udt_ts);
|
||||
assert(format_res);
|
||||
(void)format_res;
|
||||
std::string new_full_history_ts_low;
|
||||
Slice cutoff_udt_slice = cutoff_udt_;
|
||||
// TODO(yuzhangyu): Add a member to AdvancedColumnFamilyOptions for an
|
||||
// operation to get the next immediately larger user-defined timestamp to
|
||||
// expand this feature to other user-defined timestamp formats.
|
||||
PutFixed64(&new_full_history_ts_low, cutoff_udt_ts + 1);
|
||||
GetFullHistoryTsLowFromU64CutoffTs(&cutoff_udt_slice,
|
||||
&new_full_history_ts_low);
|
||||
VersionEdit edit;
|
||||
edit.SetColumnFamily(cfd_->GetID());
|
||||
edit.SetFullHistoryTsLow(new_full_history_ts_low);
|
||||
|
||||
+6
-1
@@ -83,9 +83,14 @@ class FlushJob {
|
||||
// Require db_mutex held.
|
||||
// Once PickMemTable() is called, either Run() or Cancel() has to be called.
|
||||
void PickMemTable();
|
||||
// @param skip_since_bg_error If not nullptr and if atomic_flush=false,
|
||||
// then it is set to true if flush installation is skipped and memtable
|
||||
// is rolled back due to existing background error.
|
||||
Status Run(LogsWithPrepTracker* prep_tracker = nullptr,
|
||||
FileMetaData* file_meta = nullptr,
|
||||
bool* switched_to_mempurge = nullptr);
|
||||
bool* switched_to_mempurge = nullptr,
|
||||
bool* skipped_since_bg_error = nullptr,
|
||||
ErrorHandler* error_handler = nullptr);
|
||||
void Cancel();
|
||||
const autovector<MemTable*>& GetMemTables() const { return mems_; }
|
||||
|
||||
|
||||
+18
-70
@@ -1054,25 +1054,15 @@ static bool SaveValue(void* arg, const char* entry) {
|
||||
assert(s->do_merge);
|
||||
|
||||
if (s->value || s->columns) {
|
||||
std::string result;
|
||||
// `op_failure_scope` (an output parameter) is not provided (set to
|
||||
// nullptr) since a failure must be propagated regardless of its
|
||||
// value.
|
||||
*(s->status) = MergeHelper::TimedFullMerge(
|
||||
merge_operator, s->key->user_key(), &v,
|
||||
merge_context->GetOperands(), &result, s->logger, s->statistics,
|
||||
s->clock, /* result_operand */ nullptr,
|
||||
/* update_num_ops_stats */ true,
|
||||
merge_operator, s->key->user_key(),
|
||||
MergeHelper::kPlainBaseValue, v, merge_context->GetOperands(),
|
||||
s->logger, s->statistics, s->clock,
|
||||
/* update_num_ops_stats */ true, s->value, s->columns,
|
||||
/* op_failure_scope */ nullptr);
|
||||
|
||||
if (s->status->ok()) {
|
||||
if (s->value) {
|
||||
*(s->value) = std::move(result);
|
||||
} else {
|
||||
assert(s->columns);
|
||||
s->columns->SetPlainValue(std::move(result));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (s->value) {
|
||||
s->value->assign(v.data(), v.size());
|
||||
@@ -1117,35 +1107,15 @@ static bool SaveValue(void* arg, const char* entry) {
|
||||
} else if (*(s->merge_in_progress)) {
|
||||
assert(s->do_merge);
|
||||
|
||||
if (s->value) {
|
||||
Slice value_of_default;
|
||||
*(s->status) = WideColumnSerialization::GetValueOfDefaultColumn(
|
||||
v, value_of_default);
|
||||
if (s->status->ok()) {
|
||||
// `op_failure_scope` (an output parameter) is not provided (set
|
||||
// to nullptr) since a failure must be propagated regardless of
|
||||
// its value.
|
||||
*(s->status) = MergeHelper::TimedFullMerge(
|
||||
merge_operator, s->key->user_key(), &value_of_default,
|
||||
merge_context->GetOperands(), s->value, s->logger,
|
||||
s->statistics, s->clock, /* result_operand */ nullptr,
|
||||
/* update_num_ops_stats */ true,
|
||||
/* op_failure_scope */ nullptr);
|
||||
}
|
||||
} else if (s->columns) {
|
||||
std::string result;
|
||||
// `op_failure_scope` (an output parameter) is not provided (set to
|
||||
// nullptr) since a failure must be propagated regardless of its
|
||||
// value.
|
||||
*(s->status) = MergeHelper::TimedFullMergeWithEntity(
|
||||
merge_operator, s->key->user_key(), v,
|
||||
merge_context->GetOperands(), &result, s->logger, s->statistics,
|
||||
s->clock, /* update_num_ops_stats */ true,
|
||||
if (s->value || s->columns) {
|
||||
// `op_failure_scope` (an output parameter) is not provided (set
|
||||
// to nullptr) since a failure must be propagated regardless of
|
||||
// its value.
|
||||
*(s->status) = MergeHelper::TimedFullMerge(
|
||||
merge_operator, s->key->user_key(), MergeHelper::kWideBaseValue,
|
||||
v, merge_context->GetOperands(), s->logger, s->statistics,
|
||||
s->clock, /* update_num_ops_stats */ true, s->value, s->columns,
|
||||
/* op_failure_scope */ nullptr);
|
||||
|
||||
if (s->status->ok()) {
|
||||
*(s->status) = s->columns->SetWideColumnValue(std::move(result));
|
||||
}
|
||||
}
|
||||
} else if (s->value) {
|
||||
Slice value_of_default;
|
||||
@@ -1176,25 +1146,14 @@ static bool SaveValue(void* arg, const char* entry) {
|
||||
case kTypeRangeDeletion: {
|
||||
if (*(s->merge_in_progress)) {
|
||||
if (s->value || s->columns) {
|
||||
std::string result;
|
||||
// `op_failure_scope` (an output parameter) is not provided (set to
|
||||
// nullptr) since a failure must be propagated regardless of its
|
||||
// value.
|
||||
*(s->status) = MergeHelper::TimedFullMerge(
|
||||
merge_operator, s->key->user_key(), nullptr,
|
||||
merge_context->GetOperands(), &result, s->logger, s->statistics,
|
||||
s->clock, /* result_operand */ nullptr,
|
||||
/* update_num_ops_stats */ true,
|
||||
merge_operator, s->key->user_key(), MergeHelper::kNoBaseValue,
|
||||
merge_context->GetOperands(), s->logger, s->statistics,
|
||||
s->clock, /* update_num_ops_stats */ true, s->value, s->columns,
|
||||
/* op_failure_scope */ nullptr);
|
||||
|
||||
if (s->status->ok()) {
|
||||
if (s->value) {
|
||||
*(s->value) = std::move(result);
|
||||
} else {
|
||||
assert(s->columns);
|
||||
s->columns->SetPlainValue(std::move(result));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// We have found a final value (a base deletion) and have newer
|
||||
// merge operands that we do not intend to merge. Nothing remains
|
||||
@@ -1227,25 +1186,14 @@ static bool SaveValue(void* arg, const char* entry) {
|
||||
if (s->do_merge && merge_operator->ShouldMerge(
|
||||
merge_context->GetOperandsDirectionBackward())) {
|
||||
if (s->value || s->columns) {
|
||||
std::string result;
|
||||
// `op_failure_scope` (an output parameter) is not provided (set to
|
||||
// nullptr) since a failure must be propagated regardless of its
|
||||
// value.
|
||||
*(s->status) = MergeHelper::TimedFullMerge(
|
||||
merge_operator, s->key->user_key(), nullptr,
|
||||
merge_context->GetOperands(), &result, s->logger, s->statistics,
|
||||
s->clock, /* result_operand */ nullptr,
|
||||
/* update_num_ops_stats */ true,
|
||||
merge_operator, s->key->user_key(), MergeHelper::kNoBaseValue,
|
||||
merge_context->GetOperands(), s->logger, s->statistics,
|
||||
s->clock, /* update_num_ops_stats */ true, s->value, s->columns,
|
||||
/* op_failure_scope */ nullptr);
|
||||
|
||||
if (s->status->ok()) {
|
||||
if (s->value) {
|
||||
*(s->value) = std::move(result);
|
||||
} else {
|
||||
assert(s->columns);
|
||||
s->columns->SetPlainValue(std::move(result));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
*(s->found_final_value) = true;
|
||||
|
||||
+46
-12
@@ -184,7 +184,7 @@ bool MemTableListVersion::GetFromList(
|
||||
assert(*seq != kMaxSequenceNumber || s->IsNotFound());
|
||||
return true;
|
||||
}
|
||||
if (!done && !s->ok() && !s->IsMergeInProgress() && !s->IsNotFound()) {
|
||||
if (!s->ok() && !s->IsMergeInProgress() && !s->IsNotFound()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -434,23 +434,57 @@ void MemTableList::PickMemtablesToFlush(uint64_t max_memtable_id,
|
||||
}
|
||||
|
||||
void MemTableList::RollbackMemtableFlush(const autovector<MemTable*>& mems,
|
||||
uint64_t /*file_number*/) {
|
||||
bool rollback_succeeding_memtables) {
|
||||
TEST_SYNC_POINT("RollbackMemtableFlush");
|
||||
AutoThreadOperationStageUpdater stage_updater(
|
||||
ThreadStatus::STAGE_MEMTABLE_ROLLBACK);
|
||||
assert(!mems.empty());
|
||||
|
||||
// If the flush was not successful, then just reset state.
|
||||
// Maybe a succeeding attempt to flush will be successful.
|
||||
#ifndef NDEBUG
|
||||
for (MemTable* m : mems) {
|
||||
assert(m->flush_in_progress_);
|
||||
assert(m->file_number_ == 0);
|
||||
|
||||
m->flush_in_progress_ = false;
|
||||
m->flush_completed_ = false;
|
||||
m->edit_.Clear();
|
||||
num_flush_not_started_++;
|
||||
}
|
||||
imm_flush_needed.store(true, std::memory_order_release);
|
||||
#endif
|
||||
|
||||
if (rollback_succeeding_memtables && !mems.empty()) {
|
||||
std::list<MemTable*>& memlist = current_->memlist_;
|
||||
auto it = memlist.rbegin();
|
||||
for (; *it != mems[0] && it != memlist.rend(); ++it) {
|
||||
}
|
||||
// mems should be in memlist
|
||||
assert(*it == mems[0]);
|
||||
if (*it == mems[0]) {
|
||||
++it;
|
||||
}
|
||||
while (it != memlist.rend()) {
|
||||
MemTable* m = *it;
|
||||
// Only rollback complete, not in-progress,
|
||||
// in_progress can be flushes that are still writing SSTs
|
||||
if (m->flush_completed_) {
|
||||
m->flush_in_progress_ = false;
|
||||
m->flush_completed_ = false;
|
||||
m->edit_.Clear();
|
||||
m->file_number_ = 0;
|
||||
num_flush_not_started_++;
|
||||
++it;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (MemTable* m : mems) {
|
||||
if (m->flush_in_progress_) {
|
||||
assert(m->file_number_ == 0);
|
||||
m->file_number_ = 0;
|
||||
m->flush_in_progress_ = false;
|
||||
m->flush_completed_ = false;
|
||||
m->edit_.Clear();
|
||||
num_flush_not_started_++;
|
||||
}
|
||||
}
|
||||
if (!mems.empty()) {
|
||||
imm_flush_needed.store(true, std::memory_order_release);
|
||||
}
|
||||
}
|
||||
|
||||
// Try record a successful flush in the manifest file. It might just return
|
||||
|
||||
+13
-1
@@ -271,8 +271,20 @@ class MemTableList {
|
||||
|
||||
// Reset status of the given memtable list back to pending state so that
|
||||
// they can get picked up again on the next round of flush.
|
||||
//
|
||||
// @param rollback_succeeding_memtables If true, will rollback adjacent
|
||||
// younger memtables whose flush is completed. Specifically, suppose the
|
||||
// current immutable memtables are M_0,M_1...M_N ordered from youngest to
|
||||
// oldest. Suppose that the youngest memtable in `mems` is M_K. We will try to
|
||||
// rollback M_K-1, M_K-2... until the first memtable whose flush is
|
||||
// not completed. These are the memtables that would have been installed
|
||||
// by this flush job if it were to succeed. This flag is currently used
|
||||
// by non atomic_flush rollback.
|
||||
// Note that we also do rollback in `write_manifest_cb` by calling
|
||||
// `RemoveMemTablesOrRestoreFlags()`. There we rollback the entire batch so
|
||||
// it is similar to what we do here with rollback_succeeding_memtables=true.
|
||||
void RollbackMemtableFlush(const autovector<MemTable*>& mems,
|
||||
uint64_t file_number);
|
||||
bool rollback_succeeding_memtables);
|
||||
|
||||
// Try commit a successful flush in the manifest file. It might just return
|
||||
// Status::OK letting a concurrent flush to do the actual the recording.
|
||||
|
||||
@@ -682,7 +682,7 @@ TEST_F(MemTableListTest, FlushPendingTest) {
|
||||
ASSERT_FALSE(list.imm_flush_needed.load(std::memory_order_acquire));
|
||||
|
||||
// Revert flush
|
||||
list.RollbackMemtableFlush(to_flush, 0);
|
||||
list.RollbackMemtableFlush(to_flush, false);
|
||||
ASSERT_FALSE(list.IsFlushPending());
|
||||
ASSERT_TRUE(list.imm_flush_needed.load(std::memory_order_acquire));
|
||||
to_flush.clear();
|
||||
@@ -732,7 +732,7 @@ TEST_F(MemTableListTest, FlushPendingTest) {
|
||||
ASSERT_FALSE(list.imm_flush_needed.load(std::memory_order_acquire));
|
||||
|
||||
// Rollback first pick of tables
|
||||
list.RollbackMemtableFlush(to_flush, 0);
|
||||
list.RollbackMemtableFlush(to_flush, false);
|
||||
ASSERT_TRUE(list.IsFlushPending());
|
||||
ASSERT_TRUE(list.imm_flush_needed.load(std::memory_order_acquire));
|
||||
to_flush.clear();
|
||||
|
||||
+305
-119
@@ -13,6 +13,7 @@
|
||||
#include "db/compaction/compaction_iteration_stats.h"
|
||||
#include "db/dbformat.h"
|
||||
#include "db/wide/wide_column_serialization.h"
|
||||
#include "db/wide/wide_columns_helper.h"
|
||||
#include "logging/logging.h"
|
||||
#include "monitoring/perf_context_imp.h"
|
||||
#include "monitoring/statistics_impl.h"
|
||||
@@ -23,6 +24,7 @@
|
||||
#include "rocksdb/system_clock.h"
|
||||
#include "table/format.h"
|
||||
#include "table/internal_iterator.h"
|
||||
#include "util/overload.h"
|
||||
|
||||
namespace ROCKSDB_NAMESPACE {
|
||||
|
||||
@@ -56,120 +58,297 @@ MergeHelper::MergeHelper(Env* env, const Comparator* user_comparator,
|
||||
}
|
||||
}
|
||||
|
||||
Status MergeHelper::TimedFullMerge(
|
||||
const MergeOperator* merge_operator, const Slice& key, const Slice* value,
|
||||
const std::vector<Slice>& operands, std::string* result, Logger* logger,
|
||||
Statistics* statistics, SystemClock* clock, Slice* result_operand,
|
||||
bool update_num_ops_stats,
|
||||
MergeOperator::OpFailureScope* op_failure_scope) {
|
||||
assert(merge_operator != nullptr);
|
||||
|
||||
if (operands.empty()) {
|
||||
assert(value != nullptr && result != nullptr);
|
||||
result->assign(value->data(), value->size());
|
||||
return Status::OK();
|
||||
}
|
||||
template <typename Visitor>
|
||||
Status MergeHelper::TimedFullMergeCommonImpl(
|
||||
const MergeOperator* merge_operator, const Slice& key,
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue&& existing_value,
|
||||
const std::vector<Slice>& operands, Logger* logger, Statistics* statistics,
|
||||
SystemClock* clock, bool update_num_ops_stats,
|
||||
MergeOperator::OpFailureScope* op_failure_scope, Visitor&& visitor) {
|
||||
assert(merge_operator);
|
||||
assert(!operands.empty());
|
||||
|
||||
if (update_num_ops_stats) {
|
||||
RecordInHistogram(statistics, READ_NUM_MERGE_OPERANDS,
|
||||
static_cast<uint64_t>(operands.size()));
|
||||
}
|
||||
|
||||
const MergeOperator::MergeOperationInputV3 merge_in(
|
||||
key, std::move(existing_value), operands, logger);
|
||||
MergeOperator::MergeOperationOutputV3 merge_out;
|
||||
|
||||
bool success = false;
|
||||
Slice tmp_result_operand(nullptr, 0);
|
||||
const MergeOperator::MergeOperationInput merge_in(key, value, operands,
|
||||
logger);
|
||||
MergeOperator::MergeOperationOutput merge_out(*result, tmp_result_operand);
|
||||
|
||||
{
|
||||
// Setup to time the merge
|
||||
StopWatchNano timer(clock, statistics != nullptr);
|
||||
PERF_TIMER_GUARD(merge_operator_time_nanos);
|
||||
|
||||
// Do the merge
|
||||
success = merge_operator->FullMergeV2(merge_in, &merge_out);
|
||||
|
||||
if (tmp_result_operand.data()) {
|
||||
// FullMergeV2 result is an existing operand
|
||||
if (result_operand != nullptr) {
|
||||
*result_operand = tmp_result_operand;
|
||||
} else {
|
||||
result->assign(tmp_result_operand.data(), tmp_result_operand.size());
|
||||
}
|
||||
} else if (result_operand) {
|
||||
*result_operand = Slice(nullptr, 0);
|
||||
}
|
||||
success = merge_operator->FullMergeV3(merge_in, &merge_out);
|
||||
|
||||
RecordTick(statistics, MERGE_OPERATION_TOTAL_TIME,
|
||||
statistics ? timer.ElapsedNanos() : 0);
|
||||
}
|
||||
|
||||
if (op_failure_scope != nullptr) {
|
||||
*op_failure_scope = merge_out.op_failure_scope;
|
||||
// Apply default per merge_operator.h
|
||||
if (*op_failure_scope == MergeOperator::OpFailureScope::kDefault) {
|
||||
*op_failure_scope = MergeOperator::OpFailureScope::kTryMerge;
|
||||
}
|
||||
}
|
||||
|
||||
if (!success) {
|
||||
RecordTick(statistics, NUMBER_MERGE_FAILURES);
|
||||
|
||||
if (op_failure_scope) {
|
||||
*op_failure_scope = merge_out.op_failure_scope;
|
||||
// Apply default per merge_operator.h
|
||||
if (*op_failure_scope == MergeOperator::OpFailureScope::kDefault) {
|
||||
*op_failure_scope = MergeOperator::OpFailureScope::kTryMerge;
|
||||
}
|
||||
}
|
||||
|
||||
return Status::Corruption(Status::SubCode::kMergeOperatorFailed);
|
||||
}
|
||||
|
||||
return Status::OK();
|
||||
return std::visit(std::forward<Visitor>(visitor),
|
||||
std::move(merge_out.new_value));
|
||||
}
|
||||
|
||||
Status MergeHelper::TimedFullMergeWithEntity(
|
||||
const MergeOperator* merge_operator, const Slice& key, Slice base_entity,
|
||||
const std::vector<Slice>& operands, std::string* result, Logger* logger,
|
||||
Statistics* statistics, SystemClock* clock, bool update_num_ops_stats,
|
||||
Status MergeHelper::TimedFullMergeImpl(
|
||||
const MergeOperator* merge_operator, const Slice& key,
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue&& existing_value,
|
||||
const std::vector<Slice>& operands, Logger* logger, Statistics* statistics,
|
||||
SystemClock* clock, bool update_num_ops_stats, std::string* result,
|
||||
Slice* result_operand, ValueType* result_type,
|
||||
MergeOperator::OpFailureScope* op_failure_scope) {
|
||||
WideColumns base_columns;
|
||||
assert(result);
|
||||
assert(result_type);
|
||||
|
||||
{
|
||||
const Status s =
|
||||
WideColumnSerialization::Deserialize(base_entity, base_columns);
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
auto visitor = overload{
|
||||
[&](std::string&& new_value) -> Status {
|
||||
*result_type = kTypeValue;
|
||||
|
||||
if (result_operand) {
|
||||
*result_operand = Slice(nullptr, 0);
|
||||
}
|
||||
|
||||
*result = std::move(new_value);
|
||||
|
||||
return Status::OK();
|
||||
},
|
||||
[&](MergeOperator::MergeOperationOutputV3::NewColumns&& new_columns)
|
||||
-> Status {
|
||||
*result_type = kTypeWideColumnEntity;
|
||||
|
||||
if (result_operand) {
|
||||
*result_operand = Slice(nullptr, 0);
|
||||
}
|
||||
|
||||
result->clear();
|
||||
|
||||
WideColumns sorted_columns;
|
||||
sorted_columns.reserve(new_columns.size());
|
||||
|
||||
for (const auto& column : new_columns) {
|
||||
sorted_columns.emplace_back(column.first, column.second);
|
||||
}
|
||||
|
||||
WideColumnsHelper::SortColumns(sorted_columns);
|
||||
|
||||
return WideColumnSerialization::Serialize(sorted_columns, *result);
|
||||
},
|
||||
[&](Slice&& operand) -> Status {
|
||||
*result_type = kTypeValue;
|
||||
|
||||
if (result_operand) {
|
||||
*result_operand = operand;
|
||||
result->clear();
|
||||
} else {
|
||||
result->assign(operand.data(), operand.size());
|
||||
}
|
||||
|
||||
return Status::OK();
|
||||
}};
|
||||
|
||||
return TimedFullMergeCommonImpl(merge_operator, key,
|
||||
std::move(existing_value), operands, logger,
|
||||
statistics, clock, update_num_ops_stats,
|
||||
op_failure_scope, std::move(visitor));
|
||||
}
|
||||
|
||||
Status MergeHelper::TimedFullMergeImpl(
|
||||
const MergeOperator* merge_operator, const Slice& key,
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue&& existing_value,
|
||||
const std::vector<Slice>& operands, Logger* logger, Statistics* statistics,
|
||||
SystemClock* clock, bool update_num_ops_stats, std::string* result_value,
|
||||
PinnableWideColumns* result_entity,
|
||||
MergeOperator::OpFailureScope* op_failure_scope) {
|
||||
assert(result_value || result_entity);
|
||||
assert(!result_value || !result_entity);
|
||||
|
||||
auto visitor = overload{
|
||||
[&](std::string&& new_value) -> Status {
|
||||
if (result_value) {
|
||||
*result_value = std::move(new_value);
|
||||
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
assert(result_entity);
|
||||
result_entity->SetPlainValue(std::move(new_value));
|
||||
|
||||
return Status::OK();
|
||||
},
|
||||
[&](MergeOperator::MergeOperationOutputV3::NewColumns&& new_columns)
|
||||
-> Status {
|
||||
if (result_value) {
|
||||
if (!new_columns.empty() &&
|
||||
new_columns.front().first == kDefaultWideColumnName) {
|
||||
*result_value = std::move(new_columns.front().second);
|
||||
} else {
|
||||
result_value->clear();
|
||||
}
|
||||
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
assert(result_entity);
|
||||
|
||||
WideColumns sorted_columns;
|
||||
sorted_columns.reserve(new_columns.size());
|
||||
|
||||
for (const auto& column : new_columns) {
|
||||
sorted_columns.emplace_back(column.first, column.second);
|
||||
}
|
||||
|
||||
WideColumnsHelper::SortColumns(sorted_columns);
|
||||
|
||||
std::string result;
|
||||
const Status s =
|
||||
WideColumnSerialization::Serialize(sorted_columns, result);
|
||||
if (!s.ok()) {
|
||||
result_entity->Reset();
|
||||
return s;
|
||||
}
|
||||
|
||||
return result_entity->SetWideColumnValue(std::move(result));
|
||||
},
|
||||
[&](Slice&& operand) -> Status {
|
||||
if (result_value) {
|
||||
result_value->assign(operand.data(), operand.size());
|
||||
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
assert(result_entity);
|
||||
result_entity->SetPlainValue(operand);
|
||||
|
||||
return Status::OK();
|
||||
}};
|
||||
|
||||
return TimedFullMergeCommonImpl(merge_operator, key,
|
||||
std::move(existing_value), operands, logger,
|
||||
statistics, clock, update_num_ops_stats,
|
||||
op_failure_scope, std::move(visitor));
|
||||
}
|
||||
|
||||
Status MergeHelper::TimedFullMerge(
|
||||
const MergeOperator* merge_operator, const Slice& key, NoBaseValueTag,
|
||||
const std::vector<Slice>& operands, Logger* logger, Statistics* statistics,
|
||||
SystemClock* clock, bool update_num_ops_stats, std::string* result,
|
||||
Slice* result_operand, ValueType* result_type,
|
||||
MergeOperator::OpFailureScope* op_failure_scope) {
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue existing_value;
|
||||
|
||||
return TimedFullMergeImpl(merge_operator, key, std::move(existing_value),
|
||||
operands, logger, statistics, clock,
|
||||
update_num_ops_stats, result, result_operand,
|
||||
result_type, op_failure_scope);
|
||||
}
|
||||
|
||||
Status MergeHelper::TimedFullMerge(
|
||||
const MergeOperator* merge_operator, const Slice& key, PlainBaseValueTag,
|
||||
const Slice& value, const std::vector<Slice>& operands, Logger* logger,
|
||||
Statistics* statistics, SystemClock* clock, bool update_num_ops_stats,
|
||||
std::string* result, Slice* result_operand, ValueType* result_type,
|
||||
MergeOperator::OpFailureScope* op_failure_scope) {
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue existing_value(value);
|
||||
|
||||
return TimedFullMergeImpl(merge_operator, key, std::move(existing_value),
|
||||
operands, logger, statistics, clock,
|
||||
update_num_ops_stats, result, result_operand,
|
||||
result_type, op_failure_scope);
|
||||
}
|
||||
|
||||
Status MergeHelper::TimedFullMerge(
|
||||
const MergeOperator* merge_operator, const Slice& key, WideBaseValueTag,
|
||||
const Slice& entity, const std::vector<Slice>& operands, Logger* logger,
|
||||
Statistics* statistics, SystemClock* clock, bool update_num_ops_stats,
|
||||
std::string* result, Slice* result_operand, ValueType* result_type,
|
||||
MergeOperator::OpFailureScope* op_failure_scope) {
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue existing_value;
|
||||
|
||||
Slice entity_copy(entity);
|
||||
WideColumns existing_columns;
|
||||
|
||||
const Status s =
|
||||
WideColumnSerialization::Deserialize(entity_copy, existing_columns);
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
|
||||
const bool has_default_column =
|
||||
!base_columns.empty() && base_columns[0].name() == kDefaultWideColumnName;
|
||||
existing_value = std::move(existing_columns);
|
||||
|
||||
Slice value_of_default;
|
||||
if (has_default_column) {
|
||||
value_of_default = base_columns[0].value();
|
||||
return TimedFullMergeImpl(merge_operator, key, std::move(existing_value),
|
||||
operands, logger, statistics, clock,
|
||||
update_num_ops_stats, result, result_operand,
|
||||
result_type, op_failure_scope);
|
||||
}
|
||||
|
||||
Status MergeHelper::TimedFullMerge(
|
||||
const MergeOperator* merge_operator, const Slice& key, NoBaseValueTag,
|
||||
const std::vector<Slice>& operands, Logger* logger, Statistics* statistics,
|
||||
SystemClock* clock, bool update_num_ops_stats, std::string* result_value,
|
||||
PinnableWideColumns* result_entity,
|
||||
MergeOperator::OpFailureScope* op_failure_scope) {
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue existing_value;
|
||||
|
||||
return TimedFullMergeImpl(merge_operator, key, std::move(existing_value),
|
||||
operands, logger, statistics, clock,
|
||||
update_num_ops_stats, result_value, result_entity,
|
||||
op_failure_scope);
|
||||
}
|
||||
|
||||
Status MergeHelper::TimedFullMerge(
|
||||
const MergeOperator* merge_operator, const Slice& key, PlainBaseValueTag,
|
||||
const Slice& value, const std::vector<Slice>& operands, Logger* logger,
|
||||
Statistics* statistics, SystemClock* clock, bool update_num_ops_stats,
|
||||
std::string* result_value, PinnableWideColumns* result_entity,
|
||||
MergeOperator::OpFailureScope* op_failure_scope) {
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue existing_value(value);
|
||||
|
||||
return TimedFullMergeImpl(merge_operator, key, std::move(existing_value),
|
||||
operands, logger, statistics, clock,
|
||||
update_num_ops_stats, result_value, result_entity,
|
||||
op_failure_scope);
|
||||
}
|
||||
|
||||
Status MergeHelper::TimedFullMerge(
|
||||
const MergeOperator* merge_operator, const Slice& key, WideBaseValueTag,
|
||||
const Slice& entity, const std::vector<Slice>& operands, Logger* logger,
|
||||
Statistics* statistics, SystemClock* clock, bool update_num_ops_stats,
|
||||
std::string* result_value, PinnableWideColumns* result_entity,
|
||||
MergeOperator::OpFailureScope* op_failure_scope) {
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue existing_value;
|
||||
|
||||
Slice entity_copy(entity);
|
||||
WideColumns existing_columns;
|
||||
|
||||
const Status s =
|
||||
WideColumnSerialization::Deserialize(entity_copy, existing_columns);
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
|
||||
std::string merge_result;
|
||||
existing_value = std::move(existing_columns);
|
||||
|
||||
{
|
||||
const Status s = TimedFullMerge(merge_operator, key, &value_of_default,
|
||||
operands, &merge_result, logger, statistics,
|
||||
clock, nullptr /* result_operand */,
|
||||
update_num_ops_stats, op_failure_scope);
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
if (has_default_column) {
|
||||
base_columns[0].value() = merge_result;
|
||||
|
||||
const Status s = WideColumnSerialization::Serialize(base_columns, *result);
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
} else {
|
||||
const Status s =
|
||||
WideColumnSerialization::Serialize(merge_result, base_columns, *result);
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
return Status::OK();
|
||||
return TimedFullMergeImpl(merge_operator, key, std::move(existing_value),
|
||||
operands, logger, statistics, clock,
|
||||
update_num_ops_stats, result_value, result_entity,
|
||||
op_failure_scope);
|
||||
}
|
||||
|
||||
// PRE: iter points to the first merge type entry
|
||||
@@ -287,7 +466,7 @@ Status MergeHelper::MergeUntil(InternalIterator* iter,
|
||||
// hit a put/delete/single delete
|
||||
// => merge the put value or a nullptr with operands_
|
||||
// => store result in operands_.back() (and update keys_.back())
|
||||
// => change the entry type to kTypeValue for keys_.back()
|
||||
// => change the entry type for keys_.back()
|
||||
// We are done! Success!
|
||||
|
||||
// If there are no operands, just return the Status::OK(). That will cause
|
||||
@@ -300,24 +479,23 @@ Status MergeHelper::MergeUntil(InternalIterator* iter,
|
||||
// TODO: if we're in compaction and it's a put, it would be nice to run
|
||||
// compaction filter on it.
|
||||
std::string merge_result;
|
||||
ValueType merge_result_type;
|
||||
MergeOperator::OpFailureScope op_failure_scope;
|
||||
|
||||
if (range_del_agg &&
|
||||
range_del_agg->ShouldDelete(
|
||||
ikey, RangeDelPositioningMode::kForwardTraversal)) {
|
||||
s = TimedFullMerge(user_merge_operator_, ikey.user_key, nullptr,
|
||||
merge_context_.GetOperands(), &merge_result, logger_,
|
||||
stats_, clock_,
|
||||
/* result_operand */ nullptr,
|
||||
/* update_num_ops_stats */ false, &op_failure_scope);
|
||||
s = TimedFullMerge(user_merge_operator_, ikey.user_key, kNoBaseValue,
|
||||
merge_context_.GetOperands(), logger_, stats_,
|
||||
clock_, /* update_num_ops_stats */ false,
|
||||
&merge_result, /* result_operand */ nullptr,
|
||||
&merge_result_type, &op_failure_scope);
|
||||
} else if (ikey.type == kTypeValue) {
|
||||
const Slice val = iter->value();
|
||||
|
||||
s = TimedFullMerge(user_merge_operator_, ikey.user_key, &val,
|
||||
merge_context_.GetOperands(), &merge_result, logger_,
|
||||
stats_, clock_,
|
||||
/* result_operand */ nullptr,
|
||||
/* update_num_ops_stats */ false, &op_failure_scope);
|
||||
s = TimedFullMerge(user_merge_operator_, ikey.user_key, kPlainBaseValue,
|
||||
iter->value(), merge_context_.GetOperands(), logger_,
|
||||
stats_, clock_, /* update_num_ops_stats */ false,
|
||||
&merge_result, /* result_operand */ nullptr,
|
||||
&merge_result_type, &op_failure_scope);
|
||||
} else if (ikey.type == kTypeBlobIndex) {
|
||||
BlobIndex blob_index;
|
||||
|
||||
@@ -347,22 +525,23 @@ Status MergeHelper::MergeUntil(InternalIterator* iter,
|
||||
c_iter_stats->total_blob_bytes_read += bytes_read;
|
||||
}
|
||||
|
||||
s = TimedFullMerge(user_merge_operator_, ikey.user_key, &blob_value,
|
||||
merge_context_.GetOperands(), &merge_result, logger_,
|
||||
stats_, clock_,
|
||||
/* result_operand */ nullptr,
|
||||
/* update_num_ops_stats */ false, &op_failure_scope);
|
||||
s = TimedFullMerge(user_merge_operator_, ikey.user_key, kPlainBaseValue,
|
||||
blob_value, merge_context_.GetOperands(), logger_,
|
||||
stats_, clock_, /* update_num_ops_stats */ false,
|
||||
&merge_result, /* result_operand */ nullptr,
|
||||
&merge_result_type, &op_failure_scope);
|
||||
} else if (ikey.type == kTypeWideColumnEntity) {
|
||||
s = TimedFullMergeWithEntity(
|
||||
user_merge_operator_, ikey.user_key, iter->value(),
|
||||
merge_context_.GetOperands(), &merge_result, logger_, stats_,
|
||||
clock_, /* update_num_ops_stats */ false, &op_failure_scope);
|
||||
s = TimedFullMerge(user_merge_operator_, ikey.user_key, kWideBaseValue,
|
||||
iter->value(), merge_context_.GetOperands(), logger_,
|
||||
stats_, clock_, /* update_num_ops_stats */ false,
|
||||
&merge_result, /* result_operand */ nullptr,
|
||||
&merge_result_type, &op_failure_scope);
|
||||
} else {
|
||||
s = TimedFullMerge(user_merge_operator_, ikey.user_key, nullptr,
|
||||
merge_context_.GetOperands(), &merge_result, logger_,
|
||||
stats_, clock_,
|
||||
/* result_operand */ nullptr,
|
||||
/* update_num_ops_stats */ false, &op_failure_scope);
|
||||
s = TimedFullMerge(user_merge_operator_, ikey.user_key, kNoBaseValue,
|
||||
merge_context_.GetOperands(), logger_, stats_,
|
||||
clock_, /* update_num_ops_stats */ false,
|
||||
&merge_result, /* result_operand */ nullptr,
|
||||
&merge_result_type, &op_failure_scope);
|
||||
}
|
||||
|
||||
// We store the result in keys_.back() and operands_.back()
|
||||
@@ -370,10 +549,12 @@ Status MergeHelper::MergeUntil(InternalIterator* iter,
|
||||
if (s.ok()) {
|
||||
// The original key encountered
|
||||
original_key = std::move(keys_.back());
|
||||
orig_ikey.type = ikey.type == kTypeWideColumnEntity
|
||||
? kTypeWideColumnEntity
|
||||
: kTypeValue;
|
||||
|
||||
assert(merge_result_type == kTypeValue ||
|
||||
merge_result_type == kTypeWideColumnEntity);
|
||||
orig_ikey.type = merge_result_type;
|
||||
UpdateInternalKey(&original_key, orig_ikey.sequence, orig_ikey.type);
|
||||
|
||||
keys_.clear();
|
||||
merge_context_.Clear();
|
||||
keys_.emplace_front(std::move(original_key));
|
||||
@@ -498,19 +679,24 @@ Status MergeHelper::MergeUntil(InternalIterator* iter,
|
||||
assert(merge_context_.GetNumOperands() >= 1);
|
||||
assert(merge_context_.GetNumOperands() == keys_.size());
|
||||
std::string merge_result;
|
||||
ValueType merge_result_type;
|
||||
MergeOperator::OpFailureScope op_failure_scope;
|
||||
s = TimedFullMerge(user_merge_operator_, orig_ikey.user_key, nullptr,
|
||||
merge_context_.GetOperands(), &merge_result, logger_,
|
||||
stats_, clock_,
|
||||
/* result_operand */ nullptr,
|
||||
/* update_num_ops_stats */ false, &op_failure_scope);
|
||||
s = TimedFullMerge(user_merge_operator_, orig_ikey.user_key, kNoBaseValue,
|
||||
merge_context_.GetOperands(), logger_, stats_, clock_,
|
||||
/* update_num_ops_stats */ false, &merge_result,
|
||||
/* result_operand */ nullptr, &merge_result_type,
|
||||
&op_failure_scope);
|
||||
if (s.ok()) {
|
||||
// The original key encountered
|
||||
// We are certain that keys_ is not empty here (see assertions couple of
|
||||
// lines before).
|
||||
original_key = std::move(keys_.back());
|
||||
orig_ikey.type = kTypeValue;
|
||||
|
||||
assert(merge_result_type == kTypeValue ||
|
||||
merge_result_type == kTypeWideColumnEntity);
|
||||
orig_ikey.type = merge_result_type;
|
||||
UpdateInternalKey(&original_key, orig_ikey.sequence, orig_ikey.type);
|
||||
|
||||
keys_.clear();
|
||||
merge_context_.Clear();
|
||||
keys_.emplace_front(std::move(original_key));
|
||||
|
||||
+83
-12
@@ -41,28 +41,75 @@ class MergeHelper {
|
||||
Statistics* stats = nullptr,
|
||||
const std::atomic<bool>* shutting_down = nullptr);
|
||||
|
||||
// Wrapper around MergeOperator::FullMergeV2() that records perf statistics.
|
||||
// Result of merge will be written to result if status returned is OK.
|
||||
// If operands is empty, the value will simply be copied to result.
|
||||
// Set `update_num_ops_stats` to true if it is from a user read, so that
|
||||
// the latency is sensitive.
|
||||
// Wrappers around MergeOperator::FullMergeV3() that record perf statistics.
|
||||
// Set `update_num_ops_stats` to true if it is from a user read so that
|
||||
// the corresponding statistics are updated.
|
||||
// Returns one of the following statuses:
|
||||
// - OK: Entries were successfully merged.
|
||||
// - Corruption: Merge operator reported unsuccessful merge. The scope of the
|
||||
// damage will be stored in `*op_failure_scope` when `op_failure_scope` is
|
||||
// not nullptr
|
||||
|
||||
// Empty tag types to disambiguate overloads
|
||||
struct NoBaseValueTag {};
|
||||
static constexpr NoBaseValueTag kNoBaseValue{};
|
||||
|
||||
struct PlainBaseValueTag {};
|
||||
static constexpr PlainBaseValueTag kPlainBaseValue{};
|
||||
|
||||
struct WideBaseValueTag {};
|
||||
static constexpr WideBaseValueTag kWideBaseValue{};
|
||||
|
||||
// Variants that expose the merge result directly (in serialized form for wide
|
||||
// columns) as well as its value type. Used by iterator and compaction.
|
||||
static Status TimedFullMerge(const MergeOperator* merge_operator,
|
||||
const Slice& key, const Slice* value,
|
||||
const Slice& key, NoBaseValueTag,
|
||||
const std::vector<Slice>& operands,
|
||||
std::string* result, Logger* logger,
|
||||
Statistics* statistics, SystemClock* clock,
|
||||
Slice* result_operand, bool update_num_ops_stats,
|
||||
Logger* logger, Statistics* statistics,
|
||||
SystemClock* clock, bool update_num_ops_stats,
|
||||
std::string* result, Slice* result_operand,
|
||||
ValueType* result_type,
|
||||
MergeOperator::OpFailureScope* op_failure_scope);
|
||||
|
||||
static Status TimedFullMergeWithEntity(
|
||||
const MergeOperator* merge_operator, const Slice& key, Slice base_entity,
|
||||
const std::vector<Slice>& operands, std::string* result, Logger* logger,
|
||||
static Status TimedFullMerge(
|
||||
const MergeOperator* merge_operator, const Slice& key, PlainBaseValueTag,
|
||||
const Slice& value, const std::vector<Slice>& operands, Logger* logger,
|
||||
Statistics* statistics, SystemClock* clock, bool update_num_ops_stats,
|
||||
std::string* result, Slice* result_operand, ValueType* result_type,
|
||||
MergeOperator::OpFailureScope* op_failure_scope);
|
||||
|
||||
static Status TimedFullMerge(
|
||||
const MergeOperator* merge_operator, const Slice& key, WideBaseValueTag,
|
||||
const Slice& entity, const std::vector<Slice>& operands, Logger* logger,
|
||||
Statistics* statistics, SystemClock* clock, bool update_num_ops_stats,
|
||||
std::string* result, Slice* result_operand, ValueType* result_type,
|
||||
MergeOperator::OpFailureScope* op_failure_scope);
|
||||
|
||||
// Variants that expose the merge result translated to the form requested by
|
||||
// the client. (For example, if the result is a wide-column structure but the
|
||||
// client requested the results in plain-value form, the value of the default
|
||||
// column is returned.) Used by point lookups.
|
||||
static Status TimedFullMerge(const MergeOperator* merge_operator,
|
||||
const Slice& key, NoBaseValueTag,
|
||||
const std::vector<Slice>& operands,
|
||||
Logger* logger, Statistics* statistics,
|
||||
SystemClock* clock, bool update_num_ops_stats,
|
||||
std::string* result_value,
|
||||
PinnableWideColumns* result_entity,
|
||||
MergeOperator::OpFailureScope* op_failure_scope);
|
||||
|
||||
static Status TimedFullMerge(
|
||||
const MergeOperator* merge_operator, const Slice& key, PlainBaseValueTag,
|
||||
const Slice& value, const std::vector<Slice>& operands, Logger* logger,
|
||||
Statistics* statistics, SystemClock* clock, bool update_num_ops_stats,
|
||||
std::string* result_value, PinnableWideColumns* result_entity,
|
||||
MergeOperator::OpFailureScope* op_failure_scope);
|
||||
|
||||
static Status TimedFullMerge(
|
||||
const MergeOperator* merge_operator, const Slice& key, WideBaseValueTag,
|
||||
const Slice& entity, const std::vector<Slice>& operands, Logger* logger,
|
||||
Statistics* statistics, SystemClock* clock, bool update_num_ops_stats,
|
||||
std::string* result_value, PinnableWideColumns* result_entity,
|
||||
MergeOperator::OpFailureScope* op_failure_scope);
|
||||
|
||||
// During compaction, merge entries until we hit
|
||||
@@ -198,6 +245,30 @@ class MergeHelper {
|
||||
// This is a best-effort facility, so memory_order_relaxed is sufficient.
|
||||
return shutting_down_ && shutting_down_->load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
template <typename Visitor>
|
||||
static Status TimedFullMergeCommonImpl(
|
||||
const MergeOperator* merge_operator, const Slice& key,
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue&& existing_value,
|
||||
const std::vector<Slice>& operands, Logger* logger,
|
||||
Statistics* statistics, SystemClock* clock, bool update_num_ops_stats,
|
||||
MergeOperator::OpFailureScope* op_failure_scope, Visitor&& visitor);
|
||||
|
||||
static Status TimedFullMergeImpl(
|
||||
const MergeOperator* merge_operator, const Slice& key,
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue&& existing_value,
|
||||
const std::vector<Slice>& operands, Logger* logger,
|
||||
Statistics* statistics, SystemClock* clock, bool update_num_ops_stats,
|
||||
std::string* result, Slice* result_operand, ValueType* result_type,
|
||||
MergeOperator::OpFailureScope* op_failure_scope);
|
||||
|
||||
static Status TimedFullMergeImpl(
|
||||
const MergeOperator* merge_operator, const Slice& key,
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue&& existing_value,
|
||||
const std::vector<Slice>& operands, Logger* logger,
|
||||
Statistics* statistics, SystemClock* clock, bool update_num_ops_stats,
|
||||
std::string* result_value, PinnableWideColumns* result_entity,
|
||||
MergeOperator::OpFailureScope* op_failure_scope);
|
||||
};
|
||||
|
||||
// MergeOutputIterator can be used to iterate over the result of a merge.
|
||||
|
||||
@@ -9,6 +9,11 @@
|
||||
|
||||
#include "rocksdb/merge_operator.h"
|
||||
|
||||
#include <type_traits>
|
||||
|
||||
#include "db/wide/wide_columns_helper.h"
|
||||
#include "util/overload.h"
|
||||
|
||||
namespace ROCKSDB_NAMESPACE {
|
||||
|
||||
bool MergeOperator::FullMergeV2(const MergeOperationInput& merge_in,
|
||||
@@ -23,6 +28,83 @@ bool MergeOperator::FullMergeV2(const MergeOperationInput& merge_in,
|
||||
&merge_out->new_value, merge_in.logger);
|
||||
}
|
||||
|
||||
bool MergeOperator::FullMergeV3(const MergeOperationInputV3& merge_in,
|
||||
MergeOperationOutputV3* merge_out) const {
|
||||
assert(merge_out);
|
||||
|
||||
MergeOperationInput in_v2(merge_in.key, nullptr, merge_in.operand_list,
|
||||
merge_in.logger);
|
||||
|
||||
std::string new_value;
|
||||
Slice existing_operand(nullptr, 0);
|
||||
MergeOperationOutput out_v2(new_value, existing_operand);
|
||||
|
||||
return std::visit(
|
||||
overload{
|
||||
[&](const auto& existing) -> bool {
|
||||
using T = std::decay_t<decltype(existing)>;
|
||||
|
||||
if constexpr (std::is_same_v<T, Slice>) {
|
||||
in_v2.existing_value = &existing;
|
||||
}
|
||||
|
||||
const bool result = FullMergeV2(in_v2, &out_v2);
|
||||
if (!result) {
|
||||
merge_out->op_failure_scope = out_v2.op_failure_scope;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (existing_operand.data()) {
|
||||
merge_out->new_value = existing_operand;
|
||||
} else {
|
||||
merge_out->new_value = std::move(new_value);
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
[&](const WideColumns& existing_columns) -> bool {
|
||||
const bool has_default_column =
|
||||
WideColumnsHelper::HasDefaultColumn(existing_columns);
|
||||
|
||||
Slice value_of_default;
|
||||
if (has_default_column) {
|
||||
value_of_default = existing_columns.front().value();
|
||||
}
|
||||
|
||||
in_v2.existing_value = &value_of_default;
|
||||
|
||||
const bool result = FullMergeV2(in_v2, &out_v2);
|
||||
if (!result) {
|
||||
merge_out->op_failure_scope = out_v2.op_failure_scope;
|
||||
return false;
|
||||
}
|
||||
|
||||
merge_out->new_value = MergeOperationOutputV3::NewColumns();
|
||||
auto& new_columns = std::get<MergeOperationOutputV3::NewColumns>(
|
||||
merge_out->new_value);
|
||||
new_columns.reserve(has_default_column
|
||||
? existing_columns.size()
|
||||
: (existing_columns.size() + 1));
|
||||
|
||||
if (existing_operand.data()) {
|
||||
new_columns.emplace_back(kDefaultWideColumnName.ToString(),
|
||||
existing_operand.ToString());
|
||||
} else {
|
||||
new_columns.emplace_back(kDefaultWideColumnName.ToString(),
|
||||
std::move(new_value));
|
||||
}
|
||||
|
||||
for (size_t i = has_default_column ? 1 : 0;
|
||||
i < existing_columns.size(); ++i) {
|
||||
new_columns.emplace_back(existing_columns[i].name().ToString(),
|
||||
existing_columns[i].value().ToString());
|
||||
}
|
||||
|
||||
return true;
|
||||
}},
|
||||
merge_in.existing_value);
|
||||
}
|
||||
|
||||
// The default implementation of PartialMergeMulti, which invokes
|
||||
// PartialMerge multiple times internally and merges two operands at
|
||||
// a time.
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
#include "rocksdb/env.h"
|
||||
#include "rocksdb/merge_operator.h"
|
||||
#include "rocksdb/utilities/db_ttl.h"
|
||||
#include "rocksdb/wide_columns.h"
|
||||
#include "test_util/testharness.h"
|
||||
#include "util/coding.h"
|
||||
#include "utilities/merge_operators.h"
|
||||
@@ -607,6 +608,272 @@ TEST_F(MergeTest, MergeWithCompactionAndFlush) {
|
||||
ASSERT_OK(DestroyDB(dbname, Options()));
|
||||
}
|
||||
|
||||
TEST_F(MergeTest, FullMergeV3FallbackNewValue) {
|
||||
// Test that the default FullMergeV3 implementation correctly handles the case
|
||||
// when FullMergeV2 results in a new value.
|
||||
|
||||
const Slice key("foo");
|
||||
const MergeOperator::MergeOperationInputV3::OperandList operands{
|
||||
"first", "second", "third"};
|
||||
constexpr Logger* logger = nullptr;
|
||||
|
||||
auto append_operator =
|
||||
MergeOperators::CreateStringAppendOperator(std::string());
|
||||
|
||||
// No existing value
|
||||
{
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue existing_value;
|
||||
const MergeOperator::MergeOperationInputV3 merge_in(
|
||||
key, std::move(existing_value), operands, logger);
|
||||
|
||||
MergeOperator::MergeOperationOutputV3 merge_out;
|
||||
|
||||
ASSERT_TRUE(append_operator->FullMergeV3(merge_in, &merge_out));
|
||||
|
||||
const auto& result = std::get<std::string>(merge_out.new_value);
|
||||
ASSERT_EQ(result, operands[0].ToString() + operands[1].ToString() +
|
||||
operands[2].ToString());
|
||||
}
|
||||
|
||||
// Plain existing value
|
||||
{
|
||||
const Slice plain("plain");
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue existing_value(plain);
|
||||
const MergeOperator::MergeOperationInputV3 merge_in(
|
||||
key, std::move(existing_value), operands, logger);
|
||||
|
||||
MergeOperator::MergeOperationOutputV3 merge_out;
|
||||
|
||||
ASSERT_TRUE(append_operator->FullMergeV3(merge_in, &merge_out));
|
||||
|
||||
const auto& result = std::get<std::string>(merge_out.new_value);
|
||||
ASSERT_EQ(result, plain.ToString() + operands[0].ToString() +
|
||||
operands[1].ToString() + operands[2].ToString());
|
||||
}
|
||||
|
||||
// Wide-column existing value with default column
|
||||
{
|
||||
const WideColumns entity{
|
||||
{kDefaultWideColumnName, "default"}, {"one", "1"}, {"two", "2"}};
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue existing_value(entity);
|
||||
const MergeOperator::MergeOperationInputV3 merge_in(
|
||||
key, std::move(existing_value), operands, logger);
|
||||
|
||||
MergeOperator::MergeOperationOutputV3 merge_out;
|
||||
|
||||
ASSERT_TRUE(append_operator->FullMergeV3(merge_in, &merge_out));
|
||||
|
||||
const auto& result =
|
||||
std::get<MergeOperator::MergeOperationOutputV3::NewColumns>(
|
||||
merge_out.new_value);
|
||||
ASSERT_EQ(result.size(), entity.size());
|
||||
ASSERT_EQ(result[0].first, entity[0].name());
|
||||
ASSERT_EQ(result[0].second,
|
||||
entity[0].value().ToString() + operands[0].ToString() +
|
||||
operands[1].ToString() + operands[2].ToString());
|
||||
ASSERT_EQ(result[1].first, entity[1].name());
|
||||
ASSERT_EQ(result[1].second, entity[1].value());
|
||||
ASSERT_EQ(result[2].first, entity[2].name());
|
||||
ASSERT_EQ(result[2].second, entity[2].value());
|
||||
}
|
||||
|
||||
// Wide-column existing value without default column
|
||||
{
|
||||
const WideColumns entity{{"one", "1"}, {"two", "2"}};
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue existing_value(entity);
|
||||
const MergeOperator::MergeOperationInputV3 merge_in(
|
||||
key, std::move(existing_value), operands, logger);
|
||||
|
||||
MergeOperator::MergeOperationOutputV3 merge_out;
|
||||
|
||||
ASSERT_TRUE(append_operator->FullMergeV3(merge_in, &merge_out));
|
||||
|
||||
const auto& result =
|
||||
std::get<MergeOperator::MergeOperationOutputV3::NewColumns>(
|
||||
merge_out.new_value);
|
||||
ASSERT_EQ(result.size(), entity.size() + 1);
|
||||
ASSERT_EQ(result[0].first, kDefaultWideColumnName);
|
||||
ASSERT_EQ(result[0].second, operands[0].ToString() +
|
||||
operands[1].ToString() +
|
||||
operands[2].ToString());
|
||||
ASSERT_EQ(result[1].first, entity[0].name());
|
||||
ASSERT_EQ(result[1].second, entity[0].value());
|
||||
ASSERT_EQ(result[2].first, entity[1].name());
|
||||
ASSERT_EQ(result[2].second, entity[1].value());
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(MergeTest, FullMergeV3FallbackExistingOperand) {
|
||||
// Test that the default FullMergeV3 implementation correctly handles the case
|
||||
// when FullMergeV2 results in an existing operand.
|
||||
|
||||
const Slice key("foo");
|
||||
const MergeOperator::MergeOperationInputV3::OperandList operands{
|
||||
"first", "second", "third"};
|
||||
constexpr Logger* logger = nullptr;
|
||||
|
||||
auto put_operator = MergeOperators::CreatePutOperator();
|
||||
|
||||
// No existing value
|
||||
{
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue existing_value;
|
||||
const MergeOperator::MergeOperationInputV3 merge_in(
|
||||
key, std::move(existing_value), operands, logger);
|
||||
|
||||
MergeOperator::MergeOperationOutputV3 merge_out;
|
||||
|
||||
ASSERT_TRUE(put_operator->FullMergeV3(merge_in, &merge_out));
|
||||
|
||||
const auto& result = std::get<Slice>(merge_out.new_value);
|
||||
ASSERT_EQ(result.data(), operands.back().data());
|
||||
ASSERT_EQ(result.size(), operands.back().size());
|
||||
}
|
||||
|
||||
// Plain existing value
|
||||
{
|
||||
const Slice plain("plain");
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue existing_value(plain);
|
||||
const MergeOperator::MergeOperationInputV3 merge_in(
|
||||
key, std::move(existing_value), operands, logger);
|
||||
|
||||
MergeOperator::MergeOperationOutputV3 merge_out;
|
||||
|
||||
ASSERT_TRUE(put_operator->FullMergeV3(merge_in, &merge_out));
|
||||
|
||||
const auto& result = std::get<Slice>(merge_out.new_value);
|
||||
ASSERT_EQ(result.data(), operands.back().data());
|
||||
ASSERT_EQ(result.size(), operands.back().size());
|
||||
}
|
||||
|
||||
// Wide-column existing value with default column
|
||||
{
|
||||
const WideColumns entity{
|
||||
{kDefaultWideColumnName, "default"}, {"one", "1"}, {"two", "2"}};
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue existing_value(entity);
|
||||
const MergeOperator::MergeOperationInputV3 merge_in(
|
||||
key, std::move(existing_value), operands, logger);
|
||||
|
||||
MergeOperator::MergeOperationOutputV3 merge_out;
|
||||
|
||||
ASSERT_TRUE(put_operator->FullMergeV3(merge_in, &merge_out));
|
||||
|
||||
const auto& result =
|
||||
std::get<MergeOperator::MergeOperationOutputV3::NewColumns>(
|
||||
merge_out.new_value);
|
||||
ASSERT_EQ(result.size(), entity.size());
|
||||
ASSERT_EQ(result[0].first, entity[0].name());
|
||||
ASSERT_EQ(result[0].second, operands.back());
|
||||
ASSERT_EQ(result[1].first, entity[1].name());
|
||||
ASSERT_EQ(result[1].second, entity[1].value());
|
||||
ASSERT_EQ(result[2].first, entity[2].name());
|
||||
ASSERT_EQ(result[2].second, entity[2].value());
|
||||
}
|
||||
|
||||
// Wide-column existing value without default column
|
||||
{
|
||||
const WideColumns entity{{"one", "1"}, {"two", "2"}};
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue existing_value(entity);
|
||||
const MergeOperator::MergeOperationInputV3 merge_in(
|
||||
key, std::move(existing_value), operands, logger);
|
||||
|
||||
MergeOperator::MergeOperationOutputV3 merge_out;
|
||||
|
||||
ASSERT_TRUE(put_operator->FullMergeV3(merge_in, &merge_out));
|
||||
|
||||
const auto& result =
|
||||
std::get<MergeOperator::MergeOperationOutputV3::NewColumns>(
|
||||
merge_out.new_value);
|
||||
ASSERT_EQ(result.size(), entity.size() + 1);
|
||||
ASSERT_EQ(result[0].first, kDefaultWideColumnName);
|
||||
ASSERT_EQ(result[0].second, operands.back());
|
||||
ASSERT_EQ(result[1].first, entity[0].name());
|
||||
ASSERT_EQ(result[1].second, entity[0].value());
|
||||
ASSERT_EQ(result[2].first, entity[1].name());
|
||||
ASSERT_EQ(result[2].second, entity[1].value());
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(MergeTest, FullMergeV3FallbackFailure) {
|
||||
// Test that the default FullMergeV3 implementation correctly handles the case
|
||||
// when FullMergeV2 fails.
|
||||
|
||||
const Slice key("foo");
|
||||
const MergeOperator::MergeOperationInputV3::OperandList operands{
|
||||
"first", "second", "third"};
|
||||
constexpr Logger* logger = nullptr;
|
||||
|
||||
class FailMergeOperator : public MergeOperator {
|
||||
public:
|
||||
bool FullMergeV2(const MergeOperationInput& /* merge_in */,
|
||||
MergeOperationOutput* merge_out) const override {
|
||||
assert(merge_out);
|
||||
merge_out->op_failure_scope = OpFailureScope::kMustMerge;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
const char* Name() const override { return "FailMergeOperator"; }
|
||||
};
|
||||
|
||||
FailMergeOperator fail_operator;
|
||||
|
||||
// No existing value
|
||||
{
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue existing_value;
|
||||
const MergeOperator::MergeOperationInputV3 merge_in(
|
||||
key, std::move(existing_value), operands, logger);
|
||||
|
||||
MergeOperator::MergeOperationOutputV3 merge_out;
|
||||
|
||||
ASSERT_FALSE(fail_operator.FullMergeV3(merge_in, &merge_out));
|
||||
ASSERT_EQ(merge_out.op_failure_scope,
|
||||
MergeOperator::OpFailureScope::kMustMerge);
|
||||
}
|
||||
|
||||
// Plain existing value
|
||||
{
|
||||
const Slice plain("plain");
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue existing_value(plain);
|
||||
const MergeOperator::MergeOperationInputV3 merge_in(
|
||||
key, std::move(existing_value), operands, logger);
|
||||
|
||||
MergeOperator::MergeOperationOutputV3 merge_out;
|
||||
|
||||
ASSERT_FALSE(fail_operator.FullMergeV3(merge_in, &merge_out));
|
||||
ASSERT_EQ(merge_out.op_failure_scope,
|
||||
MergeOperator::OpFailureScope::kMustMerge);
|
||||
}
|
||||
|
||||
// Wide-column existing value with default column
|
||||
{
|
||||
const WideColumns entity{
|
||||
{kDefaultWideColumnName, "default"}, {"one", "1"}, {"two", "2"}};
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue existing_value(entity);
|
||||
const MergeOperator::MergeOperationInputV3 merge_in(
|
||||
key, std::move(existing_value), operands, logger);
|
||||
|
||||
MergeOperator::MergeOperationOutputV3 merge_out;
|
||||
|
||||
ASSERT_FALSE(fail_operator.FullMergeV3(merge_in, &merge_out));
|
||||
ASSERT_EQ(merge_out.op_failure_scope,
|
||||
MergeOperator::OpFailureScope::kMustMerge);
|
||||
}
|
||||
|
||||
// Wide-column existing value without default column
|
||||
{
|
||||
const WideColumns entity{{"one", "1"}, {"two", "2"}};
|
||||
MergeOperator::MergeOperationInputV3::ExistingValue existing_value(entity);
|
||||
const MergeOperator::MergeOperationInputV3 merge_in(
|
||||
key, std::move(existing_value), operands, logger);
|
||||
|
||||
MergeOperator::MergeOperationOutputV3 merge_out;
|
||||
|
||||
ASSERT_FALSE(fail_operator.FullMergeV3(merge_in, &merge_out));
|
||||
ASSERT_EQ(merge_out.op_failure_scope,
|
||||
MergeOperator::OpFailureScope::kMustMerge);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace ROCKSDB_NAMESPACE
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
|
||||
@@ -36,6 +36,10 @@ class TruncatedRangeDelIterator {
|
||||
const InternalKeyComparator* icmp, const InternalKey* smallest,
|
||||
const InternalKey* largest);
|
||||
|
||||
void SetRangeDelReadSeqno(SequenceNumber read_seqno) {
|
||||
iter_->SetRangeDelReadSeqno(read_seqno);
|
||||
}
|
||||
|
||||
bool Valid() const;
|
||||
|
||||
void Next() { iter_->TopNext(); }
|
||||
|
||||
Loaded 100 of 262 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user