2019-12-09 07:49:32 +00:00
|
|
|
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
|
|
|
|
// 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).
|
|
|
|
//
|
|
|
|
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
|
|
// found in the LICENSE file. See the AUTHORS file for names of contributors.
|
|
|
|
//
|
|
|
|
// The test uses an array to compare against values written to the database.
|
|
|
|
// Keys written to the array are in 1:1 correspondence to the actual values in
|
|
|
|
// the database according to the formula in the function GenerateValue.
|
|
|
|
|
|
|
|
// Space is reserved in the array from 0 to FLAGS_max_key and values are
|
|
|
|
// randomly written/deleted/read from those positions. During verification we
|
|
|
|
// compare all the positions in the array. To shorten/elongate the running
|
|
|
|
// time, you could change the settings: FLAGS_max_key, FLAGS_ops_per_thread,
|
|
|
|
// (sometimes also FLAGS_threads).
|
|
|
|
//
|
|
|
|
// NOTE that if FLAGS_test_batches_snapshots is set, the test will have
|
|
|
|
// different behavior. See comment of the flag for details.
|
|
|
|
|
|
|
|
#ifdef GFLAGS
|
|
|
|
#pragma once
|
|
|
|
#include <fcntl.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <sys/types.h>
|
2020-07-09 21:33:42 +00:00
|
|
|
|
2019-12-09 07:49:32 +00:00
|
|
|
#include <algorithm>
|
|
|
|
#include <array>
|
|
|
|
#include <chrono>
|
|
|
|
#include <cinttypes>
|
|
|
|
#include <exception>
|
|
|
|
#include <queue>
|
|
|
|
#include <thread>
|
|
|
|
|
|
|
|
#include "db/db_impl/db_impl.h"
|
|
|
|
#include "db/version_set.h"
|
2019-12-16 22:28:06 +00:00
|
|
|
#include "db_stress_tool/db_stress_env_wrapper.h"
|
2019-12-09 07:49:32 +00:00
|
|
|
#include "db_stress_tool/db_stress_listener.h"
|
|
|
|
#include "db_stress_tool/db_stress_shared_state.h"
|
|
|
|
#include "db_stress_tool/db_stress_test_base.h"
|
|
|
|
#include "logging/logging.h"
|
|
|
|
#include "monitoring/histogram.h"
|
|
|
|
#include "options/options_helper.h"
|
|
|
|
#include "port/port.h"
|
|
|
|
#include "rocksdb/cache.h"
|
|
|
|
#include "rocksdb/env.h"
|
|
|
|
#include "rocksdb/slice.h"
|
|
|
|
#include "rocksdb/slice_transform.h"
|
|
|
|
#include "rocksdb/statistics.h"
|
2022-01-27 23:44:23 +00:00
|
|
|
#include "rocksdb/utilities/backup_engine.h"
|
2019-12-09 07:49:32 +00:00
|
|
|
#include "rocksdb/utilities/checkpoint.h"
|
|
|
|
#include "rocksdb/utilities/db_ttl.h"
|
|
|
|
#include "rocksdb/utilities/debug.h"
|
2023-06-17 23:27:37 +00:00
|
|
|
#include "rocksdb/utilities/optimistic_transaction_db.h"
|
2019-12-09 07:49:32 +00:00
|
|
|
#include "rocksdb/utilities/options_util.h"
|
|
|
|
#include "rocksdb/utilities/transaction.h"
|
|
|
|
#include "rocksdb/utilities/transaction_db.h"
|
|
|
|
#include "rocksdb/write_batch.h"
|
2020-07-09 21:33:42 +00:00
|
|
|
#include "test_util/testutil.h"
|
2019-12-09 07:49:32 +00:00
|
|
|
#include "util/coding.h"
|
|
|
|
#include "util/compression.h"
|
|
|
|
#include "util/crc32c.h"
|
|
|
|
#include "util/gflags_compat.h"
|
|
|
|
#include "util/mutexlock.h"
|
|
|
|
#include "util/random.h"
|
|
|
|
#include "util/string_util.h"
|
2019-12-20 18:25:48 +00:00
|
|
|
#include "utilities/blob_db/blob_db.h"
|
2022-05-06 18:17:08 +00:00
|
|
|
#include "utilities/fault_injection_fs.h"
|
2019-12-09 07:49:32 +00:00
|
|
|
#include "utilities/merge_operators.h"
|
|
|
|
|
|
|
|
using GFLAGS_NAMESPACE::ParseCommandLineFlags;
|
|
|
|
using GFLAGS_NAMESPACE::RegisterFlagValidator;
|
|
|
|
using GFLAGS_NAMESPACE::SetUsageMessage;
|
|
|
|
|
|
|
|
DECLARE_uint64(seed);
|
|
|
|
DECLARE_bool(read_only);
|
|
|
|
DECLARE_int64(max_key);
|
2019-12-16 21:59:21 +00:00
|
|
|
DECLARE_double(hot_key_alpha);
|
2020-01-10 05:25:40 +00:00
|
|
|
DECLARE_int32(max_key_len);
|
|
|
|
DECLARE_string(key_len_percent_dist);
|
|
|
|
DECLARE_int32(key_window_scale_factor);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_int32(column_families);
|
|
|
|
DECLARE_string(options_file);
|
|
|
|
DECLARE_int64(active_width);
|
|
|
|
DECLARE_bool(test_batches_snapshots);
|
|
|
|
DECLARE_bool(atomic_flush);
|
Add manual_wal_flush, FlushWAL() to stress/crash test (#10698)
Summary:
**Context/Summary:**
Introduce `manual_wal_flush_one_in` as titled.
- When `manual_wal_flush_one_in > 0`, we also need tracing to correctly verify recovery because WAL data can be lost in this case when `FlushWAL()` is not explicitly called by users of RocksDB (in our case, db stress) and the recovery from such potential WAL data loss is a prefix recovery that requires tracing to verify. As another consequence, we need to disable features can't run under unsync data loss with `manual_wal_flush_one_in`
Incompatibilities fixed along the way:
```
db_stress: db/db_impl/db_impl_open.cc:2063: static rocksdb::Status rocksdb::DBImpl::Open(const rocksdb::DBOptions&, const string&, const std::vector<rocksdb::ColumnFamilyDescriptor>&, std::vector<rocksdb::ColumnFamilyHandle*>*, rocksdb::DB**, bool, bool): Assertion `impl->TEST_WALBufferIsEmpty()' failed.
```
- It turns out that `Writer::AddCompressionTypeRecord` before this assertion `EmitPhysicalRecord(kSetCompressionType, encode.data(), encode.size());` but do not trigger flush if `manual_wal_flush` is set . This leads to `impl->TEST_WALBufferIsEmpty()' is false.
- As suggested, assertion is removed and violation case is handled by `FlushWAL(sync=true)` along with refactoring `TEST_WALBufferIsEmpty()` to be `WALBufferIsEmpty()` since it is used in prod code now.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/10698
Test Plan:
- Locally running `python3 tools/db_crashtest.py blackbox --manual_wal_flush_one_in=1 --manual_wal_flush=1 --sync_wal_one_in=100 --atomic_flush=1 --flush_one_in=100 --column_families=3`
- Joined https://github.com/facebook/rocksdb/pull/10624 in auto CI testings with all RocksDB stress/crash test jobs
Reviewed By: ajkr
Differential Revision: D39593752
Pulled By: ajkr
fbshipit-source-id: 3a2135bb792c52d2ffa60257d4fbc557fb04d2ce
2022-09-30 22:48:33 +00:00
|
|
|
DECLARE_int32(manual_wal_flush_one_in);
|
Cleanup, improve, stress test LockWAL() (#11143)
Summary:
The previous API comments for LockWAL didn't provide much about why you might want to use it, and didn't really meet what one would infer its contract was. Also, LockWAL was not in db_stress / crash test. In this change:
* Implement a counting semantics for LockWAL()+UnlockWAL(), so that they can safely be used concurrently across threads or recursively within a thread. This should make the API much less bug-prone and easier to use.
* Make sure no UnlockWAL() is needed after non-OK LockWAL() (to match RocksDB conventions)
* Make UnlockWAL() reliably return non-OK when there's no matching LockWAL() (for debug-ability)
* Clarify API comments on LockWAL(), UnlockWAL(), FlushWAL(), and SyncWAL(). Their exact meanings are not obvious, and I don't think it's appropriate to talk about implementation mutexes in the API comments, but about what operations might block each other.
* Add LockWAL()/UnlockWAL() to db_stress and crash test, mostly to check for assertion failures, but also checks that latest seqno doesn't change while WAL is locked. This is simpler to add when LockWAL() is allowed in multiple threads.
* Remove unnecessary use of sync points in test DBWALTest::LockWal. There was a bug during development of above changes that caused this test to fail sporadically, with and without this sync point change.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/11143
Test Plan: unit tests added / updated, added to stress/crash test
Reviewed By: ajkr
Differential Revision: D42848627
Pulled By: pdillinger
fbshipit-source-id: 6d976c51791941a31fd8fbf28b0f82e888d9f4b4
2023-01-31 06:52:30 +00:00
|
|
|
DECLARE_int32(lock_wal_one_in);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_bool(test_cf_consistency);
|
2021-12-14 21:33:16 +00:00
|
|
|
DECLARE_bool(test_multi_ops_txns);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_int32(threads);
|
|
|
|
DECLARE_int32(ttl);
|
|
|
|
DECLARE_int32(value_size_mult);
|
|
|
|
DECLARE_int32(compaction_readahead_size);
|
|
|
|
DECLARE_bool(enable_pipelined_write);
|
|
|
|
DECLARE_bool(verify_before_write);
|
|
|
|
DECLARE_bool(histogram);
|
|
|
|
DECLARE_bool(destroy_db_initially);
|
|
|
|
DECLARE_bool(verbose);
|
|
|
|
DECLARE_bool(progress_reports);
|
|
|
|
DECLARE_uint64(db_write_buffer_size);
|
|
|
|
DECLARE_int32(write_buffer_size);
|
|
|
|
DECLARE_int32(max_write_buffer_number);
|
|
|
|
DECLARE_int32(min_write_buffer_number_to_merge);
|
|
|
|
DECLARE_int32(max_write_buffer_number_to_maintain);
|
|
|
|
DECLARE_int64(max_write_buffer_size_to_maintain);
|
|
|
|
DECLARE_double(memtable_prefix_bloom_size_ratio);
|
|
|
|
DECLARE_bool(memtable_whole_key_filtering);
|
|
|
|
DECLARE_int32(open_files);
|
|
|
|
DECLARE_int64(compressed_cache_size);
|
Avoid overwriting options loaded from OPTIONS (#9943)
Summary:
This is similar to https://github.com/facebook/rocksdb/issues/9862, including the following fixes/refactoring:
1. If OPTIONS file is specified via `-options_file`, majority of options will be loaded from the file. We should not
overwrite options that have been loaded from the file. Instead, we configure only fields of options which are
shared objects and not set by the OPTIONS file. We also configure a few fields, e.g. `create_if_missing` necessary
for stress test to run.
2. Refactor options initialization into three functions, `InitializeOptionsFromFile()`, `InitializeOptionsFromFlags()`
and `InitializeOptionsGeneral()` similar to db_bench. I hope they can be shared in the future. The high-level logic is
as follows:
```cpp
if (!InitializeOptionsFromFile(...)) {
InitializeOptionsFromFlags(...);
}
InitializeOptionsGeneral(...);
```
3. Currently, the setting for `block_cache_compressed` does not seem correct because it by default specifies a
size of `numeric_limits<size_t>::max()` ((size_t)-1). According to code comments, `-1` indicates default value,
which should be referring to `num_shard_bits` argument.
4. Clarify `fail_if_options_file_error`.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/9943
Test Plan:
1. make check
2. Run stress tests, and manually check generated OPTIONS file and compare them with input OPTIONS files
Reviewed By: jay-zhuang
Differential Revision: D36133769
Pulled By: riversand963
fbshipit-source-id: 35dacdc090a0a72c922907170cd132b9ecaa073e
2022-05-18 19:43:50 +00:00
|
|
|
DECLARE_int32(compressed_cache_numshardbits);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_int32(compaction_style);
|
2022-07-01 05:56:58 +00:00
|
|
|
DECLARE_int32(compaction_pri);
|
2020-05-07 01:06:04 +00:00
|
|
|
DECLARE_int32(num_levels);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_int32(level0_file_num_compaction_trigger);
|
|
|
|
DECLARE_int32(level0_slowdown_writes_trigger);
|
|
|
|
DECLARE_int32(level0_stop_writes_trigger);
|
|
|
|
DECLARE_int32(block_size);
|
|
|
|
DECLARE_int32(format_version);
|
|
|
|
DECLARE_int32(index_block_restart_interval);
|
2022-03-17 02:00:04 +00:00
|
|
|
DECLARE_bool(disable_auto_compactions);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_int32(max_background_compactions);
|
|
|
|
DECLARE_int32(num_bottom_pri_threads);
|
|
|
|
DECLARE_int32(compaction_thread_pool_adjust_interval);
|
|
|
|
DECLARE_int32(compaction_thread_pool_variations);
|
|
|
|
DECLARE_int32(max_background_flushes);
|
|
|
|
DECLARE_int32(universal_size_ratio);
|
|
|
|
DECLARE_int32(universal_min_merge_width);
|
|
|
|
DECLARE_int32(universal_max_merge_width);
|
|
|
|
DECLARE_int32(universal_max_size_amplification_percent);
|
|
|
|
DECLARE_int32(clear_column_family_one_in);
|
2020-03-19 00:11:06 +00:00
|
|
|
DECLARE_int32(get_live_files_one_in);
|
|
|
|
DECLARE_int32(get_sorted_wal_files_one_in);
|
|
|
|
DECLARE_int32(get_current_wal_file_one_in);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_int32(set_options_one_in);
|
|
|
|
DECLARE_int32(set_in_place_one_in);
|
|
|
|
DECLARE_int64(cache_size);
|
2021-06-28 06:53:47 +00:00
|
|
|
DECLARE_int32(cache_numshardbits);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_bool(cache_index_and_filter_blocks);
|
2022-05-17 22:01:51 +00:00
|
|
|
DECLARE_bool(charge_compression_dictionary_building_buffer);
|
|
|
|
DECLARE_bool(charge_filter_construction);
|
|
|
|
DECLARE_bool(charge_table_reader);
|
Account memory of FileMetaData in global memory limit (#9924)
Summary:
**Context/Summary:**
As revealed by heap profiling, allocation of `FileMetaData` for [newly created file added to a Version](https://github.com/facebook/rocksdb/pull/9924/files#diff-a6aa385940793f95a2c5b39cc670bd440c4547fa54fd44622f756382d5e47e43R774) can consume significant heap memory. This PR is to account that toward our global memory limit based on block cache capacity.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/9924
Test Plan:
- Previous `make check` verified there are only 2 places where the memory of the allocated `FileMetaData` can be released
- New unit test `TEST_P(ChargeFileMetadataTestWithParam, Basic)`
- db bench (CPU cost of `charge_file_metadata` in write and compact)
- **write micros/op: -0.24%** : `TEST_TMPDIR=/dev/shm/testdb ./db_bench -benchmarks=fillseq -db=$TEST_TMPDIR -charge_file_metadata=1 (remove this option for pre-PR) -disable_auto_compactions=1 -write_buffer_size=100000 -num=4000000 | egrep 'fillseq'`
- **compact micros/op -0.87%** : `TEST_TMPDIR=/dev/shm/testdb ./db_bench -benchmarks=fillseq -db=$TEST_TMPDIR -charge_file_metadata=1 -disable_auto_compactions=1 -write_buffer_size=100000 -num=4000000 -numdistinct=1000 && ./db_bench -benchmarks=compact -db=$TEST_TMPDIR -use_existing_db=1 -charge_file_metadata=1 -disable_auto_compactions=1 | egrep 'compact'`
table 1 - write
#-run | (pre-PR) avg micros/op | std micros/op | (post-PR) micros/op | std micros/op | change (%)
-- | -- | -- | -- | -- | --
10 | 3.9711 | 0.264408 | 3.9914 | 0.254563 | 0.5111933721
20 | 3.83905 | 0.0664488 | 3.8251 | 0.0695456 | -0.3633711465
40 | 3.86625 | 0.136669 | 3.8867 | 0.143765 | 0.5289363078
80 | 3.87828 | 0.119007 | 3.86791 | 0.115674 | **-0.2673865734**
160 | 3.87677 | 0.162231 | 3.86739 | 0.16663 | **-0.2419539978**
table 2 - compact
#-run | (pre-PR) avg micros/op | std micros/op | (post-PR) micros/op | std micros/op | change (%)
-- | -- | -- | -- | -- | --
10 | 2,399,650.00 | 96,375.80 | 2,359,537.00 | 53,243.60 | -1.67
20 | 2,410,480.00 | 89,988.00 | 2,433,580.00 | 91,121.20 | 0.96
40 | 2.41E+06 | 121811 | 2.39E+06 | 131525 | **-0.96**
80 | 2.40E+06 | 134503 | 2.39E+06 | 108799 | **-0.78**
- stress test: `python3 tools/db_crashtest.py blackbox --charge_file_metadata=1 --cache_size=1` killed as normal
Reviewed By: ajkr
Differential Revision: D36055583
Pulled By: hx235
fbshipit-source-id: b60eab94707103cb1322cf815f05810ef0232625
2022-06-14 20:06:40 +00:00
|
|
|
DECLARE_bool(charge_file_metadata);
|
2022-07-19 06:26:57 +00:00
|
|
|
DECLARE_bool(charge_blob_cache);
|
2020-10-11 21:52:49 +00:00
|
|
|
DECLARE_int32(top_level_index_pinning);
|
|
|
|
DECLARE_int32(partition_pinning);
|
|
|
|
DECLARE_int32(unpartitioned_pinning);
|
2022-06-02 01:00:28 +00:00
|
|
|
DECLARE_string(cache_type);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_uint64(subcompactions);
|
|
|
|
DECLARE_uint64(periodic_compaction_seconds);
|
|
|
|
DECLARE_uint64(compaction_ttl);
|
2023-01-03 19:54:58 +00:00
|
|
|
DECLARE_bool(fifo_allow_compaction);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_bool(allow_concurrent_memtable_write);
|
2021-08-11 01:07:48 +00:00
|
|
|
DECLARE_double(experimental_mempurge_threshold);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_bool(enable_write_thread_adaptive_yield);
|
|
|
|
DECLARE_int32(reopen);
|
2019-12-10 16:38:23 +00:00
|
|
|
DECLARE_double(bloom_bits);
|
Add Bloom/Ribbon hybrid API support (#8679)
Summary:
This is essentially resurrection and fixing of the part of
https://github.com/facebook/rocksdb/issues/8198 that was reverted in https://github.com/facebook/rocksdb/issues/8212, using data added in https://github.com/facebook/rocksdb/issues/8246. Basically,
when configuring Ribbon filter, you can specify an LSM level before which
Bloom will be used instead of Ribbon. But Bloom is only considered for
Leveled and Universal compaction styles and file going into a known LSM
level. This way, SST file writer, FIFO compaction, etc. use Ribbon filter as
you would expect with NewRibbonFilterPolicy.
So that this can be controlled with a single int value and so that flushes
can be distinguished from intra-L0, we consider flush to go to level -1 for
the purposes of this option. (Explained in API comment.)
I also expect the most common and recommended Ribbon configuration to
use Bloom during flush, to minimize slowing down writes and because according
to my estimates, Ribbon only pays off if the structure lives in memory for
more than an hour. Thus, I have changed the default for NewRibbonFilterPolicy
to be this mild hybrid configuration. I don't really want to add something like
NewHybridFilterPolicy because at least the mild hybrid configuration (Bloom for
flush, Ribbon otherwise) should be considered a natural choice.
C APIs also updated, but because they don't support overloading,
rocksdb_filterpolicy_create_ribbon is kept pure ribbon for clarity and
rocksdb_filterpolicy_create_ribbon_hybrid must be called for a hybrid
configuration. While touching C API, I changed bits per key options from
int to double.
BuiltinFilterPolicy is needed so that LevelThresholdFilterPolicy doesn't inherit
unused fields from BloomFilterPolicy.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/8679
Test Plan: new + updated tests, including crash test
Reviewed By: jay-zhuang
Differential Revision: D30445797
Pulled By: pdillinger
fbshipit-source-id: 6f5aeddfd6d79f7e55493b563c2d1d2d568892e1
2021-08-21 00:59:24 +00:00
|
|
|
DECLARE_int32(ribbon_starting_level);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_bool(partition_filters);
|
Minimize memory internal fragmentation for Bloom filters (#6427)
Summary:
New experimental option BBTO::optimize_filters_for_memory builds
filters that maximize their use of "usable size" from malloc_usable_size,
which is also used to compute block cache charges.
Rather than always "rounding up," we track state in the
BloomFilterPolicy object to mix essentially "rounding down" and
"rounding up" so that the average FP rate of all generated filters is
the same as without the option. (YMMV as heavily accessed filters might
be unluckily lower accuracy.)
Thus, the option near-minimizes what the block cache considers as
"memory used" for a given target Bloom filter false positive rate and
Bloom filter implementation. There are no forward or backward
compatibility issues with this change, though it only works on the
format_version=5 Bloom filter.
With Jemalloc, we see about 10% reduction in memory footprint (and block
cache charge) for Bloom filters, but 1-2% increase in storage footprint,
due to encoding efficiency losses (FP rate is non-linear with bits/key).
Why not weighted random round up/down rather than state tracking? By
only requiring malloc_usable_size, we don't actually know what the next
larger and next smaller usable sizes for the allocator are. We pick a
requested size, accept and use whatever usable size it has, and use the
difference to inform our next choice. This allows us to narrow in on the
right balance without tracking/predicting usable sizes.
Why not weight history of generated filter false positive rates by
number of keys? This could lead to excess skew in small filters after
generating a large filter.
Results from filter_bench with jemalloc (irrelevant details omitted):
(normal keys/filter, but high variance)
$ ./filter_bench -quick -impl=2 -average_keys_per_filter=30000 -vary_key_count_ratio=0.9
Build avg ns/key: 29.6278
Number of filters: 5516
Total size (MB): 200.046
Reported total allocated memory (MB): 220.597
Reported internal fragmentation: 10.2732%
Bits/key stored: 10.0097
Average FP rate %: 0.965228
$ ./filter_bench -quick -impl=2 -average_keys_per_filter=30000 -vary_key_count_ratio=0.9 -optimize_filters_for_memory
Build avg ns/key: 30.5104
Number of filters: 5464
Total size (MB): 200.015
Reported total allocated memory (MB): 200.322
Reported internal fragmentation: 0.153709%
Bits/key stored: 10.1011
Average FP rate %: 0.966313
(very few keys / filter, optimization not as effective due to ~59 byte
internal fragmentation in blocked Bloom filter representation)
$ ./filter_bench -quick -impl=2 -average_keys_per_filter=1000 -vary_key_count_ratio=0.9
Build avg ns/key: 29.5649
Number of filters: 162950
Total size (MB): 200.001
Reported total allocated memory (MB): 224.624
Reported internal fragmentation: 12.3117%
Bits/key stored: 10.2951
Average FP rate %: 0.821534
$ ./filter_bench -quick -impl=2 -average_keys_per_filter=1000 -vary_key_count_ratio=0.9 -optimize_filters_for_memory
Build avg ns/key: 31.8057
Number of filters: 159849
Total size (MB): 200
Reported total allocated memory (MB): 208.846
Reported internal fragmentation: 4.42297%
Bits/key stored: 10.4948
Average FP rate %: 0.811006
(high keys/filter)
$ ./filter_bench -quick -impl=2 -average_keys_per_filter=1000000 -vary_key_count_ratio=0.9
Build avg ns/key: 29.7017
Number of filters: 164
Total size (MB): 200.352
Reported total allocated memory (MB): 221.5
Reported internal fragmentation: 10.5552%
Bits/key stored: 10.0003
Average FP rate %: 0.969358
$ ./filter_bench -quick -impl=2 -average_keys_per_filter=1000000 -vary_key_count_ratio=0.9 -optimize_filters_for_memory
Build avg ns/key: 30.7131
Number of filters: 160
Total size (MB): 200.928
Reported total allocated memory (MB): 200.938
Reported internal fragmentation: 0.00448054%
Bits/key stored: 10.1852
Average FP rate %: 0.963387
And from db_bench (block cache) with jemalloc:
$ ./db_bench -db=/dev/shm/dbbench.no_optimize -benchmarks=fillrandom -format_version=5 -value_size=90 -bloom_bits=10 -num=2000000 -threads=8 -compaction_style=2 -fifo_compaction_max_table_files_size_mb=10000 -fifo_compaction_allow_compaction=false
$ ./db_bench -db=/dev/shm/dbbench -benchmarks=fillrandom -format_version=5 -value_size=90 -bloom_bits=10 -num=2000000 -threads=8 -optimize_filters_for_memory -compaction_style=2 -fifo_compaction_max_table_files_size_mb=10000 -fifo_compaction_allow_compaction=false
$ (for FILE in /dev/shm/dbbench.no_optimize/*.sst; do ./sst_dump --file=$FILE --show_properties | grep 'filter block' ; done) | awk '{ t += $4; } END { print t; }'
17063835
$ (for FILE in /dev/shm/dbbench/*.sst; do ./sst_dump --file=$FILE --show_properties | grep 'filter block' ; done) | awk '{ t += $4; } END { print t; }'
17430747
$ #^ 2.1% additional filter storage
$ ./db_bench -db=/dev/shm/dbbench.no_optimize -use_existing_db -benchmarks=readrandom,stats -statistics -bloom_bits=10 -num=2000000 -compaction_style=2 -fifo_compaction_max_table_files_size_mb=10000 -fifo_compaction_allow_compaction=false -duration=10 -cache_index_and_filter_blocks -cache_size=1000000000
rocksdb.block.cache.index.add COUNT : 33
rocksdb.block.cache.index.bytes.insert COUNT : 8440400
rocksdb.block.cache.filter.add COUNT : 33
rocksdb.block.cache.filter.bytes.insert COUNT : 21087528
rocksdb.bloom.filter.useful COUNT : 4963889
rocksdb.bloom.filter.full.positive COUNT : 1214081
rocksdb.bloom.filter.full.true.positive COUNT : 1161999
$ #^ 1.04 % observed FP rate
$ ./db_bench -db=/dev/shm/dbbench -use_existing_db -benchmarks=readrandom,stats -statistics -bloom_bits=10 -num=2000000 -compaction_style=2 -fifo_compaction_max_table_files_size_mb=10000 -fifo_compaction_allow_compaction=false -optimize_filters_for_memory -duration=10 -cache_index_and_filter_blocks -cache_size=1000000000
rocksdb.block.cache.index.add COUNT : 33
rocksdb.block.cache.index.bytes.insert COUNT : 8448592
rocksdb.block.cache.filter.add COUNT : 33
rocksdb.block.cache.filter.bytes.insert COUNT : 18220328
rocksdb.bloom.filter.useful COUNT : 5360933
rocksdb.bloom.filter.full.positive COUNT : 1321315
rocksdb.bloom.filter.full.true.positive COUNT : 1262999
$ #^ 1.08 % observed FP rate, 13.6% less memory usage for filters
(Due to specific key density, this example tends to generate filters that are "worse than average" for internal fragmentation. "Better than average" cases can show little or no improvement.)
Pull Request resolved: https://github.com/facebook/rocksdb/pull/6427
Test Plan: unit test added, 'make check' with gcc, clang and valgrind
Reviewed By: siying
Differential Revision: D22124374
Pulled By: pdillinger
fbshipit-source-id: f3e3aa152f9043ddf4fae25799e76341d0d8714e
2020-06-22 20:30:57 +00:00
|
|
|
DECLARE_bool(optimize_filters_for_memory);
|
Detect (new) Bloom/Ribbon Filter construction corruption (#9342)
Summary:
Note: rebase on and merge after https://github.com/facebook/rocksdb/pull/9349, https://github.com/facebook/rocksdb/pull/9345, (optional) https://github.com/facebook/rocksdb/pull/9393
**Context:**
(Quoted from pdillinger) Layers of information during new Bloom/Ribbon Filter construction in building block-based tables includes the following:
a) set of keys to add to filter
b) set of hashes to add to filter (64-bit hash applied to each key)
c) set of Bloom indices to set in filter, with duplicates
d) set of Bloom indices to set in filter, deduplicated
e) final filter and its checksum
This PR aims to detect corruption (e.g, unexpected hardware/software corruption on data structures residing in the memory for a long time) from b) to e) and leave a) as future works for application level.
- b)'s corruption is detected by verifying the xor checksum of the hash entries calculated as the entries accumulate before being added to the filter. (i.e, `XXPH3FilterBitsBuilder::MaybeVerifyHashEntriesChecksum()`)
- c) - e)'s corruption is detected by verifying the hash entries indeed exists in the constructed filter by re-querying these hash entries in the filter (i.e, `FilterBitsBuilder::MaybePostVerify()`) after computing the block checksum (except for PartitionFilter, which is done right after each `FilterBitsBuilder::Finish` for impl simplicity - see code comment for more). For this stage of detection, we assume hash entries are not corrupted after checking on b) since the time interval from b) to c) is relatively short IMO.
Option to enable this feature of detection is `BlockBasedTableOptions::detect_filter_construct_corruption` which is false by default.
**Summary:**
- Implemented new functions `XXPH3FilterBitsBuilder::MaybeVerifyHashEntriesChecksum()` and `FilterBitsBuilder::MaybePostVerify()`
- Ensured hash entries, final filter and banding and their [cache reservation ](https://github.com/facebook/rocksdb/issues/9073) are released properly despite corruption
- See [Filter.construction.artifacts.release.point.pdf ](https://github.com/facebook/rocksdb/files/7923487/Design.Filter.construction.artifacts.release.point.pdf) for high-level design
- Bundled and refactored hash entries's related artifact in XXPH3FilterBitsBuilder into `HashEntriesInfo` for better control on lifetime of these artifact during `SwapEntires`, `ResetEntries`
- Ensured RocksDB block-based table builder calls `FilterBitsBuilder::MaybePostVerify()` after constructing the filter by `FilterBitsBuilder::Finish()`
- When encountering such filter construction corruption, stop writing the filter content to files and mark such a block-based table building non-ok by storing the corruption status in the builder.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/9342
Test Plan:
- Added new unit test `DBFilterConstructionCorruptionTestWithParam.DetectCorruption`
- Included this new feature in `DBFilterConstructionReserveMemoryTestWithParam.ReserveMemory` as this feature heavily touch ReserveMemory's impl
- For fallback case, I run `./filter_bench -impl=3 -detect_filter_construct_corruption=true -reserve_table_builder_memory=true -strict_capacity_limit=true -quick -runs 10 | grep 'Build avg'` to make sure nothing break.
- Added to `filter_bench`: increased filter construction time by **30%**, mostly by `MaybePostVerify()`
- FastLocalBloom
- Before change: `./filter_bench -impl=2 -quick -runs 10 | grep 'Build avg'`: **28.86643s**
- After change:
- `./filter_bench -impl=2 -detect_filter_construct_corruption=false -quick -runs 10 | grep 'Build avg'` (expect a tiny increase due to MaybePostVerify is always called regardless): **27.6644s (-4% perf improvement might be due to now we don't drop bloom hash entry in `AddAllEntries` along iteration but in bulk later, same with the bypassing-MaybePostVerify case below)**
- `./filter_bench -impl=2 -detect_filter_construct_corruption=true -quick -runs 10 | grep 'Build avg'` (expect acceptable increase): **34.41159s (+20%)**
- `./filter_bench -impl=2 -detect_filter_construct_corruption=true -quick -runs 10 | grep 'Build avg'` (by-passing MaybePostVerify, expect minor increase): **27.13431s (-6%)**
- Standard128Ribbon
- Before change: `./filter_bench -impl=3 -quick -runs 10 | grep 'Build avg'`: **122.5384s**
- After change:
- `./filter_bench -impl=3 -detect_filter_construct_corruption=false -quick -runs 10 | grep 'Build avg'` (expect a tiny increase due to MaybePostVerify is always called regardless - verified by removing MaybePostVerify under this case and found only +-1ns difference): **124.3588s (+2%)**
- `./filter_bench -impl=3 -detect_filter_construct_corruption=true -quick -runs 10 | grep 'Build avg'`(expect acceptable increase): **159.4946s (+30%)**
- `./filter_bench -impl=3 -detect_filter_construct_corruption=true -quick -runs 10 | grep 'Build avg'`(by-passing MaybePostVerify, expect minor increase) : **125.258s (+2%)**
- Added to `db_stress`: `make crash_test`, `./db_stress --detect_filter_construct_corruption=true`
- Manually smoke-tested: manually corrupted the filter construction in some db level tests with basic PUT and background flush. As expected, the error did get returned to users in subsequent PUT and Flush status.
Reviewed By: pdillinger
Differential Revision: D33746928
Pulled By: hx235
fbshipit-source-id: cb056426be5a7debc1cd16f23bc250f36a08ca57
2022-02-02 01:41:20 +00:00
|
|
|
DECLARE_bool(detect_filter_construct_corruption);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_int32(index_type);
|
2022-06-21 23:23:58 +00:00
|
|
|
DECLARE_int32(data_block_index_type);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_string(db);
|
|
|
|
DECLARE_string(secondaries_base);
|
2019-12-20 16:46:52 +00:00
|
|
|
DECLARE_bool(test_secondary);
|
2021-09-28 21:12:23 +00:00
|
|
|
DECLARE_string(expected_values_dir);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_bool(verify_checksum);
|
|
|
|
DECLARE_bool(mmap_read);
|
|
|
|
DECLARE_bool(mmap_write);
|
|
|
|
DECLARE_bool(use_direct_reads);
|
|
|
|
DECLARE_bool(use_direct_io_for_flush_and_compaction);
|
2020-04-25 06:58:13 +00:00
|
|
|
DECLARE_bool(mock_direct_io);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_bool(statistics);
|
|
|
|
DECLARE_bool(sync);
|
|
|
|
DECLARE_bool(use_fsync);
|
2022-10-06 21:54:21 +00:00
|
|
|
DECLARE_uint64(stats_dump_period_sec);
|
2022-05-05 20:21:03 +00:00
|
|
|
DECLARE_uint64(bytes_per_sync);
|
|
|
|
DECLARE_uint64(wal_bytes_per_sync);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_int32(kill_random_test);
|
2020-06-19 22:26:05 +00:00
|
|
|
DECLARE_string(kill_exclude_prefixes);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_bool(disable_wal);
|
|
|
|
DECLARE_uint64(recycle_log_file_num);
|
|
|
|
DECLARE_int64(target_file_size_base);
|
|
|
|
DECLARE_int32(target_file_size_multiplier);
|
|
|
|
DECLARE_uint64(max_bytes_for_level_base);
|
|
|
|
DECLARE_double(max_bytes_for_level_multiplier);
|
|
|
|
DECLARE_int32(range_deletion_width);
|
|
|
|
DECLARE_uint64(rate_limiter_bytes_per_sec);
|
|
|
|
DECLARE_bool(rate_limit_bg_reads);
|
2022-02-17 07:17:03 +00:00
|
|
|
DECLARE_bool(rate_limit_user_ops);
|
Rate-limit automatic WAL flush after each user write (#9607)
Summary:
**Context:**
WAL flush is currently not rate-limited by `Options::rate_limiter`. This PR is to provide rate-limiting to auto WAL flush, the one that automatically happen after each user write operation (i.e, `Options::manual_wal_flush == false`), by adding `WriteOptions::rate_limiter_options`.
Note that we are NOT rate-limiting WAL flush that do NOT automatically happen after each user write, such as `Options::manual_wal_flush == true + manual FlushWAL()` (rate-limiting multiple WAL flushes), for the benefits of:
- being consistent with [ReadOptions::rate_limiter_priority](https://github.com/facebook/rocksdb/blob/7.0.fb/include/rocksdb/options.h#L515)
- being able to turn off some WAL flush's rate-limiting but not all (e.g, turn off specific the WAL flush of a critical user write like a service's heartbeat)
`WriteOptions::rate_limiter_options` only accept `Env::IO_USER` and `Env::IO_TOTAL` currently due to an implementation constraint.
- The constraint is that we currently queue parallel writes (including WAL writes) based on FIFO policy which does not factor rate limiter priority into this layer's scheduling. If we allow lower priorities such as `Env::IO_HIGH/MID/LOW` and such writes specified with lower priorities occurs before ones specified with higher priorities (even just by a tiny bit in arrival time), the former would have blocked the latter, leading to a "priority inversion" issue and contradictory to what we promise for rate-limiting priority. Therefore we only allow `Env::IO_USER` and `Env::IO_TOTAL` right now before improving that scheduling.
A pre-requisite to this feature is to support operation-level rate limiting in `WritableFileWriter`, which is also included in this PR.
**Summary:**
- Renamed test suite `DBRateLimiterTest to DBRateLimiterOnReadTest` for adding a new test suite
- Accept `rate_limiter_priority` in `WritableFileWriter`'s private and public write functions
- Passed `WriteOptions::rate_limiter_options` to `WritableFileWriter` in the path of automatic WAL flush.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/9607
Test Plan:
- Added new unit test to verify existing flush/compaction rate-limiting does not break, since `DBTest, RateLimitingTest` is disabled and current db-level rate-limiting tests focus on read only (e.g, `db_rate_limiter_test`, `DBTest2, RateLimitedCompactionReads`).
- Added new unit test `DBRateLimiterOnWriteWALTest, AutoWalFlush`
- `strace -ftt -e trace=write ./db_bench -benchmarks=fillseq -db=/dev/shm/testdb -rate_limit_auto_wal_flush=1 -rate_limiter_bytes_per_sec=15 -rate_limiter_refill_period_us=1000000 -write_buffer_size=100000000 -disable_auto_compactions=1 -num=100`
- verified that WAL flush(i.e, system-call _write_) were chunked into 15 bytes and each _write_ was roughly 1 second apart
- verified the chunking disappeared when `-rate_limit_auto_wal_flush=0`
- crash test: `python3 tools/db_crashtest.py blackbox --disable_wal=0 --rate_limit_auto_wal_flush=1 --rate_limiter_bytes_per_sec=10485760 --interval=10` killed as normal
**Benchmarked on flush/compaction to ensure no performance regression:**
- compaction with rate-limiting (see table 1, avg over 1280-run): pre-change: **915635 micros/op**; post-change:
**907350 micros/op (improved by 0.106%)**
```
#!/bin/bash
TEST_TMPDIR=/dev/shm/testdb
START=1
NUM_DATA_ENTRY=8
N=10
rm -f compact_bmk_output.txt compact_bmk_output_2.txt dont_care_output.txt
for i in $(eval echo "{$START..$NUM_DATA_ENTRY}")
do
NUM_RUN=$(($N*(2**($i-1))))
for j in $(eval echo "{$START..$NUM_RUN}")
do
./db_bench --benchmarks=fillrandom -db=$TEST_TMPDIR -disable_auto_compactions=1 -write_buffer_size=6710886 > dont_care_output.txt && ./db_bench --benchmarks=compact -use_existing_db=1 -db=$TEST_TMPDIR -level0_file_num_compaction_trigger=1 -rate_limiter_bytes_per_sec=100000000 | egrep 'compact'
done > compact_bmk_output.txt && awk -v NUM_RUN=$NUM_RUN '{sum+=$3;sum_sqrt+=$3^2}END{print sum/NUM_RUN, sqrt(sum_sqrt/NUM_RUN-(sum/NUM_RUN)^2)}' compact_bmk_output.txt >> compact_bmk_output_2.txt
done
```
- compaction w/o rate-limiting (see table 2, avg over 640-run): pre-change: **822197 micros/op**; post-change: **823148 micros/op (regressed by 0.12%)**
```
Same as above script, except that -rate_limiter_bytes_per_sec=0
```
- flush with rate-limiting (see table 3, avg over 320-run, run on the [patch](https://github.com/hx235/rocksdb/commit/ee5c6023a9f6533fab9afdc681568daa21da4953) to augment current db_bench ): pre-change: **745752 micros/op**; post-change: **745331 micros/op (regressed by 0.06 %)**
```
#!/bin/bash
TEST_TMPDIR=/dev/shm/testdb
START=1
NUM_DATA_ENTRY=8
N=10
rm -f flush_bmk_output.txt flush_bmk_output_2.txt
for i in $(eval echo "{$START..$NUM_DATA_ENTRY}")
do
NUM_RUN=$(($N*(2**($i-1))))
for j in $(eval echo "{$START..$NUM_RUN}")
do
./db_bench -db=$TEST_TMPDIR -write_buffer_size=1048576000 -num=1000000 -rate_limiter_bytes_per_sec=100000000 -benchmarks=fillseq,flush | egrep 'flush'
done > flush_bmk_output.txt && awk -v NUM_RUN=$NUM_RUN '{sum+=$3;sum_sqrt+=$3^2}END{print sum/NUM_RUN, sqrt(sum_sqrt/NUM_RUN-(sum/NUM_RUN)^2)}' flush_bmk_output.txt >> flush_bmk_output_2.txt
done
```
- flush w/o rate-limiting (see table 4, avg over 320-run, run on the [patch](https://github.com/hx235/rocksdb/commit/ee5c6023a9f6533fab9afdc681568daa21da4953) to augment current db_bench): pre-change: **487512 micros/op**, post-change: **485856 micors/ops (improved by 0.34%)**
```
Same as above script, except that -rate_limiter_bytes_per_sec=0
```
| table 1 - compact with rate-limiting|
#-run | (pre-change) avg micros/op | std micros/op | (post-change) avg micros/op | std micros/op | change in avg micros/op (%)
-- | -- | -- | -- | -- | --
10 | 896978 | 16046.9 | 901242 | 15670.9 | 0.475373978
20 | 893718 | 15813 | 886505 | 17544.7 | -0.8070778478
40 | 900426 | 23882.2 | 894958 | 15104.5 | -0.6072681153
80 | 906635 | 21761.5 | 903332 | 23948.3 | -0.3643141948
160 | 898632 | 21098.9 | 907583 | 21145 | 0.9960695813
3.20E+02 | 905252 | 22785.5 | 908106 | 25325.5 | 0.3152713278
6.40E+02 | 905213 | 23598.6 | 906741 | 21370.5 | 0.1688000504
**1.28E+03** | **908316** | **23533.1** | **907350** | **24626.8** | **-0.1063506533**
average over #-run | 901896.25 | 21064.9625 | 901977.125 | 20592.025 | 0.008967217682
| table 2 - compact w/o rate-limiting|
#-run | (pre-change) avg micros/op | std micros/op | (post-change) avg micros/op | std micros/op | change in avg micros/op (%)
-- | -- | -- | -- | -- | --
10 | 811211 | 26996.7 | 807586 | 28456.4 | -0.4468627768
20 | 815465 | 14803.7 | 814608 | 28719.7 | -0.105093413
40 | 809203 | 26187.1 | 797835 | 25492.1 | -1.404839082
80 | 822088 | 28765.3 | 822192 | 32840.4 | 0.01265071379
160 | 821719 | 36344.7 | 821664 | 29544.9 | -0.006693285661
3.20E+02 | 820921 | 27756.4 | 821403 | 28347.7 | 0.05871454135
**6.40E+02** | **822197** | **28960.6** | **823148** | **30055.1** | **0.1156657103**
average over #-run | 8.18E+05 | 2.71E+04 | 8.15E+05 | 2.91E+04 | -0.25
| table 3 - flush with rate-limiting|
#-run | (pre-change) avg micros/op | std micros/op | (post-change) avg micros/op | std micros/op | change in avg micros/op (%)
-- | -- | -- | -- | -- | --
10 | 741721 | 11770.8 | 740345 | 5949.76 | -0.1855144994
20 | 735169 | 3561.83 | 743199 | 9755.77 | 1.09226586
40 | 743368 | 8891.03 | 742102 | 8683.22 | -0.1703059588
80 | 742129 | 8148.51 | 743417 | 9631.58| 0.1735547324
160 | 749045 | 9757.21 | 746256 | 9191.86 | -0.3723407806
**3.20E+02** | **745752** | **9819.65** | **745331** | **9840.62** | **-0.0564530836**
6.40E+02 | 749006 | 11080.5 | 748173 | 10578.7 | -0.1112140624
average over #-run | 743741.4286 | 9004.218571 | 744117.5714 | 9090.215714 | 0.05057441238
| table 4 - flush w/o rate-limiting|
#-run | (pre-change) avg micros/op | std micros/op | (post-change) avg micros/op | std micros/op | change in avg micros/op (%)
-- | -- | -- | -- | -- | --
10 | 477283 | 24719.6 | 473864 | 12379 | -0.7163464863
20 | 486743 | 20175.2 | 502296 | 23931.3 | 3.195320734
40 | 482846 | 15309.2 | 489820 | 22259.5 | 1.444352858
80 | 491490 | 21883.1 | 490071 | 23085.7 | -0.2887139108
160 | 493347 | 28074.3 | 483609 | 21211.7 | -1.973864238
**3.20E+02** | **487512** | **21401.5** | **485856** | **22195.2** | **-0.3396839462**
6.40E+02 | 490307 | 25418.6 | 485435 | 22405.2 | -0.9936631539
average over #-run | 4.87E+05 | 2.24E+04 | 4.87E+05 | 2.11E+04 | 0.00E+00
Reviewed By: ajkr
Differential Revision: D34442441
Pulled By: hx235
fbshipit-source-id: 4790f13e1e5c0a95ae1d1cc93ffcf69dc6e78bdd
2022-03-08 21:19:39 +00:00
|
|
|
DECLARE_bool(rate_limit_auto_wal_flush);
|
2020-02-26 00:43:33 +00:00
|
|
|
DECLARE_uint64(sst_file_manager_bytes_per_sec);
|
|
|
|
DECLARE_uint64(sst_file_manager_bytes_per_truncate);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_int32(backup_one_in);
|
Fix, enable, and enhance backup/restore in db_stress (#7348)
Summary:
Although added to db_stress, testing of backup/restore
was never integrated into the crash test, originally concerned about
performance. I've enabled it now and to address the peformance concern,
testing backup/restore is always skipped once the db exceeds a certain
size threshold, default 100MB. This should provide sufficient
opportunity for testing BackupEngine without bogging down everything
else with heavier and heavier operations.
Also fixed backup/restore in db_stress by making sure PurgeOldBackups
can remove manifest files, which are normally kept around for db_stress.
Added more coverage of backup options, and up to three backups being
saved in one backup directory (in some cases).
Pull Request resolved: https://github.com/facebook/rocksdb/pull/7348
Test Plan:
ran 'make blackbox_crash_test' for a while, with heightened
probabilitly of taking backups (1/10k). Also confirmed with some debug
output that the code is being covered, TestBackupRestore only takes
a few seconds to complete when triggered, and even at 1/10k and ~50MB
database, there's <,~ 1 thread testing backups at any time.
Reviewed By: ajkr
Differential Revision: D23510835
Pulled By: pdillinger
fbshipit-source-id: b6b8735591808141f81f10773ac31634cf03b6c0
2020-09-04 03:11:45 +00:00
|
|
|
DECLARE_uint64(backup_max_size);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_int32(checkpoint_one_in);
|
|
|
|
DECLARE_int32(ingest_external_file_one_in);
|
|
|
|
DECLARE_int32(ingest_external_file_width);
|
|
|
|
DECLARE_int32(compact_files_one_in);
|
|
|
|
DECLARE_int32(compact_range_one_in);
|
2020-08-10 23:16:19 +00:00
|
|
|
DECLARE_int32(mark_for_compaction_one_file_in);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_int32(flush_one_in);
|
2019-12-10 23:45:25 +00:00
|
|
|
DECLARE_int32(pause_background_one_in);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_int32(compact_range_width);
|
|
|
|
DECLARE_int32(acquire_snapshot_one_in);
|
|
|
|
DECLARE_bool(compare_full_db_state_snapshot);
|
|
|
|
DECLARE_uint64(snapshot_hold_ops);
|
2019-12-14 23:17:05 +00:00
|
|
|
DECLARE_bool(long_running_snapshots);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_bool(use_multiget);
|
2023-03-17 21:47:29 +00:00
|
|
|
DECLARE_bool(use_get_entity);
|
2023-03-30 03:35:15 +00:00
|
|
|
DECLARE_bool(use_multi_get_entity);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_int32(readpercent);
|
|
|
|
DECLARE_int32(prefixpercent);
|
|
|
|
DECLARE_int32(writepercent);
|
|
|
|
DECLARE_int32(delpercent);
|
|
|
|
DECLARE_int32(delrangepercent);
|
|
|
|
DECLARE_int32(nooverwritepercent);
|
|
|
|
DECLARE_int32(iterpercent);
|
|
|
|
DECLARE_uint64(num_iterations);
|
2021-12-14 21:33:16 +00:00
|
|
|
DECLARE_int32(customopspercent);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_string(compression_type);
|
2019-12-21 00:13:19 +00:00
|
|
|
DECLARE_string(bottommost_compression_type);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_int32(compression_max_dict_bytes);
|
|
|
|
DECLARE_int32(compression_zstd_max_train_bytes);
|
2020-04-30 17:46:54 +00:00
|
|
|
DECLARE_int32(compression_parallel_threads);
|
Limit buffering for collecting samples for compression dictionary (#7970)
Summary:
For dictionary compression, we need to collect some representative samples of the data to be compressed, which we use to either generate or train (when `CompressionOptions::zstd_max_train_bytes > 0`) a dictionary. Previously, the strategy was to buffer all the data blocks during flush, and up to the target file size during compaction. That strategy allowed us to randomly pick samples from as wide a range as possible that'd be guaranteed to land in a single output file.
However, some users try to make huge files in memory-constrained environments, where this strategy can cause OOM. This PR introduces an option, `CompressionOptions::max_dict_buffer_bytes`, that limits how much data blocks are buffered before we switch to unbuffered mode (which means creating the per-SST dictionary, writing out the buffered data, and compressing/writing new blocks as soon as they are built). It is not strict as we currently buffer more than just data blocks -- also keys are buffered. But it does make a step towards giving users predictable memory usage.
Related changes include:
- Changed sampling for dictionary compression to select unique data blocks when there is limited availability of data blocks
- Made use of `BlockBuilder::SwapAndReset()` to save an allocation+memcpy when buffering data blocks for building a dictionary
- Changed `ParseBoolean()` to accept an input containing characters after the boolean. This is necessary since, with this PR, a value for `CompressionOptions::enabled` is no longer necessarily the final component in the `CompressionOptions` string.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/7970
Test Plan:
- updated `CompressionOptions` unit tests to verify limit is respected (to the extent expected in the current implementation) in various scenarios of flush/compaction to bottommost/non-bottommost level
- looked at jemalloc heap profiles right before and after switching to unbuffered mode during flush/compaction. Verified memory usage in buffering is proportional to the limit set.
Reviewed By: pdillinger
Differential Revision: D26467994
Pulled By: ajkr
fbshipit-source-id: 3da4ef9fba59974e4ef40e40c01611002c861465
2021-02-19 22:06:59 +00:00
|
|
|
DECLARE_uint64(compression_max_dict_buffer_bytes);
|
Support using ZDICT_finalizeDictionary to generate zstd dictionary (#9857)
Summary:
An untrained dictionary is currently simply the concatenation of several samples. The ZSTD API, ZDICT_finalizeDictionary(), can improve such a dictionary's effectiveness at low cost. This PR changes how dictionary is created by calling the ZSTD ZDICT_finalizeDictionary() API instead of creating raw content dictionary (when max_dict_buffer_bytes > 0), and pass in all buffered uncompressed data blocks as samples.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/9857
Test Plan:
#### db_bench test for cpu/memory of compression+decompression and space saving on synthetic data:
Set up: change the parameter [here](https://github.com/facebook/rocksdb/blob/fb9a167a55e0970b1ef6f67c1600c8d9c4c6114f/tools/db_bench_tool.cc#L1766) to 16384 to make synthetic data more compressible.
```
# linked local ZSTD with version 1.5.2
# DEBUG_LEVEL=0 ROCKSDB_NO_FBCODE=1 ROCKSDB_DISABLE_ZSTD=1 EXTRA_CXXFLAGS="-DZSTD_STATIC_LINKING_ONLY -DZSTD -I/data/users/changyubi/install/include/" EXTRA_LDFLAGS="-L/data/users/changyubi/install/lib/ -l:libzstd.a" make -j32 db_bench
dict_bytes=16384
train_bytes=1048576
echo "========== No Dictionary =========="
TEST_TMPDIR=/dev/shm ./db_bench -benchmarks=filluniquerandom,compact -num=10000000 -compression_type=zstd -compression_max_dict_bytes=0 -block_size=4096 -max_background_jobs=24 -memtablerep=vector -allow_concurrent_memtable_write=false -disable_wal=true -max_write_buffer_number=8 >/dev/null 2>&1
TEST_TMPDIR=/dev/shm /usr/bin/time ./db_bench -use_existing_db=true -benchmarks=compact -compression_type=zstd -compression_max_dict_bytes=0 -block_size=4096 2>&1 | grep elapsed
du -hc /dev/shm/dbbench/*sst | grep total
echo "========== Raw Content Dictionary =========="
TEST_TMPDIR=/dev/shm ./db_bench_main -benchmarks=filluniquerandom,compact -num=10000000 -compression_type=zstd -compression_max_dict_bytes=$dict_bytes -block_size=4096 -max_background_jobs=24 -memtablerep=vector -allow_concurrent_memtable_write=false -disable_wal=true -max_write_buffer_number=8 >/dev/null 2>&1
TEST_TMPDIR=/dev/shm /usr/bin/time ./db_bench_main -use_existing_db=true -benchmarks=compact -compression_type=zstd -compression_max_dict_bytes=$dict_bytes -block_size=4096 2>&1 | grep elapsed
du -hc /dev/shm/dbbench/*sst | grep total
echo "========== FinalizeDictionary =========="
TEST_TMPDIR=/dev/shm ./db_bench -benchmarks=filluniquerandom,compact -num=10000000 -compression_type=zstd -compression_max_dict_bytes=$dict_bytes -compression_zstd_max_train_bytes=$train_bytes -compression_use_zstd_dict_trainer=false -block_size=4096 -max_background_jobs=24 -memtablerep=vector -allow_concurrent_memtable_write=false -disable_wal=true -max_write_buffer_number=8 >/dev/null 2>&1
TEST_TMPDIR=/dev/shm /usr/bin/time ./db_bench -use_existing_db=true -benchmarks=compact -compression_type=zstd -compression_max_dict_bytes=$dict_bytes -compression_zstd_max_train_bytes=$train_bytes -compression_use_zstd_dict_trainer=false -block_size=4096 2>&1 | grep elapsed
du -hc /dev/shm/dbbench/*sst | grep total
echo "========== TrainDictionary =========="
TEST_TMPDIR=/dev/shm ./db_bench -benchmarks=filluniquerandom,compact -num=10000000 -compression_type=zstd -compression_max_dict_bytes=$dict_bytes -compression_zstd_max_train_bytes=$train_bytes -block_size=4096 -max_background_jobs=24 -memtablerep=vector -allow_concurrent_memtable_write=false -disable_wal=true -max_write_buffer_number=8 >/dev/null 2>&1
TEST_TMPDIR=/dev/shm /usr/bin/time ./db_bench -use_existing_db=true -benchmarks=compact -compression_type=zstd -compression_max_dict_bytes=$dict_bytes -compression_zstd_max_train_bytes=$train_bytes -block_size=4096 2>&1 | grep elapsed
du -hc /dev/shm/dbbench/*sst | grep total
# Result: TrainDictionary is much better on space saving, but FinalizeDictionary seems to use less memory.
# before compression data size: 1.2GB
dict_bytes=16384
max_dict_buffer_bytes = 1048576
space cpu/memory
No Dictionary 468M 14.93user 1.00system 0:15.92elapsed 100%CPU (0avgtext+0avgdata 23904maxresident)k
Raw Dictionary 251M 15.81user 0.80system 0:16.56elapsed 100%CPU (0avgtext+0avgdata 156808maxresident)k
FinalizeDictionary 236M 11.93user 0.64system 0:12.56elapsed 100%CPU (0avgtext+0avgdata 89548maxresident)k
TrainDictionary 84M 7.29user 0.45system 0:07.75elapsed 100%CPU (0avgtext+0avgdata 97288maxresident)k
```
#### Benchmark on 10 sample SST files for spacing saving and CPU time on compression:
FinalizeDictionary is comparable to TrainDictionary in terms of space saving, and takes less time in compression.
```
dict_bytes=16384
train_bytes=1048576
for sst_file in `ls ../temp/myrock-sst/`
do
echo "********** $sst_file **********"
echo "========== No Dictionary =========="
./sst_dump --file="../temp/myrock-sst/$sst_file" --command=recompress --compression_level_from=6 --compression_level_to=6 --compression_types=kZSTD
echo "========== Raw Content Dictionary =========="
./sst_dump --file="../temp/myrock-sst/$sst_file" --command=recompress --compression_level_from=6 --compression_level_to=6 --compression_types=kZSTD --compression_max_dict_bytes=$dict_bytes
echo "========== FinalizeDictionary =========="
./sst_dump --file="../temp/myrock-sst/$sst_file" --command=recompress --compression_level_from=6 --compression_level_to=6 --compression_types=kZSTD --compression_max_dict_bytes=$dict_bytes --compression_zstd_max_train_bytes=$train_bytes --compression_use_zstd_finalize_dict
echo "========== TrainDictionary =========="
./sst_dump --file="../temp/myrock-sst/$sst_file" --command=recompress --compression_level_from=6 --compression_level_to=6 --compression_types=kZSTD --compression_max_dict_bytes=$dict_bytes --compression_zstd_max_train_bytes=$train_bytes
done
010240.sst (Size/Time) 011029.sst 013184.sst 021552.sst 185054.sst 185137.sst 191666.sst 7560381.sst 7604174.sst 7635312.sst
No Dictionary 28165569 / 2614419 32899411 / 2976832 32977848 / 3055542 31966329 / 2004590 33614351 / 1755877 33429029 / 1717042 33611933 / 1776936 33634045 / 2771417 33789721 / 2205414 33592194 / 388254
Raw Content Dictionary 28019950 / 2697961 33748665 / 3572422 33896373 / 3534701 26418431 / 2259658 28560825 / 1839168 28455030 / 1846039 28494319 / 1861349 32391599 / 3095649 33772142 / 2407843 33592230 / 474523
FinalizeDictionary 27896012 / 2650029 33763886 / 3719427 33904283 / 3552793 26008225 / 2198033 28111872 / 1869530 28014374 / 1789771 28047706 / 1848300 32296254 / 3204027 33698698 / 2381468 33592344 / 517433
TrainDictionary 28046089 / 2740037 33706480 / 3679019 33885741 / 3629351 25087123 / 2204558 27194353 / 1970207 27234229 / 1896811 27166710 / 1903119 32011041 / 3322315 32730692 / 2406146 33608631 / 570593
```
#### Decompression/Read test:
With FinalizeDictionary/TrainDictionary, some data structure used for decompression are in stored in dictionary, so they are expected to be faster in terms of decompression/reads.
```
dict_bytes=16384
train_bytes=1048576
echo "No Dictionary"
TEST_TMPDIR=/dev/shm/ ./db_bench -benchmarks=filluniquerandom,compact -compression_type=zstd -compression_max_dict_bytes=0 > /dev/null 2>&1
TEST_TMPDIR=/dev/shm/ ./db_bench -use_existing_db=true -benchmarks=readrandom -cache_size=0 -compression_type=zstd -compression_max_dict_bytes=0 2>&1 | grep MB/s
echo "Raw Dictionary"
TEST_TMPDIR=/dev/shm/ ./db_bench -benchmarks=filluniquerandom,compact -compression_type=zstd -compression_max_dict_bytes=$dict_bytes > /dev/null 2>&1
TEST_TMPDIR=/dev/shm/ ./db_bench -use_existing_db=true -benchmarks=readrandom -cache_size=0 -compression_type=zstd -compression_max_dict_bytes=$dict_bytes 2>&1 | grep MB/s
echo "FinalizeDict"
TEST_TMPDIR=/dev/shm/ ./db_bench -benchmarks=filluniquerandom,compact -compression_type=zstd -compression_max_dict_bytes=$dict_bytes -compression_zstd_max_train_bytes=$train_bytes -compression_use_zstd_dict_trainer=false > /dev/null 2>&1
TEST_TMPDIR=/dev/shm/ ./db_bench -use_existing_db=true -benchmarks=readrandom -cache_size=0 -compression_type=zstd -compression_max_dict_bytes=$dict_bytes -compression_zstd_max_train_bytes=$train_bytes -compression_use_zstd_dict_trainer=false 2>&1 | grep MB/s
echo "Train Dictionary"
TEST_TMPDIR=/dev/shm/ ./db_bench -benchmarks=filluniquerandom,compact -compression_type=zstd -compression_max_dict_bytes=$dict_bytes -compression_zstd_max_train_bytes=$train_bytes > /dev/null 2>&1
TEST_TMPDIR=/dev/shm/ ./db_bench -use_existing_db=true -benchmarks=readrandom -cache_size=0 -compression_type=zstd -compression_max_dict_bytes=$dict_bytes -compression_zstd_max_train_bytes=$train_bytes 2>&1 | grep MB/s
No Dictionary
readrandom : 12.183 micros/op 82082 ops/sec 12.183 seconds 1000000 operations; 9.1 MB/s (1000000 of 1000000 found)
Raw Dictionary
readrandom : 12.314 micros/op 81205 ops/sec 12.314 seconds 1000000 operations; 9.0 MB/s (1000000 of 1000000 found)
FinalizeDict
readrandom : 9.787 micros/op 102180 ops/sec 9.787 seconds 1000000 operations; 11.3 MB/s (1000000 of 1000000 found)
Train Dictionary
readrandom : 9.698 micros/op 103108 ops/sec 9.699 seconds 1000000 operations; 11.4 MB/s (1000000 of 1000000 found)
```
Reviewed By: ajkr
Differential Revision: D35720026
Pulled By: cbi42
fbshipit-source-id: 24d230fdff0fd28a1bb650658798f00dfcfb2a1f
2022-05-20 19:09:09 +00:00
|
|
|
DECLARE_bool(compression_use_zstd_dict_trainer);
|
Add `CompressionOptions::checksum` for enabling ZSTD checksum (#11666)
Summary:
Optionally enable zstd checksum flag (https://github.com/facebook/zstd/blob/d857369028d997c92ff1f1861a4d7f679a125464/lib/zstd.h#L428) to detect corruption during decompression. Main changes are in compression.h:
* User can set CompressionOptions::checksum to true to enable this feature.
* We enable this feature in ZSTD by setting the checksum flag in ZSTD compression context: `ZSTD_CCtx`.
* Uses `ZSTD_compress2()` to do compression since it supports frame parameter like the checksum flag. Compression level is also set in compression context as a flag.
* Error handling during decompression to propagate error message from ZSTD.
* Updated microbench to test read performance impact.
About compatibility, the current compression decoders should continue to work with the data created by the new compression API `ZSTD_compress2()`: https://github.com/facebook/zstd/issues/3711.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/11666
Test Plan:
* Existing unit tests for zstd compression
* Add unit test `DBTest2.ZSTDChecksum` to test the corruption case
* Manually tested that compression levels, parallel compression, dictionary compression, index compression all work with the new ZSTD_compress2() API.
* Manually tested with `sst_dump --command=recompress` that different compression levels and dictionary compression settings all work.
* Manually tested compiling with older versions of ZSTD: v1.3.8, v1.1.0, v0.6.2.
* Perf impact: from public benchmark data: http://fastcompression.blogspot.com/2019/03/presenting-xxh3.html for checksum and https://github.com/facebook/zstd#benchmarks, if decompression is 1700MB/s and checksum computation is 70000MB/s, checksum computation is an additional ~2.4% time for decompression. Compression is slower and checksumming should be less noticeable.
* Microbench:
```
TEST_TMPDIR=/dev/shm ./branch_db_basic_bench --benchmark_filter=DBGet/comp_style:0/max_data:1048576/per_key_size:256/enable_statistics:0/negative_query:0/enable_filter:0/mmap:0/compression_type:7/compression_checksum:1/no_blockcache:1/iterations:10000/threads:1 --benchmark_repetitions=100
Min out of 100 runs:
Main:
10390 10436 10456 10484 10499 10535 10544 10545 10565 10568
After this PR, checksum=false
10285 10397 10503 10508 10515 10557 10562 10635 10640 10660
After this PR, checksum=true
10827 10876 10925 10949 10971 11052 11061 11063 11100 11109
```
* db_bench:
```
Write perf
TEST_TMPDIR=/dev/shm/ ./db_bench_ichecksum --benchmarks=fillseq[-X10] --compression_type=zstd --num=10000000 --compression_checksum=..
[FillSeq checksum=0]
fillseq [AVG 10 runs] : 281635 (± 31711) ops/sec; 31.2 (± 3.5) MB/sec
fillseq [MEDIAN 10 runs] : 294027 ops/sec; 32.5 MB/sec
[FillSeq checksum=1]
fillseq [AVG 10 runs] : 286961 (± 34700) ops/sec; 31.7 (± 3.8) MB/sec
fillseq [MEDIAN 10 runs] : 283278 ops/sec; 31.3 MB/sec
Read perf
TEST_TMPDIR=/dev/shm ./db_bench_ichecksum --benchmarks=readrandom[-X20] --num=100000000 --reads=1000000 --use_existing_db=true --readonly=1
[Readrandom checksum=1]
readrandom [AVG 20 runs] : 360928 (± 3579) ops/sec; 4.0 (± 0.0) MB/sec
readrandom [MEDIAN 20 runs] : 362468 ops/sec; 4.0 MB/sec
[Readrandom checksum=0]
readrandom [AVG 20 runs] : 380365 (± 2384) ops/sec; 4.2 (± 0.0) MB/sec
readrandom [MEDIAN 20 runs] : 379800 ops/sec; 4.2 MB/sec
Compression
TEST_TMPDIR=/dev/shm ./db_bench_ichecksum --benchmarks=compress[-X20] --compression_type=zstd --num=100000000 --compression_checksum=1
checksum=1
compress [AVG 20 runs] : 54074 (± 634) ops/sec; 211.2 (± 2.5) MB/sec
compress [MEDIAN 20 runs] : 54396 ops/sec; 212.5 MB/sec
checksum=0
compress [AVG 20 runs] : 54598 (± 393) ops/sec; 213.3 (± 1.5) MB/sec
compress [MEDIAN 20 runs] : 54592 ops/sec; 213.3 MB/sec
Decompression:
TEST_TMPDIR=/dev/shm ./db_bench_ichecksum --benchmarks=uncompress[-X20] --compression_type=zstd --compression_checksum=1
checksum = 0
uncompress [AVG 20 runs] : 167499 (± 962) ops/sec; 654.3 (± 3.8) MB/sec
uncompress [MEDIAN 20 runs] : 167210 ops/sec; 653.2 MB/sec
checksum = 1
uncompress [AVG 20 runs] : 167980 (± 924) ops/sec; 656.2 (± 3.6) MB/sec
uncompress [MEDIAN 20 runs] : 168465 ops/sec; 658.1 MB/sec
```
Reviewed By: ajkr
Differential Revision: D48019378
Pulled By: cbi42
fbshipit-source-id: 674120c6e1853c2ced1436ac8138559d0204feba
2023-08-18 22:01:59 +00:00
|
|
|
DECLARE_bool(compression_checksum);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_string(checksum_type);
|
|
|
|
DECLARE_string(env_uri);
|
2020-08-17 18:51:45 +00:00
|
|
|
DECLARE_string(fs_uri);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_uint64(ops_per_thread);
|
|
|
|
DECLARE_uint64(log2_keys_per_lock);
|
|
|
|
DECLARE_uint64(max_manifest_file_size);
|
|
|
|
DECLARE_bool(in_place_update);
|
|
|
|
DECLARE_string(memtablerep);
|
|
|
|
DECLARE_int32(prefix_size);
|
|
|
|
DECLARE_bool(use_merge);
|
Add the PutEntity API to the stress/crash tests (#10760)
Summary:
The patch adds the `PutEntity` API to the non-batched, batched, and
CF consistency stress tests. Namely, when the new `db_stress` command
line parameter `use_put_entity_one_in` is greater than zero, one in
N writes on average is performed using `PutEntity` rather than `Put`.
The wide-column entity written has the generated value in its default
column; in addition, it contains up to three additional columns where
the original generated value is divided up between the column name and the
column value (with the column name containing the first k characters of
the generated value, and the column value containing the rest). Whether
`PutEntity` is used (and if so, how many columns the entity has) is completely
determined by the "value base" used to generate the value (that is, there is
no randomness involved). Assuming the same `use_put_entity_one_in` setting
is used across `db_stress` invocations, this enables us to reconstruct and
validate the entity during subsequent `db_stress` runs.
Note that `PutEntity` is currently incompatible with `Merge`, transactions, and
user-defined timestamps; these combinations are currently disabled/disallowed.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/10760
Test Plan: Ran some batched, non-batched, and CF consistency stress tests using the script.
Reviewed By: riversand963
Differential Revision: D39939032
Pulled By: ltamasi
fbshipit-source-id: eafdf124e95993fb7d73158e3b006d11819f7fa9
2022-09-30 18:11:07 +00:00
|
|
|
DECLARE_uint32(use_put_entity_one_in);
|
2019-12-09 07:49:32 +00:00
|
|
|
DECLARE_bool(use_full_merge_v1);
|
2019-12-11 05:53:43 +00:00
|
|
|
DECLARE_int32(sync_wal_one_in);
|
2019-12-16 23:24:26 +00:00
|
|
|
DECLARE_bool(avoid_unnecessary_blocking_io);
|
|
|
|
DECLARE_bool(write_dbid_to_manifest);
|
2020-04-16 19:09:18 +00:00
|
|
|
DECLARE_bool(avoid_flush_during_recovery);
|
2019-12-16 23:24:26 +00:00
|
|
|
DECLARE_uint64(max_write_batch_group_size_bytes);
|
|
|
|
DECLARE_bool(level_compaction_dynamic_level_bytes);
|
2019-12-18 04:43:06 +00:00
|
|
|
DECLARE_int32(verify_checksum_one_in);
|
Group rocksdb.sst.read.micros stat by different user read IOActivity + misc (#11444)
Summary:
**Context/Summary:**
- Similar to https://github.com/facebook/rocksdb/pull/11288 but for user read such as `Get(), MultiGet(), DBIterator::XXX(), Verify(File)Checksum()`.
- For this, I refactored some user-facing `MultiGet` calls in `TransactionBase` and various types of `DB` so that it does not call a user-facing `Get()` but `GetImpl()` for passing the `ReadOptions::io_activity` check (see PR conversation)
- New user read stats breakdown are guarded by `kExceptDetailedTimers` since measurement shows they have 4-5% regression to the upstream/main.
- Misc
- More refactoring: with https://github.com/facebook/rocksdb/pull/11288, we complete passing `ReadOptions/IOOptions` to FS level. So we can now replace the previously [added](https://github.com/facebook/rocksdb/pull/9424) `rate_limiter_priority` parameter in `RandomAccessFileReader`'s `Read/MultiRead/Prefetch()` with `IOOptions::rate_limiter_priority`
- Also, `ReadAsync()` call time is measured in `SST_READ_MICRO` now
Pull Request resolved: https://github.com/facebook/rocksdb/pull/11444
Test Plan:
- CI fake db crash/stress test
- Microbenchmarking
**Build** `make clean && ROCKSDB_NO_FBCODE=1 DEBUG_LEVEL=0 make -jN db_basic_bench`
- google benchmark version: https://github.com/google/benchmark/commit/604f6fd3f4b34a84ec4eb4db81d842fa4db829cd
- db_basic_bench_base: upstream
- db_basic_bench_pr: db_basic_bench_base + this PR
- asyncread_db_basic_bench_base: upstream + [db basic bench patch for IteratorNext](https://github.com/facebook/rocksdb/compare/main...hx235:rocksdb:micro_bench_async_read)
- asyncread_db_basic_bench_pr: asyncread_db_basic_bench_base + this PR
**Test**
Get
```
TEST_TMPDIR=/dev/shm ./db_basic_bench_{null_stat|base|pr} --benchmark_filter=DBGet/comp_style:0/max_data:134217728/per_key_size:256/enable_statistics:1/negative_query:0/enable_filter:0/mmap:1/threads:1 --benchmark_repetitions=1000
```
Result
```
Coming soon
```
AsyncRead
```
TEST_TMPDIR=/dev/shm ./asyncread_db_basic_bench_{base|pr} --benchmark_filter=IteratorNext/comp_style:0/max_data:134217728/per_key_size:256/enable_statistics:1/async_io:1/include_detailed_timers:0 --benchmark_repetitions=1000 > syncread_db_basic_bench_{base|pr}.out
```
Result
```
Base:
1956,1956,1968,1977,1979,1986,1988,1988,1988,1990,1991,1991,1993,1993,1993,1993,1994,1996,1997,1997,1997,1998,1999,2001,2001,2002,2004,2007,2007,2008,
PR (2.3% regression, due to measuring `SST_READ_MICRO` that wasn't measured before):
1993,2014,2016,2022,2024,2027,2027,2028,2028,2030,2031,2031,2032,2032,2038,2039,2042,2044,2044,2047,2047,2047,2048,2049,2050,2052,2052,2052,2053,2053,
```
Reviewed By: ajkr
Differential Revision: D45918925
Pulled By: hx235
fbshipit-source-id: 58a54560d9ebeb3a59b6d807639692614dad058a
2023-08-09 00:26:50 +00:00
|
|
|
DECLARE_int32(verify_file_checksums_one_in);
|
2019-12-20 16:46:52 +00:00
|
|
|
DECLARE_int32(verify_db_one_in);
|
|
|
|
DECLARE_int32(continuous_verification_interval);
|
2020-07-14 19:10:56 +00:00
|
|
|
DECLARE_int32(get_property_one_in);
|
2020-09-04 06:49:27 +00:00
|
|
|
DECLARE_string(file_checksum_impl);
|
2023-08-23 22:24:23 +00:00
|
|
|
DECLARE_bool(verification_only);
|
2019-12-09 07:49:32 +00:00
|
|
|
|
2023-06-17 23:27:37 +00:00
|
|
|
// Options for transaction dbs.
|
|
|
|
// Use TransactionDB (a.k.a. Pessimistic Transaction DB)
|
|
|
|
// OR OptimisticTransactionDB
|
|
|
|
DECLARE_bool(use_txn);
|
|
|
|
|
|
|
|
// Options for TransactionDB (a.k.a. Pessimistic Transaction DB)
|
|
|
|
DECLARE_uint64(txn_write_policy);
|
|
|
|
DECLARE_bool(unordered_write);
|
|
|
|
|
|
|
|
// Options for OptimisticTransactionDB
|
|
|
|
DECLARE_bool(use_optimistic_txn);
|
|
|
|
DECLARE_uint64(occ_validation_policy);
|
|
|
|
DECLARE_bool(share_occ_lock_buckets);
|
|
|
|
DECLARE_uint32(occ_lock_bucket_count);
|
|
|
|
|
2021-02-02 19:39:20 +00:00
|
|
|
// Options for StackableDB-based BlobDB
|
2019-12-20 18:25:48 +00:00
|
|
|
DECLARE_bool(use_blob_db);
|
|
|
|
DECLARE_uint64(blob_db_min_blob_size);
|
|
|
|
DECLARE_uint64(blob_db_bytes_per_sync);
|
|
|
|
DECLARE_uint64(blob_db_file_size);
|
|
|
|
DECLARE_bool(blob_db_enable_gc);
|
|
|
|
DECLARE_double(blob_db_gc_cutoff);
|
2021-02-02 19:39:20 +00:00
|
|
|
|
|
|
|
// Options for integrated BlobDB
|
|
|
|
DECLARE_bool(allow_setting_blob_options_dynamically);
|
|
|
|
DECLARE_bool(enable_blob_files);
|
|
|
|
DECLARE_uint64(min_blob_size);
|
|
|
|
DECLARE_uint64(blob_file_size);
|
|
|
|
DECLARE_string(blob_compression_type);
|
|
|
|
DECLARE_bool(enable_blob_garbage_collection);
|
|
|
|
DECLARE_double(blob_garbage_collection_age_cutoff);
|
Make it possible to force the garbage collection of the oldest blob files (#8994)
Summary:
The current BlobDB garbage collection logic works by relocating the valid
blobs from the oldest blob files as they are encountered during compaction,
and cleaning up blob files once they contain nothing but garbage. However,
with sufficiently skewed workloads, it is theoretically possible to end up in a
situation when few or no compactions get scheduled for the SST files that contain
references to the oldest blob files, which can lead to increased space amp due
to the lack of GC.
In order to efficiently handle such workloads, the patch adds a new BlobDB
configuration option called `blob_garbage_collection_force_threshold`,
which signals to BlobDB to schedule targeted compactions for the SST files
that keep alive the oldest batch of blob files if the overall ratio of garbage in
the given blob files meets the threshold *and* all the given blob files are
eligible for GC based on `blob_garbage_collection_age_cutoff`. (For example,
if the new option is set to 0.9, targeted compactions will get scheduled if the
sum of garbage bytes meets or exceeds 90% of the sum of total bytes in the
oldest blob files, assuming all affected blob files are below the age-based cutoff.)
The net result of these targeted compactions is that the valid blobs in the oldest
blob files are relocated and the oldest blob files themselves cleaned up (since
*all* SST files that rely on them get compacted away).
These targeted compactions are similar to periodic compactions in the sense
that they force certain SST files that otherwise would not get picked up to undergo
compaction and also in the sense that instead of merging files from multiple levels,
they target a single file. (Note: such compactions might still include neighboring files
from the same level due to the need of having a "clean cut" boundary but they never
include any files from any other level.)
This functionality is currently only supported with the leveled compaction style
and is inactive by default (since the default value is set to 1.0, i.e. 100%).
Pull Request resolved: https://github.com/facebook/rocksdb/pull/8994
Test Plan: Ran `make check` and tested using `db_bench` and the stress/crash tests.
Reviewed By: riversand963
Differential Revision: D31489850
Pulled By: ltamasi
fbshipit-source-id: 44057d511726a0e2a03c5d9313d7511b3f0c4eab
2021-10-12 01:00:44 +00:00
|
|
|
DECLARE_double(blob_garbage_collection_force_threshold);
|
2021-11-20 01:52:42 +00:00
|
|
|
DECLARE_uint64(blob_compaction_readahead_size);
|
2022-06-03 03:04:33 +00:00
|
|
|
DECLARE_int32(blob_file_starting_level);
|
2022-06-22 23:04:03 +00:00
|
|
|
DECLARE_bool(use_blob_cache);
|
|
|
|
DECLARE_bool(use_shared_block_and_blob_cache);
|
|
|
|
DECLARE_uint64(blob_cache_size);
|
|
|
|
DECLARE_int32(blob_cache_numshardbits);
|
2022-07-17 14:13:59 +00:00
|
|
|
DECLARE_int32(prepopulate_blob_cache);
|
2021-02-02 19:39:20 +00:00
|
|
|
|
2019-12-21 05:42:19 +00:00
|
|
|
DECLARE_int32(approximate_size_one_in);
|
2020-04-16 18:10:53 +00:00
|
|
|
DECLARE_bool(sync_fault_injection);
|
2019-12-20 18:25:48 +00:00
|
|
|
|
2020-06-13 02:24:11 +00:00
|
|
|
DECLARE_bool(best_efforts_recovery);
|
|
|
|
DECLARE_bool(skip_verifydb);
|
2020-06-18 16:51:14 +00:00
|
|
|
DECLARE_bool(enable_compaction_filter);
|
2020-09-30 21:39:47 +00:00
|
|
|
DECLARE_bool(paranoid_file_checks);
|
2021-05-05 19:53:42 +00:00
|
|
|
DECLARE_bool(fail_if_options_file_error);
|
Integrity protection for live updates to WriteBatch (#7748)
Summary:
This PR adds the foundation classes for key-value integrity protection and the first use case: protecting live updates from the source buffers added to `WriteBatch` through the destination buffer in `MemTable`. The width of the protection info is not yet configurable -- only eight bytes per key is supported. This PR allows users to enable protection by constructing `WriteBatch` with `protection_bytes_per_key == 8`. It does not yet expose a way for users to get integrity protection via other write APIs (e.g., `Put()`, `Merge()`, `Delete()`, etc.).
The foundation classes (`ProtectionInfo.*`) embed the coverage info in their type, and provide `Protect.*()` and `Strip.*()` functions to navigate between types with different coverage. For making bytes per key configurable (for powers of two up to eight) in the future, these classes are templated on the unsigned integer type used to store the protection info. That integer contains the XOR'd result of hashes with independent seeds for all covered fields. For integer fields, the hash is computed on the raw unadjusted bytes, so the result is endian-dependent. The most significant bytes are truncated when the hash value (8 bytes) is wider than the protection integer.
When `WriteBatch` is constructed with `protection_bytes_per_key == 8`, we hold a `ProtectionInfoKVOTC` (i.e., one that covers key, value, optype aka `ValueType`, timestamp, and CF ID) for each entry added to the batch. The protection info is generated from the original buffers passed by the user, as well as the original metadata generated internally. When writing to memtable, each entry is transformed to a `ProtectionInfoKVOTS` (i.e., dropping coverage of CF ID and adding coverage of sequence number), since at that point we know the sequence number, and have already selected a memtable corresponding to a particular CF. This protection info is verified once the entry is encoded in the `MemTable` buffer.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/7748
Test Plan:
- an integration test to verify a wide variety of single-byte changes to the encoded `MemTable` buffer are caught
- add to stress/crash test to verify it works in variety of configs/operations without intentional corruption
- [deferred] unit tests for `ProtectionInfo.*` classes for edge cases like KV swap, `SliceParts` and `Slice` APIs are interchangeable, etc.
Reviewed By: pdillinger
Differential Revision: D25754492
Pulled By: ajkr
fbshipit-source-id: e481bac6c03c2ab268be41359730f1ceb9964866
2021-01-29 20:17:17 +00:00
|
|
|
DECLARE_uint64(batch_protection_bytes_per_key);
|
2022-08-12 20:51:32 +00:00
|
|
|
DECLARE_uint32(memtable_protection_bytes_per_key);
|
2023-04-25 19:08:23 +00:00
|
|
|
DECLARE_uint32(block_protection_bytes_per_key);
|
2020-06-13 02:24:11 +00:00
|
|
|
|
Add user-defined timestamps to db_stress (#8061)
Summary:
Add some basic test for user-defined timestamp to db_stress. Currently,
read with timestamp always tries to read using the current timestamp.
Due to the per-key timestamp-sequence ordering constraint, we only add timestamp-
related tests to the `NonBatchedOpsStressTest` since this test serializes accesses
to the same key and uses a file to cross-check data correctness.
The timestamp feature is not supported in a number of components, e.g. Merge, SingleDelete,
DeleteRange, CompactionFilter, Readonly instance, secondary instance, SST file ingestion, transaction,
etc. Therefore, db_stress should exit if user enables both timestamp and these features at the same
time. The (currently) incompatible features can be found in
`CheckAndSetOptionsForUserTimestamp`.
This PR also fixes a bug triggered when timestamp is enabled together with
`index_type=kBinarySearchWithFirstKey`. This bug fix will also be in another separate PR
with more unit tests coverage. Fixing it here because I do not want to exclude the index type
from crash test.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/8061
Test Plan: make crash_test_with_ts
Reviewed By: jay-zhuang
Differential Revision: D27056282
Pulled By: riversand963
fbshipit-source-id: c3e00ad1023fdb9ebbdf9601ec18270c5e2925a9
2021-03-23 12:12:04 +00:00
|
|
|
DECLARE_uint64(user_timestamp_size);
|
2021-06-28 06:53:47 +00:00
|
|
|
DECLARE_string(secondary_cache_uri);
|
2021-11-08 18:26:48 +00:00
|
|
|
DECLARE_int32(secondary_cache_fault_one_in);
|
Add user-defined timestamps to db_stress (#8061)
Summary:
Add some basic test for user-defined timestamp to db_stress. Currently,
read with timestamp always tries to read using the current timestamp.
Due to the per-key timestamp-sequence ordering constraint, we only add timestamp-
related tests to the `NonBatchedOpsStressTest` since this test serializes accesses
to the same key and uses a file to cross-check data correctness.
The timestamp feature is not supported in a number of components, e.g. Merge, SingleDelete,
DeleteRange, CompactionFilter, Readonly instance, secondary instance, SST file ingestion, transaction,
etc. Therefore, db_stress should exit if user enables both timestamp and these features at the same
time. The (currently) incompatible features can be found in
`CheckAndSetOptionsForUserTimestamp`.
This PR also fixes a bug triggered when timestamp is enabled together with
`index_type=kBinarySearchWithFirstKey`. This bug fix will also be in another separate PR
with more unit tests coverage. Fixing it here because I do not want to exclude the index type
from crash test.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/8061
Test Plan: make crash_test_with_ts
Reviewed By: jay-zhuang
Differential Revision: D27056282
Pulled By: riversand963
fbshipit-source-id: c3e00ad1023fdb9ebbdf9601ec18270c5e2925a9
2021-03-23 12:12:04 +00:00
|
|
|
|
2021-12-08 20:43:09 +00:00
|
|
|
DECLARE_int32(prepopulate_block_cache);
|
|
|
|
|
2022-03-17 02:00:04 +00:00
|
|
|
DECLARE_bool(two_write_queues);
|
|
|
|
DECLARE_bool(use_only_the_last_commit_time_batch_for_recovery);
|
|
|
|
DECLARE_uint64(wp_snapshot_cache_bits);
|
|
|
|
DECLARE_uint64(wp_commit_cache_bits);
|
|
|
|
|
2022-03-30 20:52:37 +00:00
|
|
|
DECLARE_bool(adaptive_readahead);
|
|
|
|
DECLARE_bool(async_io);
|
2022-04-06 22:47:09 +00:00
|
|
|
DECLARE_string(wal_compression);
|
2022-05-19 18:04:21 +00:00
|
|
|
DECLARE_bool(verify_sst_unique_id_in_manifest);
|
2022-03-30 20:52:37 +00:00
|
|
|
|
Snapshots with user-specified timestamps (#9879)
Summary:
In RocksDB, keys are associated with (internal) sequence numbers which denote when the keys are written
to the database. Sequence numbers in different RocksDB instances are unrelated, thus not comparable.
It is nice if we can associate sequence numbers with their corresponding actual timestamps. One thing we can
do is to support user-defined timestamp, which allows the applications to specify the format of custom timestamps
and encode a timestamp with each key. More details can be found at https://github.com/facebook/rocksdb/wiki/User-defined-Timestamp-%28Experimental%29.
This PR provides a different but complementary approach. We can associate rocksdb snapshots (defined in
https://github.com/facebook/rocksdb/blob/7.2.fb/include/rocksdb/snapshot.h#L20) with **user-specified** timestamps.
Since a snapshot is essentially an object representing a sequence number, this PR establishes a bi-directional mapping between sequence numbers and timestamps.
In the past, snapshots are usually taken by readers. The current super-version is grabbed, and a `rocksdb::Snapshot`
object is created with the last published sequence number of the super-version. You can see that the reader actually
has no good idea of what timestamp to assign to this snapshot, because by the time the `GetSnapshot()` is called,
an arbitrarily long period of time may have already elapsed since the last write, which is when the last published
sequence number is written.
This observation motivates the creation of "timestamped" snapshots on the write path. Currently, this functionality is
exposed only to the layer of `TransactionDB`. Application can tell RocksDB to create a snapshot when a transaction
commits, effectively associating the last sequence number with a timestamp. It is also assumed that application will
ensure any two snapshots with timestamps should satisfy the following:
```
snapshot1.seq < snapshot2.seq iff. snapshot1.ts < snapshot2.ts
```
If the application can guarantee that when a reader takes a timestamped snapshot, there is no active writes going on
in the database, then we also allow the user to use a new API `TransactionDB::CreateTimestampedSnapshot()` to create
a snapshot with associated timestamp.
Code example
```cpp
// Create a timestamped snapshot when committing transaction.
txn->SetCommitTimestamp(100);
txn->SetSnapshotOnNextOperation();
txn->Commit();
// A wrapper API for convenience
Status Transaction::CommitAndTryCreateSnapshot(
std::shared_ptr<TransactionNotifier> notifier,
TxnTimestamp ts,
std::shared_ptr<const Snapshot>* ret);
// Create a timestamped snapshot if caller guarantees no concurrent writes
std::pair<Status, std::shared_ptr<const Snapshot>> snapshot = txn_db->CreateTimestampedSnapshot(100);
```
The snapshots created in this way will be managed by RocksDB with ref-counting and potentially shared with
other readers. We provide the following APIs for readers to retrieve a snapshot given a timestamp.
```cpp
// Return the timestamped snapshot correponding to given timestamp. If ts is
// kMaxTxnTimestamp, then we return the latest timestamped snapshot if present.
// Othersise, we return the snapshot whose timestamp is equal to `ts`. If no
// such snapshot exists, then we return null.
std::shared_ptr<const Snapshot> TransactionDB::GetTimestampedSnapshot(TxnTimestamp ts) const;
// Return the latest timestamped snapshot if present.
std::shared_ptr<const Snapshot> TransactionDB::GetLatestTimestampedSnapshot() const;
```
We also provide two additional APIs for stats collection and reporting purposes.
```cpp
Status TransactionDB::GetAllTimestampedSnapshots(
std::vector<std::shared_ptr<const Snapshot>>& snapshots) const;
// Return timestamped snapshots whose timestamps fall in [ts_lb, ts_ub) and store them in `snapshots`.
Status TransactionDB::GetTimestampedSnapshots(
TxnTimestamp ts_lb,
TxnTimestamp ts_ub,
std::vector<std::shared_ptr<const Snapshot>>& snapshots) const;
```
To prevent the number of timestamped snapshots from growing infinitely, we provide the following API to release
timestamped snapshots whose timestamps are older than or equal to a given threshold.
```cpp
void TransactionDB::ReleaseTimestampedSnapshotsOlderThan(TxnTimestamp ts);
```
Before shutdown, RocksDB will release all timestamped snapshots.
Comparison with user-defined timestamp and how they can be combined:
User-defined timestamp persists every key with a timestamp, while timestamped snapshots maintain a volatile
mapping between snapshots (sequence numbers) and timestamps.
Different internal keys with the same user key but different timestamps will be treated as different by compaction,
thus a newer version will not hide older versions (with smaller timestamps) unless they are eligible for garbage collection.
In contrast, taking a timestamped snapshot at a certain sequence number and timestamp prevents all the keys visible in
this snapshot from been dropped by compaction. Here, visible means (seq < snapshot and most recent).
The timestamped snapshot supports the semantics of reading at an exact point in time.
Timestamped snapshots can also be used with user-defined timestamp.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/9879
Test Plan:
```
make check
TEST_TMPDIR=/dev/shm make crash_test_with_txn
```
Reviewed By: siying
Differential Revision: D35783919
Pulled By: riversand963
fbshipit-source-id: 586ad905e169189e19d3bfc0cb0177a7239d1bd4
2022-06-10 23:07:03 +00:00
|
|
|
DECLARE_int32(create_timestamped_snapshot_one_in);
|
|
|
|
|
2022-06-15 19:38:04 +00:00
|
|
|
DECLARE_bool(allow_data_in_errors);
|
|
|
|
|
2023-04-21 16:07:18 +00:00
|
|
|
DECLARE_bool(enable_thread_tracking);
|
|
|
|
|
2023-08-03 02:58:56 +00:00
|
|
|
DECLARE_uint32(memtable_max_range_deletions);
|
|
|
|
|
Delay bottommost level single file compactions (#11701)
Summary:
For leveled compaction, RocksDB has a special kind of compaction with reason "kBottommmostFiles" that compacts bottommost level files to clear data held by snapshots (more detail in https://github.com/facebook/rocksdb/issues/3009). Such compactions can happen soon after a relevant snapshot is released. For some use cases, a bottommost file may contain only a small amount of keys that can be cleared, so compacting such a file has a high write amp. In addition, these bottommost files may be compacted in compactions with reason other than "kBottommmostFiles" if we wait for some time (so that enough data is ingested to trigger such a compaction). This PR introduces an option `bottommost_file_compaction_delay` to specify the delay of these bottommost level single file compactions.
* The main change is in `VersionStorageInfo::ComputeBottommostFilesMarkedForCompaction()` where we only add a file to `bottommost_files_marked_for_compaction_` if it oldest_snapshot is larger than its non-zero largest_seqno **and** the file is old enough. Note that if a file is not old enough but its largest_seqno is less than oldest_snapshot, we exclude it from the calculation of `bottommost_files_mark_threshold_`. This makes the change simpler, but such a file's eligibility for compaction will only be checked the next time `ComputeBottommostFilesMarkedForCompaction()` is called. This happens when a new Version is created (compaction, flush, SetOptions()...), a new enough snapshot is released (`VersionStorageInfo::UpdateOldestSnapshot()`) or when a compaction is picked and compaction score has to be re-calculated.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/11701
Test Plan:
* Add two unit tests to test when bottommost_file_compaction_delay > 0.
* Ran crash test with the new option.
Reviewed By: jaykorean, ajkr
Differential Revision: D48331564
Pulled By: cbi42
fbshipit-source-id: c584f3dc5f6354fce3ed65f4c6366dc450b15ba8
2023-08-17 00:45:44 +00:00
|
|
|
DECLARE_uint32(bottommost_file_compaction_delay);
|
|
|
|
|
2022-08-08 20:08:35 +00:00
|
|
|
// Tiered storage
|
|
|
|
DECLARE_bool(enable_tiered_storage); // set last_level_temperature
|
|
|
|
DECLARE_int64(preclude_last_level_data_seconds);
|
2022-10-16 16:28:43 +00:00
|
|
|
DECLARE_int64(preserve_internal_time_seconds);
|
2022-08-08 20:08:35 +00:00
|
|
|
|
Add Iterator test against expected state to stress test (#10538)
Summary:
As mentioned in https://github.com/facebook/rocksdb/pull/5506#issuecomment-506021913,
`db_stress` does not have much verification for iterator correctness.
It has a `TestIterate()` function, but that is mainly for comparing results
between two iterators, one with `total_order_seek` and the other optionally
sets auto_prefix, upper/lower bounds. Commit 49a0581ad2462e31aa3f768afa769e0d33390f33
added a new `TestIterateAgainstExpected()` function that compares iterator against
expected state. It locks a range of keys, creates an iterator, does
a random sequence of `Next/Prev` and compares against expected state.
This PR is based on that commit, the main changes include some logs
(for easier debugging if a test fails), a forward and backward scan to
cover the entire locked key range, and a flag for optionally turning on
this version of Iterator testing.
Added constraint that the checks against expected state in
`TestIterateAgainstExpected()` and in `TestGet()` are only turned on
when `--skip_verifydb` flag is not set.
Remove the change log introduced in https://github.com/facebook/rocksdb/issues/10553.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/10538
Test Plan:
Run `db_stress` with `--verify_iterator_with_expected_state_one_in=1`,
and a large `--iterpercent` and `--num_iterations`. Checked `op_logs`
manually to ensure expected coverage. Tweaked part of the code in
https://github.com/facebook/rocksdb/issues/10449 and stress test was able to catch it.
- internally run various flavor of crash test
Reviewed By: ajkr
Differential Revision: D38847269
Pulled By: cbi42
fbshipit-source-id: 8b4402a9bba9f6cfa08051943cd672579d489599
2022-08-24 21:59:50 +00:00
|
|
|
DECLARE_int32(verify_iterator_with_expected_state_one_in);
|
db_stress option to preserve all files until verification success (#10659)
Summary:
In `db_stress`, DB and expected state files containing changes leading up to a verification failure are often deleted, which makes debugging such failures difficult. On the DB side, flushed WAL files and compacted SST files are marked obsolete and then deleted. Without those files, we cannot pinpoint where a key that failed verification changed unexpectedly. On the expected state side, files for verifying prefix-recoverability in the presence of unsynced data loss are deleted before verification. These include a baseline state file containing the expected state at the time of the last successful verification, and a trace file containing all operations since then. Without those files, we cannot know the sequence of DB operations expected to be recovered.
This PR attempts to address this gap with a new `db_stress` flag: `preserve_unverified_changes`. Setting `preserve_unverified_changes=1` has two effects.
First, prior to startup verification, `db_stress` hardlinks all DB and expected state files in "unverified/" subdirectories of `FLAGS_db` and `FLAGS_expected_values_dir`. The separate directories are needed because the pre-verification opening process deletes files written by the previous `db_stress` run as described above. These "unverified/" subdirectories are cleaned up following startup verification success.
I considered other approaches for preserving DB files through startup verification, like using a read-only DB or preventing deletion of DB files externally, e.g., in the `Env` layer. However, I decided against it since such an approach would not work for expected state files, and I did not want to change the DB management logic. If there were a way to disable DB file deletions before regular DB open, I would have preferred to use that.
Second, `db_stress` attempts to keep all DB and expected state files that were live at some point since the start of the `db_stress` run. This is a bit tricky and involves the following changes.
- Open the DB with `disable_auto_compactions=1` and `avoid_flush_during_recovery=1`
- DisableFileDeletions()
- EnableAutoCompactions()
For this part, too, I would have preferred to use a hypothetical API that disables DB file deletion before regular DB open.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/10659
Reviewed By: hx235
Differential Revision: D39407454
Pulled By: ajkr
fbshipit-source-id: 6e981025c7dce147649d2e770728471395a7fa53
2022-09-12 21:49:38 +00:00
|
|
|
DECLARE_bool(preserve_unverified_changes);
|
Add Iterator test against expected state to stress test (#10538)
Summary:
As mentioned in https://github.com/facebook/rocksdb/pull/5506#issuecomment-506021913,
`db_stress` does not have much verification for iterator correctness.
It has a `TestIterate()` function, but that is mainly for comparing results
between two iterators, one with `total_order_seek` and the other optionally
sets auto_prefix, upper/lower bounds. Commit 49a0581ad2462e31aa3f768afa769e0d33390f33
added a new `TestIterateAgainstExpected()` function that compares iterator against
expected state. It locks a range of keys, creates an iterator, does
a random sequence of `Next/Prev` and compares against expected state.
This PR is based on that commit, the main changes include some logs
(for easier debugging if a test fails), a forward and backward scan to
cover the entire locked key range, and a flag for optionally turning on
this version of Iterator testing.
Added constraint that the checks against expected state in
`TestIterateAgainstExpected()` and in `TestGet()` are only turned on
when `--skip_verifydb` flag is not set.
Remove the change log introduced in https://github.com/facebook/rocksdb/issues/10553.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/10538
Test Plan:
Run `db_stress` with `--verify_iterator_with_expected_state_one_in=1`,
and a large `--iterpercent` and `--num_iterations`. Checked `op_logs`
manually to ensure expected coverage. Tweaked part of the code in
https://github.com/facebook/rocksdb/issues/10449 and stress test was able to catch it.
- internally run various flavor of crash test
Reviewed By: ajkr
Differential Revision: D38847269
Pulled By: cbi42
fbshipit-source-id: 8b4402a9bba9f6cfa08051943cd672579d489599
2022-08-24 21:59:50 +00:00
|
|
|
|
2022-09-09 19:52:27 +00:00
|
|
|
DECLARE_uint64(readahead_size);
|
|
|
|
DECLARE_uint64(initial_auto_readahead_size);
|
|
|
|
DECLARE_uint64(max_auto_readahead_size);
|
|
|
|
DECLARE_uint64(num_file_reads_for_auto_readahead);
|
2023-02-21 20:53:55 +00:00
|
|
|
DECLARE_bool(use_io_uring);
|
2023-08-24 21:58:27 +00:00
|
|
|
DECLARE_bool(auto_readahead_size);
|
2022-09-09 19:52:27 +00:00
|
|
|
|
Add user-defined timestamps to db_stress (#8061)
Summary:
Add some basic test for user-defined timestamp to db_stress. Currently,
read with timestamp always tries to read using the current timestamp.
Due to the per-key timestamp-sequence ordering constraint, we only add timestamp-
related tests to the `NonBatchedOpsStressTest` since this test serializes accesses
to the same key and uses a file to cross-check data correctness.
The timestamp feature is not supported in a number of components, e.g. Merge, SingleDelete,
DeleteRange, CompactionFilter, Readonly instance, secondary instance, SST file ingestion, transaction,
etc. Therefore, db_stress should exit if user enables both timestamp and these features at the same
time. The (currently) incompatible features can be found in
`CheckAndSetOptionsForUserTimestamp`.
This PR also fixes a bug triggered when timestamp is enabled together with
`index_type=kBinarySearchWithFirstKey`. This bug fix will also be in another separate PR
with more unit tests coverage. Fixing it here because I do not want to exclude the index type
from crash test.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/8061
Test Plan: make crash_test_with_ts
Reviewed By: jay-zhuang
Differential Revision: D27056282
Pulled By: riversand963
fbshipit-source-id: c3e00ad1023fdb9ebbdf9601ec18270c5e2925a9
2021-03-23 12:12:04 +00:00
|
|
|
constexpr long KB = 1024;
|
|
|
|
constexpr int kRandomValueMaxFactor = 3;
|
|
|
|
constexpr int kValueMaxLen = 100;
|
2019-12-09 07:49:32 +00:00
|
|
|
|
2022-01-25 03:56:37 +00:00
|
|
|
// wrapped posix environment
|
2020-12-17 19:51:04 +00:00
|
|
|
extern ROCKSDB_NAMESPACE::Env* db_stress_env;
|
2022-01-25 23:56:08 +00:00
|
|
|
extern ROCKSDB_NAMESPACE::Env* db_stress_listener_env;
|
2020-04-11 00:18:56 +00:00
|
|
|
extern std::shared_ptr<ROCKSDB_NAMESPACE::FaultInjectionTestFS> fault_fs_guard;
|
2019-12-09 07:49:32 +00:00
|
|
|
|
2020-02-20 20:07:53 +00:00
|
|
|
extern enum ROCKSDB_NAMESPACE::CompressionType compression_type_e;
|
|
|
|
extern enum ROCKSDB_NAMESPACE::CompressionType bottommost_compression_type_e;
|
|
|
|
extern enum ROCKSDB_NAMESPACE::ChecksumType checksum_type_e;
|
2019-12-09 07:49:32 +00:00
|
|
|
|
|
|
|
enum RepFactory { kSkipList, kHashSkipList, kVectorRep };
|
|
|
|
|
|
|
|
inline enum RepFactory StringToRepFactory(const char* ctype) {
|
|
|
|
assert(ctype);
|
|
|
|
|
|
|
|
if (!strcasecmp(ctype, "skip_list"))
|
|
|
|
return kSkipList;
|
|
|
|
else if (!strcasecmp(ctype, "prefix_hash"))
|
|
|
|
return kHashSkipList;
|
|
|
|
else if (!strcasecmp(ctype, "vector"))
|
|
|
|
return kVectorRep;
|
|
|
|
|
|
|
|
fprintf(stdout, "Cannot parse memreptable %s\n", ctype);
|
|
|
|
return kSkipList;
|
|
|
|
}
|
|
|
|
|
|
|
|
extern enum RepFactory FLAGS_rep_factory;
|
|
|
|
|
2020-02-20 20:07:53 +00:00
|
|
|
namespace ROCKSDB_NAMESPACE {
|
|
|
|
inline enum ROCKSDB_NAMESPACE::CompressionType StringToCompressionType(
|
2019-12-09 07:49:32 +00:00
|
|
|
const char* ctype) {
|
|
|
|
assert(ctype);
|
|
|
|
|
2020-02-20 20:07:53 +00:00
|
|
|
ROCKSDB_NAMESPACE::CompressionType ret_compression_type;
|
2019-12-09 07:49:32 +00:00
|
|
|
|
2019-12-21 00:13:19 +00:00
|
|
|
if (!strcasecmp(ctype, "disable")) {
|
2020-02-20 20:07:53 +00:00
|
|
|
ret_compression_type = ROCKSDB_NAMESPACE::kDisableCompressionOption;
|
2019-12-21 00:13:19 +00:00
|
|
|
} else if (!strcasecmp(ctype, "none")) {
|
2020-02-20 20:07:53 +00:00
|
|
|
ret_compression_type = ROCKSDB_NAMESPACE::kNoCompression;
|
2019-12-21 00:13:19 +00:00
|
|
|
} else if (!strcasecmp(ctype, "snappy")) {
|
2020-02-20 20:07:53 +00:00
|
|
|
ret_compression_type = ROCKSDB_NAMESPACE::kSnappyCompression;
|
2019-12-21 00:13:19 +00:00
|
|
|
} else if (!strcasecmp(ctype, "zlib")) {
|
2020-02-20 20:07:53 +00:00
|
|
|
ret_compression_type = ROCKSDB_NAMESPACE::kZlibCompression;
|
2019-12-21 00:13:19 +00:00
|
|
|
} else if (!strcasecmp(ctype, "bzip2")) {
|
2020-02-20 20:07:53 +00:00
|
|
|
ret_compression_type = ROCKSDB_NAMESPACE::kBZip2Compression;
|
2019-12-21 00:13:19 +00:00
|
|
|
} else if (!strcasecmp(ctype, "lz4")) {
|
2020-02-20 20:07:53 +00:00
|
|
|
ret_compression_type = ROCKSDB_NAMESPACE::kLZ4Compression;
|
2019-12-21 00:13:19 +00:00
|
|
|
} else if (!strcasecmp(ctype, "lz4hc")) {
|
2020-02-20 20:07:53 +00:00
|
|
|
ret_compression_type = ROCKSDB_NAMESPACE::kLZ4HCCompression;
|
2019-12-21 00:13:19 +00:00
|
|
|
} else if (!strcasecmp(ctype, "xpress")) {
|
2020-02-20 20:07:53 +00:00
|
|
|
ret_compression_type = ROCKSDB_NAMESPACE::kXpressCompression;
|
2019-12-21 00:13:19 +00:00
|
|
|
} else if (!strcasecmp(ctype, "zstd")) {
|
2020-02-20 20:07:53 +00:00
|
|
|
ret_compression_type = ROCKSDB_NAMESPACE::kZSTD;
|
2019-12-21 00:13:19 +00:00
|
|
|
} else {
|
|
|
|
fprintf(stderr, "Cannot parse compression type '%s'\n", ctype);
|
2020-02-20 20:07:53 +00:00
|
|
|
ret_compression_type =
|
|
|
|
ROCKSDB_NAMESPACE::kSnappyCompression; // default value
|
2019-12-21 00:13:19 +00:00
|
|
|
}
|
2020-02-20 20:07:53 +00:00
|
|
|
if (ret_compression_type != ROCKSDB_NAMESPACE::kDisableCompressionOption &&
|
2019-12-21 00:13:19 +00:00
|
|
|
!CompressionTypeSupported(ret_compression_type)) {
|
|
|
|
// Use no compression will be more portable but considering this is
|
|
|
|
// only a stress test and snappy is widely available. Use snappy here.
|
2020-02-20 20:07:53 +00:00
|
|
|
ret_compression_type = ROCKSDB_NAMESPACE::kSnappyCompression;
|
2019-12-21 00:13:19 +00:00
|
|
|
}
|
|
|
|
return ret_compression_type;
|
2019-12-09 07:49:32 +00:00
|
|
|
}
|
|
|
|
|
2020-02-20 20:07:53 +00:00
|
|
|
inline enum ROCKSDB_NAMESPACE::ChecksumType StringToChecksumType(
|
|
|
|
const char* ctype) {
|
2019-12-09 07:49:32 +00:00
|
|
|
assert(ctype);
|
2020-02-20 20:07:53 +00:00
|
|
|
auto iter = ROCKSDB_NAMESPACE::checksum_type_string_map.find(ctype);
|
|
|
|
if (iter != ROCKSDB_NAMESPACE::checksum_type_string_map.end()) {
|
2019-12-09 07:49:32 +00:00
|
|
|
return iter->second;
|
|
|
|
}
|
|
|
|
fprintf(stderr, "Cannot parse checksum type '%s'\n", ctype);
|
2020-02-20 20:07:53 +00:00
|
|
|
return ROCKSDB_NAMESPACE::kCRC32c;
|
2019-12-09 07:49:32 +00:00
|
|
|
}
|
|
|
|
|
2020-02-20 20:07:53 +00:00
|
|
|
inline std::string ChecksumTypeToString(ROCKSDB_NAMESPACE::ChecksumType ctype) {
|
2019-12-09 07:49:32 +00:00
|
|
|
auto iter = std::find_if(
|
2020-02-20 20:07:53 +00:00
|
|
|
ROCKSDB_NAMESPACE::checksum_type_string_map.begin(),
|
|
|
|
ROCKSDB_NAMESPACE::checksum_type_string_map.end(),
|
|
|
|
[&](const std::pair<std::string, ROCKSDB_NAMESPACE::ChecksumType>&
|
2019-12-09 07:49:32 +00:00
|
|
|
name_and_enum_val) { return name_and_enum_val.second == ctype; });
|
2020-02-20 20:07:53 +00:00
|
|
|
assert(iter != ROCKSDB_NAMESPACE::checksum_type_string_map.end());
|
2019-12-09 07:49:32 +00:00
|
|
|
return iter->first;
|
|
|
|
}
|
|
|
|
|
|
|
|
inline std::vector<std::string> SplitString(std::string src) {
|
|
|
|
std::vector<std::string> ret;
|
|
|
|
if (src.empty()) {
|
|
|
|
return ret;
|
|
|
|
}
|
|
|
|
size_t pos = 0;
|
|
|
|
size_t pos_comma;
|
|
|
|
while ((pos_comma = src.find(',', pos)) != std::string::npos) {
|
|
|
|
ret.push_back(src.substr(pos, pos_comma - pos));
|
|
|
|
pos = pos_comma + 1;
|
|
|
|
}
|
|
|
|
ret.push_back(src.substr(pos, src.length()));
|
|
|
|
return ret;
|
|
|
|
}
|
|
|
|
|
|
|
|
#ifdef _MSC_VER
|
|
|
|
#pragma warning(push)
|
|
|
|
// truncation of constant value on static_cast
|
|
|
|
#pragma warning(disable : 4309)
|
|
|
|
#endif
|
2020-02-20 20:07:53 +00:00
|
|
|
inline bool GetNextPrefix(const ROCKSDB_NAMESPACE::Slice& src, std::string* v) {
|
2019-12-09 07:49:32 +00:00
|
|
|
std::string ret = src.ToString();
|
|
|
|
for (int i = static_cast<int>(ret.size()) - 1; i >= 0; i--) {
|
|
|
|
if (ret[i] != static_cast<char>(255)) {
|
|
|
|
ret[i] = ret[i] + 1;
|
|
|
|
break;
|
|
|
|
} else if (i != 0) {
|
|
|
|
ret[i] = 0;
|
|
|
|
} else {
|
|
|
|
// all FF. No next prefix
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
*v = ret;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
#ifdef _MSC_VER
|
|
|
|
#pragma warning(pop)
|
|
|
|
#endif
|
|
|
|
|
2022-02-01 19:46:12 +00:00
|
|
|
// Append `val` to `*key` in fixed-width big-endian format
|
|
|
|
extern inline void AppendIntToString(uint64_t val, std::string* key) {
|
|
|
|
// PutFixed64 uses little endian
|
|
|
|
PutFixed64(key, val);
|
|
|
|
// Reverse to get big endian
|
|
|
|
char* int_data = &((*key)[key->size() - sizeof(uint64_t)]);
|
|
|
|
for (size_t i = 0; i < sizeof(uint64_t) / 2; ++i) {
|
|
|
|
std::swap(int_data[i], int_data[sizeof(uint64_t) - 1 - i]);
|
2019-12-09 07:49:32 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-10 05:25:40 +00:00
|
|
|
// A struct for maintaining the parameters for generating variable length keys
|
|
|
|
struct KeyGenContext {
|
|
|
|
// Number of adjacent keys in one cycle of key lengths
|
|
|
|
uint64_t window;
|
|
|
|
// Number of keys of each possible length in a given window
|
|
|
|
std::vector<uint64_t> weights;
|
|
|
|
};
|
|
|
|
extern KeyGenContext key_gen_ctx;
|
|
|
|
|
|
|
|
// Generate a variable length key string from the given int64 val. The
|
|
|
|
// order of the keys is preserved. The key could be anywhere from 8 to
|
|
|
|
// max_key_len * 8 bytes.
|
|
|
|
// The algorithm picks the length based on the
|
|
|
|
// offset of the val within a configured window and the distribution of the
|
|
|
|
// number of keys of various lengths in that window. For example, if x, y, x are
|
|
|
|
// the weights assigned to each possible key length, the keys generated would be
|
|
|
|
// - {0}...{x-1}
|
|
|
|
// {(x-1),0}..{(x-1),(y-1)},{(x-1),(y-1),0}..{(x-1),(y-1),(z-1)} and so on.
|
|
|
|
// Additionally, a trailer of 0-7 bytes could be appended.
|
|
|
|
extern inline std::string Key(int64_t val) {
|
|
|
|
uint64_t window = key_gen_ctx.window;
|
|
|
|
size_t levels = key_gen_ctx.weights.size();
|
|
|
|
std::string key;
|
2022-02-01 19:46:12 +00:00
|
|
|
// Over-reserve and for now do not bother `shrink_to_fit()` since the key
|
|
|
|
// strings are transient.
|
|
|
|
key.reserve(FLAGS_max_key_len * 8);
|
2020-01-10 05:25:40 +00:00
|
|
|
|
2022-02-01 19:46:12 +00:00
|
|
|
uint64_t window_idx = static_cast<uint64_t>(val) / window;
|
|
|
|
uint64_t offset = static_cast<uint64_t>(val) % window;
|
2020-01-10 05:25:40 +00:00
|
|
|
for (size_t level = 0; level < levels; ++level) {
|
|
|
|
uint64_t weight = key_gen_ctx.weights[level];
|
2022-02-01 19:46:12 +00:00
|
|
|
uint64_t pfx;
|
|
|
|
if (level == 0) {
|
|
|
|
pfx = window_idx * weight;
|
|
|
|
} else {
|
|
|
|
pfx = 0;
|
|
|
|
}
|
|
|
|
pfx += offset >= weight ? weight - 1 : offset;
|
|
|
|
AppendIntToString(pfx, &key);
|
2020-01-10 05:25:40 +00:00
|
|
|
if (offset < weight) {
|
|
|
|
// Use the bottom 3 bits of offset as the number of trailing 'x's in the
|
|
|
|
// key. If the next key is going to be of the next level, then skip the
|
2022-10-25 21:29:41 +00:00
|
|
|
// trailer as it would break ordering. If the key length is already at
|
|
|
|
// max, skip the trailer.
|
2020-01-10 05:25:40 +00:00
|
|
|
if (offset < weight - 1 && level < levels - 1) {
|
|
|
|
size_t trailer_len = offset & 0x7;
|
|
|
|
key.append(trailer_len, 'x');
|
|
|
|
}
|
|
|
|
break;
|
|
|
|
}
|
2022-02-01 19:46:12 +00:00
|
|
|
offset -= weight;
|
2020-01-10 05:25:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return key;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Given a string key, map it to an index into the expected values buffer
|
2019-12-09 07:49:32 +00:00
|
|
|
extern inline bool GetIntVal(std::string big_endian_key, uint64_t* key_p) {
|
2020-01-10 05:25:40 +00:00
|
|
|
size_t size_key = big_endian_key.size();
|
|
|
|
std::vector<uint64_t> prefixes;
|
|
|
|
|
|
|
|
assert(size_key <= key_gen_ctx.weights.size() * sizeof(uint64_t));
|
|
|
|
|
2019-12-09 07:49:32 +00:00
|
|
|
std::string little_endian_key;
|
|
|
|
little_endian_key.resize(size_key);
|
2020-06-18 16:51:14 +00:00
|
|
|
for (size_t start = 0; start + sizeof(uint64_t) <= size_key;
|
|
|
|
start += sizeof(uint64_t)) {
|
2020-01-10 05:25:40 +00:00
|
|
|
size_t end = start + sizeof(uint64_t);
|
|
|
|
for (size_t i = 0; i < sizeof(uint64_t); ++i) {
|
|
|
|
little_endian_key[start + i] = big_endian_key[end - 1 - i];
|
|
|
|
}
|
|
|
|
Slice little_endian_slice =
|
|
|
|
Slice(&little_endian_key[start], sizeof(uint64_t));
|
|
|
|
uint64_t pfx;
|
|
|
|
if (!GetFixed64(&little_endian_slice, &pfx)) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
prefixes.emplace_back(pfx);
|
|
|
|
}
|
|
|
|
|
|
|
|
uint64_t key = 0;
|
|
|
|
for (size_t i = 0; i < prefixes.size(); ++i) {
|
|
|
|
uint64_t pfx = prefixes[i];
|
|
|
|
key += (pfx / key_gen_ctx.weights[i]) * key_gen_ctx.window +
|
|
|
|
pfx % key_gen_ctx.weights[i];
|
2020-06-18 16:51:14 +00:00
|
|
|
if (i < prefixes.size() - 1) {
|
|
|
|
// The encoding writes a `key_gen_ctx.weights[i] - 1` that counts for
|
|
|
|
// `key_gen_ctx.weights[i]` when there are more prefixes to come. So we
|
|
|
|
// need to add back the one here as we're at a non-last prefix.
|
|
|
|
++key;
|
|
|
|
}
|
2019-12-09 07:49:32 +00:00
|
|
|
}
|
2020-01-10 05:25:40 +00:00
|
|
|
*key_p = key;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2020-06-18 16:51:14 +00:00
|
|
|
// Given a string prefix, map it to the first corresponding index in the
|
|
|
|
// expected values buffer.
|
|
|
|
inline bool GetFirstIntValInPrefix(std::string big_endian_prefix,
|
|
|
|
uint64_t* key_p) {
|
|
|
|
size_t size_key = big_endian_prefix.size();
|
|
|
|
// Pad with zeros to make it a multiple of 8. This function may be called
|
|
|
|
// with a prefix, in which case we return the first index that falls
|
|
|
|
// inside or outside that prefix, dependeing on whether the prefix is
|
|
|
|
// the start of upper bound of a scan
|
|
|
|
unsigned int pad = sizeof(uint64_t) - (size_key % sizeof(uint64_t));
|
|
|
|
if (pad < sizeof(uint64_t)) {
|
|
|
|
big_endian_prefix.append(pad, '\0');
|
|
|
|
}
|
|
|
|
return GetIntVal(std::move(big_endian_prefix), key_p);
|
|
|
|
}
|
|
|
|
|
2020-01-10 05:25:40 +00:00
|
|
|
extern inline uint64_t GetPrefixKeyCount(const std::string& prefix,
|
|
|
|
const std::string& ub) {
|
|
|
|
uint64_t start = 0;
|
|
|
|
uint64_t end = 0;
|
|
|
|
|
2020-06-18 16:51:14 +00:00
|
|
|
if (!GetFirstIntValInPrefix(prefix, &start) ||
|
|
|
|
!GetFirstIntValInPrefix(ub, &end)) {
|
2020-01-10 05:25:40 +00:00
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
return end - start;
|
2019-12-09 07:49:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
extern inline std::string StringToHex(const std::string& str) {
|
|
|
|
std::string result = "0x";
|
|
|
|
result.append(Slice(str).ToString(true));
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2023-03-17 21:47:29 +00:00
|
|
|
inline std::string WideColumnsToHex(const WideColumns& columns) {
|
|
|
|
if (columns.empty()) {
|
|
|
|
return std::string();
|
|
|
|
}
|
|
|
|
|
|
|
|
std::ostringstream oss;
|
|
|
|
|
|
|
|
oss << std::hex;
|
|
|
|
|
|
|
|
auto it = columns.begin();
|
|
|
|
oss << *it;
|
|
|
|
for (++it; it != columns.end(); ++it) {
|
|
|
|
oss << ' ' << *it;
|
|
|
|
}
|
|
|
|
|
|
|
|
return oss.str();
|
|
|
|
}
|
|
|
|
|
2019-12-10 16:38:23 +00:00
|
|
|
// Unified output format for double parameters
|
|
|
|
extern inline std::string FormatDoubleParam(double param) {
|
|
|
|
return std::to_string(param);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Make sure that double parameter is a value we can reproduce by
|
|
|
|
// re-inputting the value printed.
|
|
|
|
extern inline void SanitizeDoubleParam(double* param) {
|
|
|
|
*param = std::atof(FormatDoubleParam(*param).c_str());
|
|
|
|
}
|
|
|
|
|
2019-12-09 07:49:32 +00:00
|
|
|
extern void PoolSizeChangeThread(void* v);
|
|
|
|
|
2019-12-20 16:46:52 +00:00
|
|
|
extern void DbVerificationThread(void* v);
|
Snapshots with user-specified timestamps (#9879)
Summary:
In RocksDB, keys are associated with (internal) sequence numbers which denote when the keys are written
to the database. Sequence numbers in different RocksDB instances are unrelated, thus not comparable.
It is nice if we can associate sequence numbers with their corresponding actual timestamps. One thing we can
do is to support user-defined timestamp, which allows the applications to specify the format of custom timestamps
and encode a timestamp with each key. More details can be found at https://github.com/facebook/rocksdb/wiki/User-defined-Timestamp-%28Experimental%29.
This PR provides a different but complementary approach. We can associate rocksdb snapshots (defined in
https://github.com/facebook/rocksdb/blob/7.2.fb/include/rocksdb/snapshot.h#L20) with **user-specified** timestamps.
Since a snapshot is essentially an object representing a sequence number, this PR establishes a bi-directional mapping between sequence numbers and timestamps.
In the past, snapshots are usually taken by readers. The current super-version is grabbed, and a `rocksdb::Snapshot`
object is created with the last published sequence number of the super-version. You can see that the reader actually
has no good idea of what timestamp to assign to this snapshot, because by the time the `GetSnapshot()` is called,
an arbitrarily long period of time may have already elapsed since the last write, which is when the last published
sequence number is written.
This observation motivates the creation of "timestamped" snapshots on the write path. Currently, this functionality is
exposed only to the layer of `TransactionDB`. Application can tell RocksDB to create a snapshot when a transaction
commits, effectively associating the last sequence number with a timestamp. It is also assumed that application will
ensure any two snapshots with timestamps should satisfy the following:
```
snapshot1.seq < snapshot2.seq iff. snapshot1.ts < snapshot2.ts
```
If the application can guarantee that when a reader takes a timestamped snapshot, there is no active writes going on
in the database, then we also allow the user to use a new API `TransactionDB::CreateTimestampedSnapshot()` to create
a snapshot with associated timestamp.
Code example
```cpp
// Create a timestamped snapshot when committing transaction.
txn->SetCommitTimestamp(100);
txn->SetSnapshotOnNextOperation();
txn->Commit();
// A wrapper API for convenience
Status Transaction::CommitAndTryCreateSnapshot(
std::shared_ptr<TransactionNotifier> notifier,
TxnTimestamp ts,
std::shared_ptr<const Snapshot>* ret);
// Create a timestamped snapshot if caller guarantees no concurrent writes
std::pair<Status, std::shared_ptr<const Snapshot>> snapshot = txn_db->CreateTimestampedSnapshot(100);
```
The snapshots created in this way will be managed by RocksDB with ref-counting and potentially shared with
other readers. We provide the following APIs for readers to retrieve a snapshot given a timestamp.
```cpp
// Return the timestamped snapshot correponding to given timestamp. If ts is
// kMaxTxnTimestamp, then we return the latest timestamped snapshot if present.
// Othersise, we return the snapshot whose timestamp is equal to `ts`. If no
// such snapshot exists, then we return null.
std::shared_ptr<const Snapshot> TransactionDB::GetTimestampedSnapshot(TxnTimestamp ts) const;
// Return the latest timestamped snapshot if present.
std::shared_ptr<const Snapshot> TransactionDB::GetLatestTimestampedSnapshot() const;
```
We also provide two additional APIs for stats collection and reporting purposes.
```cpp
Status TransactionDB::GetAllTimestampedSnapshots(
std::vector<std::shared_ptr<const Snapshot>>& snapshots) const;
// Return timestamped snapshots whose timestamps fall in [ts_lb, ts_ub) and store them in `snapshots`.
Status TransactionDB::GetTimestampedSnapshots(
TxnTimestamp ts_lb,
TxnTimestamp ts_ub,
std::vector<std::shared_ptr<const Snapshot>>& snapshots) const;
```
To prevent the number of timestamped snapshots from growing infinitely, we provide the following API to release
timestamped snapshots whose timestamps are older than or equal to a given threshold.
```cpp
void TransactionDB::ReleaseTimestampedSnapshotsOlderThan(TxnTimestamp ts);
```
Before shutdown, RocksDB will release all timestamped snapshots.
Comparison with user-defined timestamp and how they can be combined:
User-defined timestamp persists every key with a timestamp, while timestamped snapshots maintain a volatile
mapping between snapshots (sequence numbers) and timestamps.
Different internal keys with the same user key but different timestamps will be treated as different by compaction,
thus a newer version will not hide older versions (with smaller timestamps) unless they are eligible for garbage collection.
In contrast, taking a timestamped snapshot at a certain sequence number and timestamp prevents all the keys visible in
this snapshot from been dropped by compaction. Here, visible means (seq < snapshot and most recent).
The timestamped snapshot supports the semantics of reading at an exact point in time.
Timestamped snapshots can also be used with user-defined timestamp.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/9879
Test Plan:
```
make check
TEST_TMPDIR=/dev/shm make crash_test_with_txn
```
Reviewed By: siying
Differential Revision: D35783919
Pulled By: riversand963
fbshipit-source-id: 586ad905e169189e19d3bfc0cb0177a7239d1bd4
2022-06-10 23:07:03 +00:00
|
|
|
|
2022-07-11 19:44:08 +00:00
|
|
|
extern void TimestampedSnapshotsThread(void* v);
|
2019-12-20 16:46:52 +00:00
|
|
|
|
2019-12-09 07:49:32 +00:00
|
|
|
extern void PrintKeyValue(int cf, uint64_t key, const char* value, size_t sz);
|
|
|
|
|
|
|
|
extern int64_t GenerateOneKey(ThreadState* thread, uint64_t iteration);
|
|
|
|
|
|
|
|
extern std::vector<int64_t> GenerateNKeys(ThreadState* thread, int num_keys,
|
|
|
|
uint64_t iteration);
|
|
|
|
|
|
|
|
extern size_t GenerateValue(uint32_t rand, char* v, size_t max_sz);
|
2021-12-15 20:53:32 +00:00
|
|
|
extern uint32_t GetValueBase(Slice s);
|
2019-12-09 07:49:32 +00:00
|
|
|
|
Add the PutEntity API to the stress/crash tests (#10760)
Summary:
The patch adds the `PutEntity` API to the non-batched, batched, and
CF consistency stress tests. Namely, when the new `db_stress` command
line parameter `use_put_entity_one_in` is greater than zero, one in
N writes on average is performed using `PutEntity` rather than `Put`.
The wide-column entity written has the generated value in its default
column; in addition, it contains up to three additional columns where
the original generated value is divided up between the column name and the
column value (with the column name containing the first k characters of
the generated value, and the column value containing the rest). Whether
`PutEntity` is used (and if so, how many columns the entity has) is completely
determined by the "value base" used to generate the value (that is, there is
no randomness involved). Assuming the same `use_put_entity_one_in` setting
is used across `db_stress` invocations, this enables us to reconstruct and
validate the entity during subsequent `db_stress` runs.
Note that `PutEntity` is currently incompatible with `Merge`, transactions, and
user-defined timestamps; these combinations are currently disabled/disallowed.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/10760
Test Plan: Ran some batched, non-batched, and CF consistency stress tests using the script.
Reviewed By: riversand963
Differential Revision: D39939032
Pulled By: ltamasi
fbshipit-source-id: eafdf124e95993fb7d73158e3b006d11819f7fa9
2022-09-30 18:11:07 +00:00
|
|
|
extern WideColumns GenerateWideColumns(uint32_t value_base, const Slice& slice);
|
|
|
|
extern WideColumns GenerateExpectedWideColumns(uint32_t value_base,
|
|
|
|
const Slice& slice);
|
2023-03-17 21:47:29 +00:00
|
|
|
extern bool VerifyWideColumns(const Slice& value, const WideColumns& columns);
|
|
|
|
extern bool VerifyWideColumns(const WideColumns& columns);
|
Add the PutEntity API to the stress/crash tests (#10760)
Summary:
The patch adds the `PutEntity` API to the non-batched, batched, and
CF consistency stress tests. Namely, when the new `db_stress` command
line parameter `use_put_entity_one_in` is greater than zero, one in
N writes on average is performed using `PutEntity` rather than `Put`.
The wide-column entity written has the generated value in its default
column; in addition, it contains up to three additional columns where
the original generated value is divided up between the column name and the
column value (with the column name containing the first k characters of
the generated value, and the column value containing the rest). Whether
`PutEntity` is used (and if so, how many columns the entity has) is completely
determined by the "value base" used to generate the value (that is, there is
no randomness involved). Assuming the same `use_put_entity_one_in` setting
is used across `db_stress` invocations, this enables us to reconstruct and
validate the entity during subsequent `db_stress` runs.
Note that `PutEntity` is currently incompatible with `Merge`, transactions, and
user-defined timestamps; these combinations are currently disabled/disallowed.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/10760
Test Plan: Ran some batched, non-batched, and CF consistency stress tests using the script.
Reviewed By: riversand963
Differential Revision: D39939032
Pulled By: ltamasi
fbshipit-source-id: eafdf124e95993fb7d73158e3b006d11819f7fa9
2022-09-30 18:11:07 +00:00
|
|
|
|
2019-12-09 07:49:32 +00:00
|
|
|
extern StressTest* CreateCfConsistencyStressTest();
|
|
|
|
extern StressTest* CreateBatchedOpsStressTest();
|
|
|
|
extern StressTest* CreateNonBatchedOpsStressTest();
|
2021-12-14 21:33:16 +00:00
|
|
|
extern StressTest* CreateMultiOpsTxnsStressTest();
|
|
|
|
extern void CheckAndSetOptionsForMultiOpsTxnStressTest();
|
2019-12-16 21:59:21 +00:00
|
|
|
extern void InitializeHotKeyGenerator(double alpha);
|
|
|
|
extern int64_t GetOneHotKeyID(double rand_seed, int64_t max_key);
|
2020-09-04 06:49:27 +00:00
|
|
|
|
2022-07-05 20:30:15 +00:00
|
|
|
extern std::string GetNowNanos();
|
Add user-defined timestamps to db_stress (#8061)
Summary:
Add some basic test for user-defined timestamp to db_stress. Currently,
read with timestamp always tries to read using the current timestamp.
Due to the per-key timestamp-sequence ordering constraint, we only add timestamp-
related tests to the `NonBatchedOpsStressTest` since this test serializes accesses
to the same key and uses a file to cross-check data correctness.
The timestamp feature is not supported in a number of components, e.g. Merge, SingleDelete,
DeleteRange, CompactionFilter, Readonly instance, secondary instance, SST file ingestion, transaction,
etc. Therefore, db_stress should exit if user enables both timestamp and these features at the same
time. The (currently) incompatible features can be found in
`CheckAndSetOptionsForUserTimestamp`.
This PR also fixes a bug triggered when timestamp is enabled together with
`index_type=kBinarySearchWithFirstKey`. This bug fix will also be in another separate PR
with more unit tests coverage. Fixing it here because I do not want to exclude the index type
from crash test.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/8061
Test Plan: make crash_test_with_ts
Reviewed By: jay-zhuang
Differential Revision: D27056282
Pulled By: riversand963
fbshipit-source-id: c3e00ad1023fdb9ebbdf9601ec18270c5e2925a9
2021-03-23 12:12:04 +00:00
|
|
|
|
2020-09-04 06:49:27 +00:00
|
|
|
std::shared_ptr<FileChecksumGenFactory> GetFileChecksumImpl(
|
|
|
|
const std::string& name);
|
db_stress option to preserve all files until verification success (#10659)
Summary:
In `db_stress`, DB and expected state files containing changes leading up to a verification failure are often deleted, which makes debugging such failures difficult. On the DB side, flushed WAL files and compacted SST files are marked obsolete and then deleted. Without those files, we cannot pinpoint where a key that failed verification changed unexpectedly. On the expected state side, files for verifying prefix-recoverability in the presence of unsynced data loss are deleted before verification. These include a baseline state file containing the expected state at the time of the last successful verification, and a trace file containing all operations since then. Without those files, we cannot know the sequence of DB operations expected to be recovered.
This PR attempts to address this gap with a new `db_stress` flag: `preserve_unverified_changes`. Setting `preserve_unverified_changes=1` has two effects.
First, prior to startup verification, `db_stress` hardlinks all DB and expected state files in "unverified/" subdirectories of `FLAGS_db` and `FLAGS_expected_values_dir`. The separate directories are needed because the pre-verification opening process deletes files written by the previous `db_stress` run as described above. These "unverified/" subdirectories are cleaned up following startup verification success.
I considered other approaches for preserving DB files through startup verification, like using a read-only DB or preventing deletion of DB files externally, e.g., in the `Env` layer. However, I decided against it since such an approach would not work for expected state files, and I did not want to change the DB management logic. If there were a way to disable DB file deletions before regular DB open, I would have preferred to use that.
Second, `db_stress` attempts to keep all DB and expected state files that were live at some point since the start of the `db_stress` run. This is a bit tricky and involves the following changes.
- Open the DB with `disable_auto_compactions=1` and `avoid_flush_during_recovery=1`
- DisableFileDeletions()
- EnableAutoCompactions()
For this part, too, I would have preferred to use a hypothetical API that disables DB file deletion before regular DB open.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/10659
Reviewed By: hx235
Differential Revision: D39407454
Pulled By: ajkr
fbshipit-source-id: 6e981025c7dce147649d2e770728471395a7fa53
2022-09-12 21:49:38 +00:00
|
|
|
|
|
|
|
Status DeleteFilesInDirectory(const std::string& dirname);
|
|
|
|
Status SaveFilesInDirectory(const std::string& src_dirname,
|
|
|
|
const std::string& dst_dirname);
|
|
|
|
Status DestroyUnverifiedSubdir(const std::string& dirname);
|
|
|
|
Status InitUnverifiedSubdir(const std::string& dirname);
|
2020-02-20 20:07:53 +00:00
|
|
|
} // namespace ROCKSDB_NAMESPACE
|
2019-12-09 07:49:32 +00:00
|
|
|
#endif // GFLAGS
|